Files
clean-architecture-frontend…/scripts/verify-hosting-headers.ts
T
DongHyeonka 0f58abbd32 fix(hosting): live probe가 사전 캐시 확장자마다 Content-Type을 확인한다
문제
워커 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
2026-11-04 20:26:24 +09:00

222 lines
7.8 KiB
TypeScript

import { mkdir, readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts";
import { hostingHeadersArtifactSchema } from "./contracts/release-artifacts.ts";
import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
probeAssetContentTypes,
probeLiveRelease,
releaseIdentity,
shipsServiceWorker,
type HostingMode,
type ProbeResult,
type ResponseHeaders,
} from "./lib/hosting-probe.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type Document = Record<string, unknown>;
function isRecord(value: unknown): value is Document {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function recordValue(value: unknown): Document {
return isRecord(value) ? value : {};
}
function strings(value: unknown): string[] {
return Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string")
: [];
}
function stringRecord(value: unknown): Record<string, string> {
return Object.fromEntries(
Object.entries(recordValue(value)).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
);
}
function responseHeaders(value: unknown): ResponseHeaders {
return Object.fromEntries(
Object.entries(recordValue(value)).map(([surface, headers]) => [
surface,
stringRecord(headers),
]),
);
}
async function readDocument(file: string): Promise<Document> {
const parsed: unknown = JSON.parse(await readFile(file, "utf8"));
if (!isRecord(parsed)) throw new Error(`${file} must be a JSON object`);
return parsed;
}
const cachePolicy = await readDocument("config/hosting/cache-policy.json");
const cacheSurfaces = recordValue(cachePolicy.surfaces);
const securityPolicy = await readDocument(
"config/hosting/security-headers.json",
);
const securityHeaders = stringRecord(securityPolicy.headers);
const baseUrl = process.env.HOSTING_BASE_URL;
const liveTarget = baseUrl ? classifyLiveHostingBaseUrl(baseUrl) : null;
// 1101/13-01. FE-GATE-019 passes the promoted archive it extracted, so the
// files checked here and the identity the host must serve are the candidate's,
// not a local rebuild's. Without the flag a local run checks its own `dist`.
const releaseRootFlag = process.argv.indexOf("--release-root");
const releaseRoot = releaseRootFlag >= 0 ? process.argv[releaseRootFlag + 1] : ".";
if (!releaseRoot) {
process.stderr.write("Usage: verify:hosting-headers [-- --release-root <extracted release archive>]\n");
process.exit(2);
}
const distRoot = path.join(releaseRoot, "dist");
const distFiles = (await readdir(distRoot, { recursive: true })).map(String);
// 1101/13-01. The deployment slot job reports whether it deployed this
// candidate. An empty slot deployed nothing, so the host still serves an
// earlier release: probing it proves nothing about this one (UNVERIFIED).
const deployedBySlot = process.env.RELEASE_DEPLOYED;
const slotEmpty = deployedBySlot !== undefined && deployedBySlot !== "true";
const publicSourceMaps = distFiles.filter((file) => file.endsWith(".map"));
// 1101/13-04. The worker script surface exists only in a build that ships one.
const workerShipped = shipsServiceWorker(INSTALLED_RUNTIME_CAPABILITIES.serviceWorker);
const requiredSurfaces = Object.entries(cacheSurfaces)
.map(([surface, policy]) => [surface, recordValue(policy)] as const)
.filter(([, policy]) => policy.requiredWhen !== "service-worker-shipped" || workerShipped);
let responses: ResponseHeaders = {};
let mode: HostingMode;
const probeResults: ProbeResult[] = [];
if (liveTarget?.passed && !slotEmpty) {
mode = "live";
const paths = Object.fromEntries(
requiredSurfaces.flatMap(([surface, policy]) =>
typeof policy.path === "string" ? [[surface, policy.path] as const] : [],
),
);
const candidateManifest = await readFile(path.join(distRoot, "release-manifest.json"), "utf8").catch(() => null);
const candidate = releaseIdentity(candidateManifest);
if (!candidate) {
throw new Error(`${distRoot}/release-manifest.json does not name a buildId and releaseId`);
}
const probed = await probeLiveRelease(liveTarget.url, paths, candidate);
responses = probed.responses;
probeResults.push(...probed.results);
// 1103/06-03. The worker needs every precached asset kind typed exactly.
probeResults.push(...(await probeAssetContentTypes(liveTarget.url, distFiles)));
} else if (liveTarget && !liveTarget.passed) {
mode = "invalid-live";
probeResults.push({
surface: "deployment",
header: "base-url",
expected: "canonical non-loopback HTTPS root URL",
observed: liveTarget.observedOrigin,
reason: liveTarget.reason,
passed: false,
});
} else {
mode = "fixture";
const fixture = await readDocument(
"config/hosting/response-headers.fixture.json",
);
responses = responseHeaders(fixture.responses);
}
const results: ProbeResult[] = [...probeResults];
for (const [surface, policy] of requiredSurfaces) {
if (typeof policy.cacheControl !== "string") continue;
const contentTypes = strings(policy.contentTypes);
const observed = responses[surface]?.["cache-control"];
results.push({
surface,
header: "cache-control",
expected: policy.cacheControl,
observed,
passed: observed === policy.cacheControl,
});
const observedContentType = responses[surface]?.["content-type"];
const observedMime = observedContentType
?.split(";", 1)[0]
?.trim()
.toLowerCase();
results.push({
surface,
header: "content-type",
expected: contentTypes,
observed: observedContentType,
passed: observedMime !== undefined && contentTypes.includes(observedMime),
});
if (policy.securityHeaders === true) {
for (const [header, expected] of Object.entries(securityHeaders)) {
const observedSecurity = responses[surface]?.[header.toLowerCase()];
results.push({
surface,
header: header.toLowerCase(),
expected,
observed: observedSecurity,
passed: observedSecurity === expected,
});
}
}
}
const sourceMapPolicy = recordValue(cacheSurfaces.sourceMap);
results.push({
surface: "sourceMap",
header: "public",
expected: false,
observed: publicSourceMaps.length > 0,
passed: sourceMapPolicy.public === false && publicSourceMaps.length === 0,
});
results.push(
checkPublicServiceWorkers(
distFiles,
INSTALLED_RUNTIME_CAPABILITIES.serviceWorker,
),
);
const passed = results.every((result) => result.passed);
const status = hostingVerdict(mode, passed);
await mkdir("artifacts/release", { recursive: true });
await writeValidatedJsonArtifact({
path: "artifacts/release/hosting-headers.json",
schema: hostingHeadersArtifactSchema,
value: {
schemaVersion: 1,
generatedAt: new Date().toISOString(),
mode,
// The schema records a base URL only for a host that was probed.
baseUrl: mode === "live" ? (liveTarget?.observedOrigin ?? null) : null,
providerVerificationRequired: mode !== "live",
results,
passed,
status,
},
});
if (status === "FAIL") {
process.stderr.write(
"Hosting cache/content-type/security header verification failed.\n",
);
process.exit(1);
}
if (status === "UNVERIFIED" && slotEmpty) {
process.stderr.write(
"Hosting header contract: UNVERIFIED (the deployment slot is empty: nothing deployed this release, so the host was not probed; fill the deployment job in config/ci/gates.json)\n",
);
process.exit(3);
}
if (status === "UNVERIFIED") {
// Not a pass (D-14): set HOSTING_BASE_URL to the deployed release.
process.stderr.write(
"Hosting header contract: UNVERIFIED (fixture: declared headers are consistent; set HOSTING_BASE_URL to probe the deployed release)\n",
);
process.exit(3);
}
process.stdout.write("Hosting header contract: PASS (live)\n");