문제: 사전 캐시 수집기(`collectStaticAssets`)는 dist 전체를 돌고 파일 이름만 해시 정규식으로 본다. `public/` 파일은 이름 그대로 dist 루트에 복사되는데, `apple-touch-icon.png`, `android-chrome-192x192.png`, `safari-pinned-tab.svg`는 정규식에 걸려 immutable 자산으로 들어간다(리뷰 06-R1). 제품이 같은 이름으로 아이콘을 바꾸고 CDN이 옛 바이트를 주면 새 릴리스 install이 INTEGRITY_MISMATCH로 통째로 거절된다. 이전 릴리스 fallback, 호스팅 정책 `/assets/*`, MIME probe, 레시피 문서는 모두 `assets/`만 가정한다. 고른 방법: 리뷰 06-01의 (a). 계약 모듈에 `BUILD_ASSET_DIRECTORY = "assets/"` 하나를 두고, 수집기는 그 아래 파일만 받는다. 워커 fallback (`service-worker-static-assets.ts`)과 probe(`hosting-probe.ts`)도 같은 상수를 읽는다. `build.assetsDir`를 바꿀 때(0925/06-08) 이 상수 한 곳만 고치면 된다. 수집기의 `.vite/` 제외는 새 조건이 덮으므로 지웠다. 레시피 문서에 루트 파일이 빠진다는 문장을 더했다. 버린 대안: - 정규식을 Vite 해시 형식(8자 고정)으로 좁히기. 우연히 맞는 이름이 남는다. - 문서만 고치기. 아이콘 문제가 그대로다. 위험·한계: 루트에 해시 이름 파일을 일부러 두는 제품은 그 파일이 사전 캐시에서 빠진다. Vite는 그런 파일을 만들지 않는다. 상수는 vite 설정에서 읽지 않는다. `build.assetsDir`를 바꾸는 제품은 상수도 같이 바꿔야 한다 (0925/06-08은 그대로 남는다). 검증: desktop batch에서 확인. - node scripts/run-vitest.ts run tests/unit/service-worker-web-push-remediation.test.ts tests/unit/service-worker-runtime.test.ts tests/unit/hosting-probe.test.ts tests/unit/service-worker-build-output.test.ts - RED: "precaches only the assets directory, not public files at the dist root"가 옛 수집기에서 루트 아이콘 세 개를 받아 실패한다. Refs: 1105/06-01
424 lines
15 KiB
TypeScript
424 lines
15 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.
|
|
*/
|
|
export async function probeAssetContentTypes(
|
|
base: URL,
|
|
distFiles: readonly string[],
|
|
fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }),
|
|
): 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;
|
|
try {
|
|
const response = await fetcher(new URL(file, base));
|
|
await response.body?.cancel().catch(() => undefined);
|
|
observed =
|
|
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,
|
|
passed: expected.includes(observed),
|
|
});
|
|
}
|
|
return 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 };
|
|
}
|