From 0f58abbd328775e242c845af011576eb830e5f8d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:26:24 +0900 Subject: [PATCH] =?UTF-8?q?fix(hosting):=20live=20probe=EA=B0=80=20?= =?UTF-8?q?=EC=82=AC=EC=A0=84=20=EC=BA=90=EC=8B=9C=20=ED=99=95=EC=9E=A5?= =?UTF-8?q?=EC=9E=90=EB=A7=88=EB=8B=A4=20Content-Type=EC=9D=84=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 워커 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., 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 --- docs/operations/release-cache-rollback.md | 7 +- scripts/lib/hosting-probe.ts | 65 ++++++++++++++++ scripts/verify-hosting-headers.ts | 3 + tests/unit/hosting-probe.test.ts | 91 +++++++++++++++++++++++ 4 files changed, 165 insertions(+), 1 deletion(-) diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 2ec859a3..d3661342 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -72,7 +72,12 @@ for): the host must answer 200 with the same `index.html` (the same entry script) and the HTML headers, so a host without the SPA fallback fails (review 1101/13-04). When the build ships a worker it requests `/service-worker.js` and expects `no-cache`. The surfaces and their headers are -declared in `config/hosting/cache-policy.json`. +declared in `config/hosting/cache-policy.json`. For each cacheable extension the +release has under `assets/` (`.css`, `.js`, `.woff2` and the rest of +`CACHEABLE_ASSET_CONTENT_TYPES`) it requests the first such file and expects +exactly that type (`hashedAsset.css` and so on). The worker's install refuses +the whole release when one precached asset has another type, while a page +still uses a font served as `application/octet-stream` (review 1103/06-03). The served `release-manifest.json` must name the `buildId` and `releaseId` of the release being checked: correct headers on an earlier release are not diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index faf6473b..63cacf94 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -1,4 +1,7 @@ +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}$/; @@ -148,6 +151,68 @@ export async function probeLiveRelease( 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 { + const samples = new Map(); + 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"; diff --git a/scripts/verify-hosting-headers.ts b/scripts/verify-hosting-headers.ts index 5d883661..5005c1c7 100644 --- a/scripts/verify-hosting-headers.ts +++ b/scripts/verify-hosting-headers.ts @@ -7,6 +7,7 @@ import { checkPublicServiceWorkers, classifyLiveHostingBaseUrl, hostingVerdict, + probeAssetContentTypes, probeLiveRelease, releaseIdentity, shipsServiceWorker, @@ -106,6 +107,8 @@ if (liveTarget?.passed && !slotEmpty) { 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({ diff --git a/tests/unit/hosting-probe.test.ts b/tests/unit/hosting-probe.test.ts index 258e0825..ad0818e3 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -6,9 +6,11 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { + acceptedAssetContentTypes, checkPublicServiceWorkers, classifyLiveHostingBaseUrl, hostingVerdict, + probeAssetContentTypes, probeLiveRelease, servedEntryScript, } from "../../scripts/lib/hosting-probe.ts"; @@ -207,6 +209,95 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => { }); }); +// 1103/06-03. The worker's install requires each precached asset's exact +// Content-Type (CACHEABLE_ASSET_CONTENT_TYPES) and refuses the whole release on +// one mismatch. A page still uses a font served as octet-stream, so only the +// worker notices. The live probe requests one built asset per extension. +describe("hashed asset content types (1103/06-03)", () => { + const base = new URL("https://frontend.example.test/"); + const DIST_FILES = [ + "index.html", + "config.json", + "assets/index-A1.js", + "assets/chunk-B2.js", + "assets/index-C3.css", + "assets/inter-D4.woff2", + "assets/notes-E5.txt", + "robots.txt", + ]; + const host = + (types: Readonly>, requested: string[] = []) => + async (url: URL) => { + requested.push(url.pathname); + const extension = /\.[^./]+$/u.exec(url.pathname)?.[0] ?? ""; + const type = types[extension]; + const response = new Response("", { + status: type ? 200 : 404, + headers: type ? { "content-type": type } : {}, + }); + Object.defineProperty(response, "url", { value: url.href }); + return response; + }; + const CORRECT = { + ".js": "text/javascript; charset=utf-8", + ".css": "text/css", + ".woff2": "font/woff2", + }; + + it("requests one built asset per cacheable extension and passes correct types", async () => { + const requested: string[] = []; + const results = await probeAssetContentTypes(base, DIST_FILES, host(CORRECT, requested)); + expect(requested).toEqual([ + "/assets/index-C3.css", + "/assets/chunk-B2.js", + "/assets/inter-D4.woff2", + ]); + expect(results.map((result) => [result.surface, result.passed])).toEqual([ + ["hashedAsset.css", true], + ["hashedAsset.js", true], + ["hashedAsset.woff2", true], + ]); + }); + + it("fails a host that serves CSS as text/plain", async () => { + const results = await probeAssetContentTypes( + base, + DIST_FILES, + host({ ...CORRECT, ".css": "text/plain" }), + ); + expect(results.filter((result) => !result.passed)).toEqual([ + expect.objectContaining({ + surface: "hashedAsset.css", + header: "content-type", + expected: ["text/css"], + observed: "text/plain", + }), + ]); + }); + + it("fails a font served as octet-stream and an asset the host does not serve", async () => { + const results = await probeAssetContentTypes( + base, + DIST_FILES, + host({ ".js": "application/javascript", ".woff2": "application/octet-stream" }), + ); + expect( + results.filter((result) => !result.passed).map((result) => [result.surface, result.observed]), + ).toEqual([ + ["hashedAsset.css", "HTTP 404"], + ["hashedAsset.woff2", "application/octet-stream"], + ]); + }); + + it("accepts for JavaScript what the hashedAsset surface declares", async () => { + const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as { + surfaces: { hashedAsset: { contentTypes: string[] } }; + }; + expect(acceptedAssetContentTypes(".js")).toEqual(policy.surfaces.hashedAsset.contentTypes); + expect(acceptedAssetContentTypes(".woff2")).toEqual(["font/woff2"]); + }); +}); + // 1101/13-01. FE-GATE-019 checks the promoted candidate it downloaded, not a // local rebuild, and an empty deployment slot proves nothing about the host. describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => {