문제
워커 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
364 lines
14 KiB
TypeScript
364 lines
14 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
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";
|
|
import { SERVICE_WORKER_SCRIPT_PATH } from "../../src/contracts/service-worker.ts";
|
|
|
|
describe("public service worker in dist", () => {
|
|
const app = ["index.html", "config.json", "assets/index-abc.js"];
|
|
const active = {
|
|
mode: "ACTIVE",
|
|
scriptPath: "service-worker.js",
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
} as const;
|
|
const removal = { mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" } as const;
|
|
const purge = { mode: "PURGE_OWNED_RESOURCES", scriptPath: "service-worker.js" } as const;
|
|
|
|
it("accepts the selected worker when the selection is ACTIVE", () => {
|
|
expect(
|
|
checkPublicServiceWorkers([...app, "service-worker.js"], active),
|
|
).toMatchObject({ expected: true, observed: true, passed: true });
|
|
});
|
|
|
|
// 06-03 (D-5). REMOVE_REGISTRATION ships the self-unregistering worker.
|
|
it("accepts the selected worker when the selection is REMOVE_REGISTRATION", () => {
|
|
expect(
|
|
checkPublicServiceWorkers([...app, "service-worker.js"], removal),
|
|
).toMatchObject({ expected: true, observed: true, passed: true });
|
|
});
|
|
|
|
it("accepts a worker-free dist when no worker is selected", () => {
|
|
expect(checkPublicServiceWorkers(app, null)).toMatchObject({
|
|
expected: false,
|
|
passed: true,
|
|
});
|
|
});
|
|
|
|
it.each([
|
|
["no selection", [...app, "service-worker.js"], null],
|
|
["a PURGE_OWNED_RESOURCES selection", [...app, "service-worker.js"], purge],
|
|
["REMOVE_REGISTRATION without the worker", app, removal],
|
|
["ACTIVE without the worker", app, active],
|
|
["ACTIVE with an extra worker", [...app, "service-worker.js", "assets/sw.js"], active],
|
|
["ACTIVE with the worker off the root", [...app, "assets/service-worker.js"], active],
|
|
] as const)("rejects %s", (_, files, selection) => {
|
|
expect(checkPublicServiceWorkers(files, selection)).toMatchObject({
|
|
passed: false,
|
|
reason: expect.stringContaining("dist worker scripts"),
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("live hosting evidence target", () => {
|
|
it("accepts a canonical production HTTPS root", () => {
|
|
expect(
|
|
classifyLiveHostingBaseUrl("https://frontend.example.test/"),
|
|
).toMatchObject({
|
|
passed: true,
|
|
observedOrigin: "https://frontend.example.test",
|
|
});
|
|
});
|
|
|
|
it.each([
|
|
["http://frontend.example.test/", "requires HTTPS"],
|
|
["https://localhost:4173/", "not live deployment evidence"],
|
|
["https://127.0.0.1/", "not live deployment evidence"],
|
|
["https://frontend.example.test/app/", "canonical root URL"],
|
|
["https://user:secret@frontend.example.test/", "must not contain credentials"],
|
|
])("rejects %s", (url, reason) => {
|
|
expect(classifyLiveHostingBaseUrl(url)).toMatchObject({
|
|
passed: false,
|
|
reason: expect.stringContaining(reason),
|
|
});
|
|
});
|
|
});
|
|
|
|
// 13-05 (D-14). The declared-header fixture proves nothing about hosting, so it
|
|
// is UNVERIFIED, and a live probe checks the release actually served.
|
|
describe("hosting header verdict", () => {
|
|
it("passes only a live probe of the deployed release", () => {
|
|
expect(hostingVerdict("live", true)).toBe("PASS");
|
|
expect(hostingVerdict("fixture", true)).toBe("UNVERIFIED");
|
|
expect(hostingVerdict("fixture", false)).toBe("FAIL");
|
|
expect(hostingVerdict("invalid-live", false)).toBe("FAIL");
|
|
expect(hostingVerdict("live", false)).toBe("FAIL");
|
|
});
|
|
|
|
it("probes the entry script named by the served index.html", () => {
|
|
expect(
|
|
servedEntryScript(
|
|
'<head><link rel="modulepreload" href="/assets/a-1.js"><script type="module" crossorigin src="/app/assets/index-Dpjd89Th.js"></script></head>',
|
|
),
|
|
).toBe("/app/assets/index-Dpjd89Th.js");
|
|
expect(servedEntryScript("<html><body>maintenance</body></html>")).toBeNull();
|
|
});
|
|
});
|
|
|
|
// 1101/13-04. The router uses browser history, so a reload or a shared link of
|
|
// any route reaches the host as a path the build has no file for. The host has
|
|
// to answer it with the release's index.html; without that fallback `/` still
|
|
// opens and only deep links are 404, which no other check sees.
|
|
describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
|
type Surface = Partial<{
|
|
path: string;
|
|
cacheControl: string;
|
|
contentTypes: string[];
|
|
securityHeaders: boolean;
|
|
requiredWhen: string;
|
|
}>;
|
|
const surfaces = async () =>
|
|
(JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as {
|
|
surfaces: Record<string, Surface | undefined>;
|
|
}).surfaces;
|
|
|
|
it("declares an app route the build has no file for, served like index.html", async () => {
|
|
const { appRoute, index } = await surfaces();
|
|
expect(appRoute).toMatchObject({
|
|
cacheControl: index?.cacheControl,
|
|
contentTypes: index?.contentTypes,
|
|
securityHeaders: true,
|
|
});
|
|
expect(appRoute?.path).toMatch(/^\/[^.]+$/u);
|
|
const { responses } = JSON.parse(
|
|
await readFile("config/hosting/response-headers.fixture.json", "utf8"),
|
|
) as { responses: Record<string, unknown> };
|
|
expect(responses["appRoute"]).toEqual(responses["index"]);
|
|
});
|
|
|
|
it("declares the worker script, served no-cache, only for a build that ships it", async () => {
|
|
expect((await surfaces())["serviceWorker"]).toMatchObject({
|
|
path: `/${SERVICE_WORKER_SCRIPT_PATH}`,
|
|
cacheControl: "no-cache",
|
|
requiredWhen: "service-worker-shipped",
|
|
});
|
|
});
|
|
|
|
const INDEX = '<script type="module" src="/assets/index-A1.js"></script>';
|
|
const PATHS = {
|
|
index: "/",
|
|
runtimeConfig: "/config.json",
|
|
releaseManifest: "/release-manifest.json",
|
|
appRoute: "/__probe/deep-link",
|
|
};
|
|
const CANDIDATE = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" };
|
|
const RELEASE: Record<string, [number, string]> = {
|
|
"/": [200, INDEX],
|
|
"/config.json": [200, "{}"],
|
|
"/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...CANDIDATE })],
|
|
"/assets/index-A1.js": [200, ""],
|
|
};
|
|
const host = (routes: Record<string, [number, string]>) => async (url: URL) => {
|
|
const [status, body] = routes[url.pathname] ?? [404, "Not Found"];
|
|
const response = new Response(body, { status, headers: { "cache-control": "no-cache" } });
|
|
Object.defineProperty(response, "url", { value: url.href });
|
|
return response;
|
|
};
|
|
const base = new URL("https://frontend.example.test/");
|
|
const failed = async (routes: Record<string, [number, string]>) =>
|
|
(await probeLiveRelease(base, PATHS, CANDIDATE, host(routes))).results
|
|
.filter((result) => !result.passed)
|
|
.map((result) => `${result.surface} ${result.header}`);
|
|
|
|
it("passes a host that answers every route with the release's index.html", async () => {
|
|
expect(await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX] })).toEqual([]);
|
|
});
|
|
|
|
it("fails a host without the fallback", async () => {
|
|
expect(await failed(RELEASE)).toEqual(["appRoute http-status", "appRoute entry-script"]);
|
|
});
|
|
|
|
it("fails a fallback that answers 200 with a page that is not the release's index.html", async () => {
|
|
expect(
|
|
await failed({ ...RELEASE, "/__probe/deep-link": [200, "<h1>Not found</h1>"] }),
|
|
).toEqual(["appRoute entry-script"]);
|
|
});
|
|
|
|
// 1101/13-01. Headers alone pass for whatever release the host serves,
|
|
// usually the previous one when nothing deployed this candidate.
|
|
it("fails a host that still serves an earlier release", async () => {
|
|
const earlier = JSON.stringify({ schemaVersion: 2, buildId: "gitea-41-1", releaseId: "refs/tags/v1.1.0-41-1" });
|
|
expect(
|
|
await failed({
|
|
...RELEASE,
|
|
"/__probe/deep-link": [200, INDEX],
|
|
"/release-manifest.json": [200, earlier],
|
|
}),
|
|
).toEqual(["releaseManifest build-id", "releaseManifest release-id"]);
|
|
});
|
|
|
|
it("fails when the served release manifest is unreadable", async () => {
|
|
expect(
|
|
await failed({
|
|
...RELEASE,
|
|
"/__probe/deep-link": [200, INDEX],
|
|
"/release-manifest.json": [200, "<html>maintenance</html>"],
|
|
}),
|
|
).toEqual(["releaseManifest build-id", "releaseManifest release-id"]);
|
|
});
|
|
});
|
|
|
|
// 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<Record<string, string>>, 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)", () => {
|
|
async function verify(
|
|
distFiles: Readonly<Record<string, string>>,
|
|
env: Readonly<Record<string, string>> = {},
|
|
) {
|
|
const root = await mkdtemp(path.join(tmpdir(), "hosting-release-root-"));
|
|
try {
|
|
await mkdir(path.join(root, "config/hosting"), { recursive: true });
|
|
for (const file of ["cache-policy.json", "security-headers.json", "response-headers.fixture.json"]) {
|
|
await copyFile(`config/hosting/${file}`, path.join(root, "config/hosting", file));
|
|
}
|
|
for (const [file, content] of Object.entries(distFiles)) {
|
|
await mkdir(path.dirname(path.join(root, "candidate/dist", file)), { recursive: true });
|
|
await writeFile(path.join(root, "candidate/dist", file), content);
|
|
}
|
|
const environment: NodeJS.ProcessEnv = { ...process.env, ...env };
|
|
if (!("HOSTING_BASE_URL" in env)) delete environment["HOSTING_BASE_URL"];
|
|
if (!("RELEASE_DEPLOYED" in env)) delete environment["RELEASE_DEPLOYED"];
|
|
const result = spawnSync(
|
|
process.execPath,
|
|
[path.resolve("scripts/verify-hosting-headers.ts"), "--", "--release-root", "candidate"],
|
|
{ cwd: root, encoding: "utf8", env: environment },
|
|
);
|
|
const record = JSON.parse(
|
|
await readFile(path.join(root, "artifacts/release/hosting-headers.json"), "utf8"),
|
|
) as { mode: string; results: { surface: string; header: string; passed: boolean }[] };
|
|
return {
|
|
status: result.status,
|
|
stderr: result.stderr,
|
|
mode: record.mode,
|
|
failed: record.results
|
|
.filter((entry) => !entry.passed)
|
|
.map((entry) => `${entry.surface} ${entry.header}`),
|
|
};
|
|
} finally {
|
|
await rm(root, { recursive: true, force: true });
|
|
}
|
|
}
|
|
const DIST = {
|
|
"index.html": '<script type="module" src="/assets/index-A1.js"></script>',
|
|
"release-manifest.json": JSON.stringify({ buildId: "gitea-42-1", releaseId: "r-42" }),
|
|
"assets/index-A1.js": "",
|
|
};
|
|
|
|
it("checks the dist inside --release-root, with no local build present", async () => {
|
|
const result = await verify({ ...DIST, "assets/index-A1.js.map": "{}" });
|
|
expect(result.failed, result.stderr).toEqual(["sourceMap public"]);
|
|
expect(result.status).toBe(1);
|
|
});
|
|
|
|
it("ends UNVERIFIED without probing the host when the deployment slot is empty", async () => {
|
|
const result = await verify(DIST, {
|
|
HOSTING_BASE_URL: "https://frontend.example.test/",
|
|
RELEASE_DEPLOYED: "false",
|
|
});
|
|
expect(result.failed, result.stderr).toEqual([]);
|
|
expect(result.mode).toBe("fixture");
|
|
expect(result.status).toBe(3);
|
|
expect(result.stderr).toContain("deployment slot");
|
|
});
|
|
});
|