문제
워커 install은 사전 캐시 자산마다 응답 MIME이 manifest 값
(CACHEABLE_ASSET_CONTENT_TYPES: .css .js .mjs .png .svg .webp .woff2)과
정확히 같아야 하고, 하나라도 틀리면 release 전체를 거절한다. 호스팅
live probe는 index가 가리키는 entry script 하나만 요청하고
hashedAsset.contentTypes도 JavaScript뿐이다. 그래서 CSS를 text/plain,
글꼴을 octet-stream으로 보내는 호스트도 게이트는 PASS다. 페이지는
글꼴을 그대로 쓰므로 워커만 조용히 설치되지 않는다.
고른 방법
- probeAssetContentTypes를 더한다. 후보 dist의 assets/에서 확장자마다
첫 파일(이름순)을 요청하고, 그 확장자의 워커 표 MIME과 비교한다.
결과는 surface hashedAsset.<ext>, header content-type이다.
verify-hosting-headers live 모드에서만 부른다.
- 기대 MIME은 워커 표에서 바로 읽는다. .js 계열은 hashedAsset surface와
같이 application/javascript도 받는다. 두 목록이 같다는 것을 테스트가
지킨다(acceptedAssetContentTypes(".js") = cache-policy hashedAsset).
- 운영 문서(release-cache-rollback.md)에 새 검사를 적는다.
- 버린 대안: (b) 워커가 비JS 자산 MIME을 느슨하게 받기 — 캐시에서 꺼낸
응답이 틀린 MIME을 그대로 갖고 설계 §18 확인 순서 4와 어긋난다.
(c) 사전 캐시를 JS·CSS로 줄이기 — 글꼴 캐시 이득을 잃는다. (d) 문서만
— 검출이 없다(리뷰 5.2).
위험·한계
- live probe 요청이 확장자 수만큼 는다(지금 빌드는 .js·.css 2개).
- 확장자마다 파일 하나만 본다. 같은 확장자 안에서 경로마다 MIME이
다른 호스트는 잡지 못한다.
- cache-control은 이 자산들에서 다시 보지 않는다. entry script의
hashedAsset 검사가 그대로 본다.
- 실제 호스트로 live 모드를 돌리지 않았다. fetcher 대역으로만 확인했다.
- 하위 경로 base는 probe가 아직 거절한다(0929/13-06, 다른 영역). 새
함수는 base 기준 상대 경로로 요청하므로 그 수정 뒤에도 그대로 쓴다.
검증
- 새 테스트 4건을 옛 코드에 돌림: 4건 실패(RED). 새 코드:
hosting-probe·service-worker-build-output 테스트 통과.
- CSS를 text/plain으로 보내는 호스트 → hashedAsset.css FAIL.
- check:types:node·check:types:test 통과, 바꾼 파일 eslint 통과.
Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 06-03
320 lines
10 KiB
TypeScript
320 lines
10 KiB
TypeScript
import path from "node:path";
|
|
|
|
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
|
|
import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.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 }>;
|
|
|
|
/** `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.
|
|
*/
|
|
export async function probeLiveRelease(
|
|
base: URL,
|
|
paths: Readonly<Record<string, string>>,
|
|
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<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,
|
|
});
|
|
}
|
|
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("assets/") &&
|
|
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 };
|
|
}
|