Files
clean-architecture-frontend…/scripts/lib/hosting-probe.ts
T
DongHyeonka 4d6f254438 fix(hosting): 자산 MIME probe가 redirect를 거절하고 live 분기를 테스트한다
문제: 확장자별 MIME probe(1103/06-03)는 install 조건 일부만 옮겼다.
1. install fetch는 `redirect: "error"`라 redirect가 하나라도 있으면
   실패한다. probe는 `redirect: "follow"`로 받고 최종 status와 MIME만
   본다. 같은 origin 안 redirect 뒤 200을 주는 호스트가 PASS다(리뷰
   06-R1). FE-GATE-019가 PASS인데 워커 install은 매번 실패한다.
2. 워커 없는 빌드에서도 돈다. 주석과 문서는 이유를 워커로만 적는다.
3. live 분기의 호출 줄(`verify-hosting-headers.ts`)을 지키는 테스트가
   없다. live 모드는 루프백·http를 거절해 저장소 테스트가 들어갈 수
   없다. 호출을 지우는 변이가 44건 통과로 살아남았다(06-R2).

고른 방법:
1. 자산 probe 기본 fetcher를 `redirect: "manual"`로 바꾸고,
   `response.redirected`이거나 `opaqueredirect`이면 관측 "redirected",
   이유 "install fetch가 redirect를 거절"로 FAIL이다. 3xx는 지금처럼
   `HTTP 3xx`로 FAIL이다. fetcher가 redirect를 따라가도 `redirected`로
   잡으므로 fetcher 방식과 무관하다.
2. 동작은 그대로 두고 의도를 주석과 운영 문서에 적었다. 워커가 없어도
   `nosniff` 아래 script·style은 MIME이 틀리면 페이지가 깨지고, 나중에
   워커를 켜는 릴리스가 호스팅을 다시 확인하지 않아도 된다. 글꼴·이미지는
   페이지에 피해가 없는데 FAIL한다는 것도 적었다. 워커 없는 빌드에서
   script·style만 보도록 좁히는 것은 검사를 약하게 하는 정책 결정이라
   하지 않았다(결정 대기, 템플릿 소유자).
3. live 분기 전체를 `probeLiveHosting`(release surface +
   자산 MIME)으로 빼고 스크립트는 그것만 부른다. 테스트가 fetcher
   대역으로 이 함수를 돌려 CSS `text/plain`이 FAIL인지 본다. 자산 probe
   호출을 빼면 이 테스트가 실패한다. 스크립트에서 `probeLiveHosting`
   호출을 빼면 live 결과가 비어 cache-control 행이 모두 FAIL이라 스스로
   드러난다.
버린 대안: 문서에 한계만 적기(리뷰 (b)). 1·3이 그대로다.

위험·한계: 정규 경로 규칙으로 자산을 redirect하는 호스트는 이제
FE-GATE-019에서 FAIL이다. 워커가 없는 제품도 마찬가지다(2의 판단).
실제 호스트로 live 모드를 돌리지는 않았다.

검증: desktop batch에서 확인.
- node scripts/run-vitest.ts run tests/unit/hosting-probe.test.ts
- RED: "fails an asset the host answers only after a redirect"(옛 probe는
  redirect 뒤 200을 PASS), "checks every built asset type besides the
  release surfaces"(옛 코드에 `probeLiveHosting`이 없음)가 실패한다.
- 변이(06-R2 대응): `probeLiveHosting`에서 `probeAssetContentTypes` 결과를
  빼면 "checks every built asset type ..."가 실패해야 한다.

Refs: 1105/06-02
2026-11-05 22:11:49 +09:00

463 lines
16 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.
*/
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,
},
);
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 };
}