import { env } from "cloudflare:workers"; import { hostKey, isForgeHost, manifestKey, objectKey, pagesDomain, slotKey } from "./config"; import type { Manifest, ManifestFile, SitePointer } from "./config"; const POINTER_CACHE_SECONDS = 60; const MANIFEST_CACHE_SECONDS = 3600; const HTTP_OK = 200; const PREVIEW_PREFIX = /^\/_pr\/(\d+)(\/.*)?$/; const CONTENT_TYPES: Record = { html: "text/html; charset=utf-8", htm: "text/html; charset=utf-8", css: "text/css; charset=utf-8", js: "text/javascript; charset=utf-8", mjs: "text/javascript; charset=utf-8", json: "application/json", map: "application/json", webmanifest: "application/manifest+json", txt: "text/plain; charset=utf-8", md: "text/plain; charset=utf-8", xml: "application/xml", svg: "image/svg+xml", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", ico: "image/x-icon", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", wasm: "application/wasm", pdf: "application/pdf", mp4: "video/mp4", webm: "video/webm", mp3: "audio/mpeg", wav: "audio/wav", }; /** Headers for untrusted user content; served on a separate registrable domain from the forge. */ export const SECURITY_HEADERS: Record = { "x-content-type-options": "nosniff", "strict-transport-security": "max-age=31536000; includeSubDomains", "referrer-policy": "strict-origin-when-cross-origin", "cross-origin-opener-policy": "same-origin", "cross-origin-resource-policy": "same-site", "content-security-policy": "frame-ancestors 'self'; base-uri 'self'; form-action 'self' https:", "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()", "x-robots-tag": "noarchive", }; type Target = { slot: string; path: string; base: string }; export function contentType(path: string): string { const extension = path.slice(path.lastIndexOf(".") + 1).toLowerCase(); return CONTENT_TYPES[extension] ?? "application/octet-stream"; } function plain(status: number, body: string): Response { return new Response(body, { status, headers: { ...SECURITY_HEADERS, "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }, }); } function redirect(location: string): Response { return new Response(null, { status: 308, headers: { ...SECURITY_HEADERS, location } }); } function pointer(slot: string): Promise { return env.KV.get(slot, { type: "json", cacheTtl: POINTER_CACHE_SECONDS }); } function withPreview(base: string, slot: string, path: string): Target { const preview = PREVIEW_PREFIX.exec(path); if (!preview) return { slot, path, base }; return { slot: `${slot}#pr-${preview[1]}`, path: preview[2] ?? "", base: `${base}_pr/${preview[1]}/` }; } async function ownerTarget(owner: string, host: string, pathname: string): Promise { const [, first = "", ...rest] = pathname.split("/"); if (first && first.toLowerCase() !== host) { const repo = decodeURIComponent(first); const slot = slotKey(owner, repo, null); if (await pointer(slot)) { if (rest.length === 0) return redirect(`/${first}/`); return withPreview(`/${first}/`, slot, `/${rest.join("/")}`); } } return withPreview("/", slotKey(owner, host, null), pathname); } async function resolveTarget(hostname: string, pathname: string): Promise { const domain = pagesDomain(); if (!domain) return null; if (hostname.endsWith(`.${domain}`)) { const owner = hostname.slice(0, -domain.length - 1); if (!owner || owner.includes(".")) return plain(404, "Site not found"); return ownerTarget(owner, hostname, pathname); } if (hostname === domain) return plain(404, "Site not found"); if (isForgeHost(hostname)) return null; const mapped = await env.KV.get<{ owner: string; repo: string }>(hostKey(hostname), { type: "json", cacheTtl: POINTER_CACHE_SECONDS, }); if (!mapped) return null; return { slot: slotKey(mapped.owner, mapped.repo, null), path: pathname, base: "/" }; } export function decodePath(path: string): string | null { try { const decoded = decodeURIComponent(path).replace(/^\/+/, ""); return decoded.split("/").some((part) => part === "..") ? null : decoded; } catch { return null; } } type Lookup = { path: string; file: ManifestFile; status: number } | { redirect: string } | null; export function lookup(manifest: Manifest, spa: boolean, path: string, base: string): Lookup { const files = manifest.files; const direct = path === "" || path.endsWith("/") ? `${path}index.html` : path; if (files[direct]) return { path: direct, file: files[direct], status: 200 }; if (!path.endsWith("/") && path !== "") { if (files[`${path}/index.html`]) return { redirect: `${base}${path}/` }; if (files[`${path}.html`]) return { path: `${path}.html`, file: files[`${path}.html`], status: 200 }; } if (spa && files["index.html"]) return { path: "index.html", file: files["index.html"], status: 200 }; if (files["404.html"]) return { path: "404.html", file: files["404.html"], status: 404 }; return null; } async function serveTarget(request: Request, target: Target): Promise { const site = await pointer(target.slot); if (!site) return plain(404, "Site not found"); const manifest = await env.KV.get(manifestKey(site.deploymentId), { type: "json", cacheTtl: MANIFEST_CACHE_SECONDS, }); if (!manifest) return plain(503, "Deployment unavailable"); const path = decodePath(target.path); if (path === null) return plain(400, "Bad path"); const found = lookup(manifest, site.spa, path, target.base); if (!found) return plain(404, "Not found"); if ("redirect" in found) return redirect(found.redirect); const [sha, size] = found.file; const etag = `"${sha}"`; const headers: Record = { ...SECURITY_HEADERS, "content-type": contentType(found.path), etag, "cache-control": found.path.endsWith(".html") ? "public, max-age=0, must-revalidate" : "public, max-age=600", }; if (found.status === HTTP_OK && request.headers.get("if-none-match") === etag) { return new Response(null, { status: 304, headers }); } if (request.method === "HEAD") { return new Response(null, { status: found.status, headers: { ...headers, "content-length": String(size) } }); } const object = await env.BUCKET.get(objectKey(sha)); if (!object) return plain(503, "Deployment object missing"); return new Response(object.body, { status: found.status, headers: { ...headers, "content-length": String(object.size) }, }); } /** Dispatches Pages hosts (owner subdomains and custom domains) before forge routing; null for forge traffic. */ export async function handlePagesRequest(request: Request): Promise { const url = new URL(request.url); const target = await resolveTarget(url.hostname.toLowerCase(), url.pathname); if (!target) return null; if (target instanceof Response) return target; if (request.method !== "GET" && request.method !== "HEAD") return plain(405, "Method not allowed"); return serveTarget(request, target); }