import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts"; const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/; export type HostingMode = "live" | "invalid-live" | "fixture"; export type HostingVerdict = "PASS" | "FAIL" | "UNVERIFIED"; /** * 13-05 (D-14). The fixture compares the declared headers with a copy of * themselves, so it can only find a contradiction, never prove hosting. Only a * live probe of the deployed release can PASS. */ export function hostingVerdict(mode: HostingMode, passed: boolean): HostingVerdict { if (!passed) return "FAIL"; return mode === "live" ? "PASS" : "UNVERIFIED"; } /** * 13-05. The live probe requests the entry script the served index.html names, * so it checks the release that is deployed rather than the first asset of a * local build, which the deployed release may not contain. */ export function servedEntryScript(indexHtml: string): string | null { for (const tag of indexHtml.match(/]*>/gu) ?? []) { if (!/\btype=["']module["']/u.test(tag)) continue; const source = /\bsrc=["']([^"']+\.js)["']/u.exec(tag)?.[1]; if (source) return source; } return null; } export type ProbeResult = Readonly<{ surface: string; header: string; expected: unknown; observed: unknown; reason?: string; passed: boolean; }>; export type ResponseHeaders = Record>; export type HostingFetcher = (url: URL) => Promise; export type ReleaseIdentity = Readonly<{ buildId: string; releaseId: string }>; /** `buildId` and `releaseId` of a release-manifest.json text, or null. */ export function releaseIdentity(manifest: string | null): ReleaseIdentity | null { try { const { buildId, releaseId } = JSON.parse(manifest ?? "") as Record; return typeof buildId === "string" && typeof releaseId === "string" ? { buildId, releaseId } : null; } catch { return null; } } /** * 13-05 (D-14). Runs after the promoted release is deployed. Every surface must * answer 200 without leaving the probed origin, and the hashed asset it * requests is the entry script the served index.html names. * * 1101/13-04. `appRoute` is a path the build has no file for. The router uses * browser history, so a reload or a shared link of any route reaches the host * as such a path, and the host must answer it with the same index.html (SPA * fallback). A 404 or any other page there fails, although `/` still works. * * 1101/13-01. The served release manifest must name the candidate's build and * release. Correct headers on an earlier release are not evidence for this one. */ export async function probeLiveRelease( base: URL, paths: Readonly>, candidate: ReleaseIdentity, fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }), ): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> { const responses: ResponseHeaders = {}; const results: ProbeResult[] = []; const probe = async (surface: string, pathname: string): Promise => { try { const response = await fetcher(new URL(pathname, base)); const finalOrigin = new URL(response.url).origin; results.push( { surface, header: "http-status", expected: 200, observed: response.status, passed: response.status === 200, }, { surface, header: "final-origin", expected: base.origin, observed: finalOrigin, passed: finalOrigin === base.origin, }, ); responses[surface] = Object.fromEntries( [...response.headers.entries()].map(([name, value]) => [name.toLowerCase(), value]), ); return await response.text(); } catch (error: unknown) { results.push({ surface, header: "transport", expected: "reachable", observed: error instanceof Error ? error.name : "UnknownError", passed: false, }); return null; } }; const bodies: Record = {}; for (const [surface, pathname] of Object.entries(paths)) { bodies[surface] = await probe(surface, pathname); } const entryScript = servedEntryScript(bodies["index"] ?? ""); if (entryScript) { await probe("hashedAsset", entryScript); } else { results.push({ surface: "hashedAsset", header: "entry-script", expected: "a module script named by the served index.html", observed: null, passed: false, }); } const served = releaseIdentity(bodies["releaseManifest"] ?? null); for (const [field, header] of [["buildId", "build-id"], ["releaseId", "release-id"]] as const) { results.push({ surface: "releaseManifest", header, expected: candidate[field], observed: served?.[field] ?? null, passed: served?.[field] === candidate[field], }); } if ("appRoute" in paths) { const observed = servedEntryScript(bodies["appRoute"] ?? ""); results.push({ surface: "appRoute", header: "entry-script", expected: entryScript, observed, passed: entryScript !== null && observed === entryScript, }); } return { responses, results }; } /** A build ships a worker script for these selections (06-03: REMOVE_REGISTRATION ships the self-unregistering one). */ export function shipsServiceWorker(selection: InstalledServiceWorkerSelection | null): boolean { return selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION"; } const PUBLIC_SERVICE_WORKER = /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/i; /** * A built `dist` may ship a worker script only when the static selection is * `ACTIVE` or `REMOVE_REGISTRATION` (the self-unregistering worker, 06-03), and * then only the selected script at the app root. */ export function checkPublicServiceWorkers( distFiles: readonly string[], selection: InstalledServiceWorkerSelection | null, ) { const found = distFiles.filter((file) => PUBLIC_SERVICE_WORKER.test(file)); const allowed: string[] = selection && shipsServiceWorker(selection) ? [selection.scriptPath] : []; const passed = found.length === allowed.length && found.every((file) => allowed.includes(file)); return { surface: "serviceWorker", header: "enabled", expected: allowed.length > 0, observed: found.length > 0, passed, ...(passed ? {} : { reason: `dist worker scripts: ${found.join(", ") || "none"}` }), }; } /** * A release gate must not promote a local preview server as live hosting * evidence. * */ export function classifyLiveHostingBaseUrl(value: string): | { passed: true; reason: null; url: URL; observedOrigin: string; } | { passed: false; reason: string; url: URL | null; observedOrigin: string | null; } { let url: URL; try { url = new URL(value); } catch { return { passed: false, reason: "HOSTING_BASE_URL must be an absolute URL", url: null, observedOrigin: null, }; } const observedOrigin = url.origin; const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, ""); if (url.protocol !== "https:") { return { passed: false, reason: "live hosting evidence requires HTTPS", url, observedOrigin, }; } if (url.username || url.password) { return { passed: false, reason: "HOSTING_BASE_URL must not contain credentials", url, observedOrigin, }; } if ( hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "::1" || hostname === "0.0.0.0" || LOOPBACK_IPV4.test(hostname) ) { return { passed: false, reason: "local or loopback hosts are not live deployment evidence", url, observedOrigin, }; } if (url.pathname !== "/" || url.search || url.hash) { return { passed: false, reason: "HOSTING_BASE_URL must be the canonical root URL", url, observedOrigin, }; } return { passed: true, reason: null, url, observedOrigin }; }