Files
clean-architecture-frontend…/scripts/lib/hosting-probe.ts
DongHyeonka 2a78169c58 fix(hosting): live probe가 redirect된 워커 스크립트를 거절한다
문제
워커를 싣는 빌드에서 live probe는 `/service-worker.js`를 기본 fetcher
`redirect: "follow"`로 받고, 최종 응답의 status와 origin만 본다
(`scripts/lib/hosting-probe.ts` `probeLiveRelease`). 같은 origin 안
redirect 뒤에 200·`no-cache`·JS MIME이 오면 FE-GATE-019가 PASS다.
브라우저는 워커 스크립트를 redirect mode "error"로 받는다(Service
Worker Update 알고리즘). 그런 호스트에서는 첫 등록, update 검사,
`REMOVE_REGISTRATION` kill switch가 모두 실패한다.

고른 방법과 버린 대안
- `serviceWorker` surface에만 `redirect` 행을 더한다.
  `response.redirected`이거나 `opaqueredirect`이면 FAIL이다. 자산
  probe(1105/06-02)와 같은 판정식이라 fetcher가 redirect를 따라가든
  manual이든 잡는다. 3xx 응답은 지금처럼 `http-status` 행이 FAIL로 본다.
- redirect가 없으면 이 행은 PASS로 남는다. 산출물에 이 검사를 했다는
  기록이 된다.
- 버린 대안: 모든 surface에서 redirect를 FAIL로 보기(리뷰 (b)).
  `index`·`appRoute`의 정상 redirect(끝 슬래시 정규화 등)까지 막는다.
  문서에만 적기(리뷰 (c))는 게이트가 그대로 PASS다.
- 운영 문서 두 곳에 "redirect 없이"를 적었다. release-cache-rollback.md의
  live probe 설명과 browser-file-storage-recovery.md의 kill switch
  전제다.

위험·한계
- 워커 스크립트를 redirect하던 호스트는 이제 FE-GATE-019에서 FAIL이다.
  그런 호스트에서는 지금도 워커가 동작하지 않는다.
- 브라우저 거절은 명세와 Chromium 오류 문구에 기댄 것이다. redirect하는
  호스트로 실제 등록을 돌려 보지 않았고, live 모드도 실제 호스트로 돌리지
  않았다(리뷰 §5 미검증 그대로).

검증
- desktop batch에서 확인:
  node scripts/run-vitest.ts run tests/unit/hosting-probe.test.ts
- RED: "live hosting probe (1105/06-02) > fails a worker script the host
  answers only after a same-origin redirect"가 실패한다. 옛 probe에는
  redirect 행이 없어 실패 행이 비어 있다.
- 함께: check:types, lint, verify:documentation

Refs: 1106/06-01
2026-11-06 05:17:04 +09:00

480 lines
17 KiB
TypeScript

import { isIP } from "node:net";
import path from "node:path";
import { connect } from "node:tls";
import {
BUILD_ASSET_DIRECTORY,
type InstalledServiceWorkerSelection,
} from "../../src/contracts/service-worker.ts";
import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.ts";
import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.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(/<script\b[^>]*>/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<string, Record<string, string>>;
export type HostingFetcher = (url: URL) => Promise<Response>;
export type ReleaseIdentity = Readonly<{ buildId: string; releaseId: string }>;
/** The promoted candidate: its manifest names and the texts of its dist/config.json and dist/index.html. */
export type CandidateRelease = ReleaseIdentity & Readonly<{ runtimeConfig: string; indexHtml: string }>;
export type ProbeTransport = Readonly<{
fetcher?: HostingFetcher;
/** The ALPN protocol the host negotiates over TLS, or null when none. */
negotiateAlpn?: (base: URL) => Promise<string | null>;
/** Accepted protocols (`transport.alpnProtocols` in config/hosting/cache-policy.json); empty skips the check. */
alpnProtocols?: readonly string[];
}>;
/**
* 1103/13-02. Node's fetch speaks HTTP/1.1 even to a host that offers h2, so
* the protocol a browser gets is read from the TLS handshake instead: the
* client offers h2 and http/1.1 and the host picks one. The certificate is
* verified as fetch verifies it.
*/
export function negotiatedAlpnProtocol(base: URL, timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve, reject) => {
const host = base.hostname.replace(/^\[|\]$/gu, "");
const socket = connect({
host,
port: Number(base.port || 443),
...(isIP(host) === 0 ? { servername: host } : {}),
ALPNProtocols: ["h2", "http/1.1"],
});
socket.setTimeout(timeoutMs, () => socket.destroy(new Error("TLS handshake timed out")));
socket.once("secureConnect", () => {
const protocol = socket.alpnProtocol;
socket.end();
resolve(typeof protocol === "string" ? protocol : null);
});
socket.once("error", reject);
});
}
function parsedJsonObject(text: string | null): object | null {
try {
const value: unknown = JSON.parse(text ?? "");
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
} catch {
return null;
}
}
/** `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<string, unknown>;
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.
*
* 1103/13-01. Those names come from the CI run, so a release rebuilt in the
* same run (say with the local profile) carries them too. The served
* config.json must equal the candidate's, the one release admission
* (FE-GATE-027) admitted, except for the two emergency switches FE-RB-001 may
* change; and the served index.html must name the candidate's entry script.
*
* 1103/13-02. The host must negotiate a declared protocol (HTTP/2): the
* template splits its initial chunks on that premise.
*
* 1106/06-01. The worker script alone must also answer without any redirect.
* Browsers fetch it with redirect mode "error" (the Service Worker Update
* algorithm), so a same-origin redirect breaks registration, every update
* check and the REMOVE_REGISTRATION kill switch, although the followed answer
* is a 200 with the right headers. Pages may still follow a redirect.
*/
export async function probeLiveRelease(
base: URL,
paths: Readonly<Record<string, string>>,
candidate: CandidateRelease,
transport: ProbeTransport = {},
): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> {
const fetcher = transport.fetcher ?? ((url: URL) => fetch(url, { redirect: "follow" }));
const negotiateAlpn = transport.negotiateAlpn ?? negotiatedAlpnProtocol;
const responses: ResponseHeaders = {};
const results: ProbeResult[] = [];
const probe = async (surface: string, pathname: string): Promise<string | null> => {
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,
},
);
if (surface === "serviceWorker") {
const redirected = response.redirected || response.type === "opaqueredirect";
results.push({
surface,
header: "redirect",
expected: false,
observed: redirected,
...(redirected ? { reason: "browsers refuse a redirected worker script" } : {}),
passed: !redirected,
});
}
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<string, string | null> = {};
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,
});
}
const candidateEntryScript = servedEntryScript(candidate.indexHtml);
results.push({
surface: "index",
header: "candidate-entry-script",
expected: candidateEntryScript,
observed: entryScript,
passed: candidateEntryScript !== null && entryScript === candidateEntryScript,
});
if ("runtimeConfig" in paths) {
const served = parsedJsonObject(bodies["runtimeConfig"] ?? null);
const admitted = parsedJsonObject(candidate.runtimeConfig);
const changed = served && admitted ? changedRuntimeConfigBuildFields(admitted, served) : null;
results.push({
surface: "runtimeConfig",
header: "build-fields",
expected: [],
observed: changed ?? "unreadable",
...(changed === null
? { reason: "the served or the candidate config.json is not a JSON object" }
: changed.length > 0
? { reason: "differs from the candidate's config.json beyond the emergency switches" }
: {}),
passed: changed !== null && changed.length === 0,
});
}
const alpnProtocols = transport.alpnProtocols ?? [];
if (alpnProtocols.length > 0) {
let observed: string | null;
try {
observed = await negotiateAlpn(base);
} catch (error: unknown) {
observed = error instanceof Error ? error.name : "UnknownError";
}
results.push({
surface: "transport",
header: "alpn",
expected: alpnProtocols,
observed,
...(observed !== null && alpnProtocols.includes(observed)
? {}
: { reason: "the split initial chunks assume HTTP/2 (docs/architecture/static-delivery.md)" }),
passed: observed !== null && alpnProtocols.includes(observed),
});
}
return { responses, results };
}
/**
* 1103/06-03. The types the probe accepts for a hashed asset: the worker's
* table (`CACHEABLE_ASSET_CONTENT_TYPES`), plus `application/javascript`,
* which servers still send for `.js` (R-6.5) and the `hashedAsset` surface in
* `config/hosting/cache-policy.json` also accepts.
*/
export function acceptedAssetContentTypes(extension: string): readonly string[] {
const type = Object.hasOwn(CACHEABLE_ASSET_CONTENT_TYPES, extension)
? CACHEABLE_ASSET_CONTENT_TYPES[extension]
: undefined;
if (type === undefined) return [];
return type === "text/javascript" ? [type, "application/javascript"] : [type];
}
/**
* 1103/06-03. The worker's install compares every precached asset's
* Content-Type with the manifest's and refuses the whole release on one
* mismatch, while a page still uses, say, a font served as octet-stream. The
* entry script alone does not show that, so the live probe requests the first
* built `assets/` file of each cacheable extension.
*
* 1105/06-02. The install fetch also refuses any redirect (`redirect:
* "error"`), so an asset answered only after one fails here too, whichever
* redirect mode the fetcher uses.
*
* It runs for a build without a worker as well, on purpose: under `nosniff`
* a script or style of another type breaks the page anyway, and a later
* release that turns the worker on needs no new hosting check. A font or
* image of another type fails this probe although such a page still loads it.
*/
export async function probeAssetContentTypes(
base: URL,
distFiles: readonly string[],
fetcher: HostingFetcher = (url) => fetch(url, { redirect: "manual" }),
): Promise<ProbeResult[]> {
const samples = new Map<string, string>();
for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) {
const extension = path.posix.extname(file).toLowerCase();
if (
file.startsWith(BUILD_ASSET_DIRECTORY) &&
acceptedAssetContentTypes(extension).length > 0 &&
!samples.has(extension)
) {
samples.set(extension, file);
}
}
const results: ProbeResult[] = [];
for (const [extension, file] of [...samples].sort(([left], [right]) => left.localeCompare(right))) {
const expected = acceptedAssetContentTypes(extension);
let observed: string;
let redirected = false;
try {
const response = await fetcher(new URL(file, base));
await response.body?.cancel().catch(() => undefined);
redirected = response.redirected || response.type === "opaqueredirect";
observed = redirected
? "redirected"
: response.status === 200
? (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "")
: `HTTP ${response.status}`;
} catch (error: unknown) {
observed = error instanceof Error ? error.name : "UnknownError";
}
results.push({
surface: `hashedAsset${extension}`,
header: "content-type",
expected,
observed,
...(redirected
? { reason: "the worker's install fetch refuses a redirected asset" }
: {}),
passed: !redirected && expected.includes(observed),
});
}
return results;
}
/**
* 1105/06-02. Everything live mode of `verify:hosting-headers` asks the
* deployed host: the release surfaces (`probeLiveRelease`) and one built asset
* per cacheable type (`probeAssetContentTypes`). Live mode refuses loopback
* and plain http, so tests reach it only through this function and a fetcher
* double; a check dropped from here fails a test.
*/
export async function probeLiveHosting(
base: URL,
paths: Readonly<Record<string, string>>,
candidate: CandidateRelease,
distFiles: readonly string[],
transport: ProbeTransport = {},
): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> {
const probed = await probeLiveRelease(base, paths, candidate, transport);
return {
responses: probed.responses,
results: [
...probed.results,
...(await probeAssetContentTypes(base, distFiles, transport.fetcher)),
],
};
}
/** 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 };
}