Files
clean-architecture-frontend…/tests/unit/service-worker-web-push-remediation.test.ts
DongHyeonka 3b3396ea07 fix(service-worker): public/ 사본을 사전 캐시와 assets 폴더에서 뺀다
Vite는 public/을 그대로 복사한다. public/assets/x는 dist assets/x가
되어 Vite의 hash 파일 옆에 자기 이름으로 놓인다. 그 이름이
HASHED_STATIC_ASSET_NAME과 맞으면 Service Worker가 immutable로 사전
캐시하고(REV-FE-0043), 호스팅 계약(config/hosting/cache-policy.json
hashedAsset)도 /assets/* 전체에 1년 immutable 헤더를 준다
(REV-FE-0044). 제품이 다음 release에서 이름은 두고 바이트만 바꾸면
worker와 브라우저·CDN이 옛 바이트를 낸다.

두 곳에서 막는다.
- 사전 캐시: 생성기가 dist 파일 가운데 public/에도 같은 경로로 있는
  파일을 뺀다. collectStaticAssets와 countPrecachedAssets가 같은 목록
  (precachedFiles)을 읽는다.
- 빌드: scripts/build-frontend.ts가 Vite 전에 public/ 아래
  BUILD_ASSET_DIRECTORY 이름의 폴더를 찾으면, 소스에서 import하거나
  public/의 다른 폴더로 옮기라는 메시지로 실패한다
  (scripts/lib/public-asset-directory.ts).
public/ 이름은 PUBLIC_DIRECTORY 한 값으로 두고, vite.config.ts의
publicDir와 같은지 시험이 본다. Mmax 측정법 2단계는 public/assets/로
채우던 것을 빌드가 import하는 소스 자산(new URL(..., ?no-inline))으로
바꾸고, 채우기 모듈이 URL 배열을 globalThis 속성 하나에 대입한다고
적는다.

시험은 두 검사를 실제 진입점으로도 부른다. 임시 프로젝트 폴더에서
scripts/build-frontend.ts가 0단계에서 거절하고 dist를 만들지 않는지,
scripts/generate-service-worker-assets.ts <dist>가 인자 없는 기본
public/로 사본을 빼는지(목록과 countPrecachedAssets 둘 다) 본다.

버린 안:
- Vite manifest(.vite/manifest.json)의 file·css·assets로 사전 캐시를
  고른다: desktop 실빌드에서 Web Worker 출력(assets/<이름>-<hash>.js)이
  manifest에 없어 빠진다.
- 호스팅 계약에 파일별 목록을 둔다: 호스팅마다 설정 방식이 달라
  템플릿이 덮지 못한다.
- 문서로만 금지한다: 지키는지 보는 곳이 없다.
- 검사를 check:bundle이나 FE-GATE-019에 둔다: 게이트 없이 pnpm
  build만 하는 배포를 막지 못하고, 019는 production 단계다.
- 카드마다 커밋 하나: 두 검사가 같은 PUBLIC_DIRECTORY를 읽는 것이
  수정의 일부라, 나누면 중간 커밋에 상수가 둘 생긴다.

위험·한계: public/assets/를 둔 파생 프로젝트는 빌드가 실패로 바뀐다
(CHANGELOG 「먼저 할 일」). publicDir를 바꾼 제품은 PUBLIC_DIRECTORY도
바꿔야 한다. scripts/check-bundle.ts는 아직 "public" 글자를 직접
쓴다(REV-FE-0010 파일, 이 커밋 밖). Mmax 측정법의 채우기 모듈 청크는
초기 JS로 세어진다(측정 트리에서 200,765 B, 예산 안). 실제 호스팅
헤더는 재지 않았다(FE-GATE-019는 production 단계).

검증(트리 fd833429):
- RED: 8bb30d2a + 사전 캐시 변경만(트리 f0b1076c)에서
  public/assets/brand-wordmark.svg를 둔 desktop 빌드가 rc=0이고 dist
  assets/brand-wordmark.svg가 같은 바이트로 생긴다. 검사를 넣은
  트리(105919e1)에서는 build refused 메시지로 rc=1, 0단계를 지운 변이는
  다시 rc=0이다.
- 사전 캐시: 고치기 전 생성기에서 시험 2 failed → 6 passed, 변이 5개
  실패(82b959ff 위). 고친 생성기 실빌드에서 사전 캐시 28 → 27이고
  빠진 것은 assets/brand-wordmark.svg 하나, Web Worker 출력은 남는다.
- 빌드 검사 단위: tests/unit/public-asset-directory.test.ts 10 passed.
  변이 6개(검사 제거, "assets" 글자 둘, public/ 자체, ENOENT 실패,
  이름 바꾸기) 모두 실패. build-frontend.ts 0단계와 import를 지운
  변이는 진입점 시험 1 failed.
- 생성기 진입점: service-worker-asset-bounds 8 passed. 기본 public
  경로를 "public-missing"으로 바꾼 변이(collectStaticAssets 쪽,
  countPrecachedAssets 쪽, 둘 다)가 각각 1·1·2 failed.
- 자식 프로세스 시한: desktop JSON reporter로 잰 가장 긴 값 527.3 ms·
  302.3 ms(unit, coverage보다 길다)를 childProcessTimeout(528)·(303)로.
- Mmax(새 채우기): 사전 캐시 256개, 23,417 B, 다섯 자리 23,441 B,
  handler 둘 23,439 B → 1 KiB 올림 23,552로 예산 그대로.
- desktop merge 단계 14개 rc=0, desktop verify:documentation rc=0.
  노트북 test:unit 4,090개, check:types, lint, check:architecture,
  verify:documentation, scripts/verify.sh docs rc=0.

Refs: REV-FE-0043, REV-FE-0044
2026-11-23 17:02:06 +09:00

299 lines
10 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { afterEach, describe, expect, it } from "vitest";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import {
CACHEABLE_ASSET_CONTENT_TYPES,
decodeStaticAssetManifest,
isCanonicalStaticAssetUrl,
} from "../../src/contracts/service-worker-static-manifest.ts";
/**
* SW-RR-03. The build generator and the shared runtime decoder must agree on
* exactly which asset kinds exist. A generator that emits `.mjs` or `.png` while
* the decoder refuses them turns a correct build into a runtime contract
* failure, and the reverse admits a kind no build produces.
*/
describe("SW-RR-03 one authoritative cacheable asset table", () => {
it("covers every extension the generator emits", async () => {
const generator = await import(
"../../scripts/generate-service-worker-assets.ts"
);
expect(generator).toBeDefined();
for (const extension of [
".js",
".mjs",
".css",
".woff2",
".svg",
".png",
".webp",
]) {
expect(CACHEABLE_ASSET_CONTENT_TYPES[extension]).toBeDefined();
}
});
it("decodes a manifest row for every table entry", () => {
const assets = Object.entries(CACHEABLE_ASSET_CONTENT_TYPES).map(
([extension, contentType], index) => ({
url: `/assets/name-abcdefgh${index}${extension}`,
sha256: `sha256:${"a".repeat(64)}`,
bytes: 16,
contentType,
}),
);
const decoded = decodeStaticAssetManifest({
schemaVersion: 1,
buildId: "build-1",
releaseId: "release-1",
assets,
setDigest: `sha256:${"b".repeat(64)}`,
});
expect(decoded).toMatchObject({ ok: true });
});
it("refuses a row whose extension is not in the table", () => {
const decoded = decodeStaticAssetManifest({
schemaVersion: 1,
buildId: "build-1",
releaseId: "release-1",
setDigest: `sha256:${"b".repeat(64)}`,
assets: [
{
url: "/assets/control-abcdefgh.json",
sha256: `sha256:${"a".repeat(64)}`,
bytes: 16,
contentType: "application/json",
},
],
});
expect(decoded.ok).toBe(false);
});
});
/**
* CI names a release after its ref (`refs/heads/main-12-1`) and the deploy
* system owns that name. A build id is the build's own short token.
*/
describe("the identities of a service worker manifest", () => {
const decode = (buildId: string, releaseId: string) =>
decodeStaticAssetManifest({
schemaVersion: 1,
buildId,
releaseId,
setDigest: `sha256:${"b".repeat(64)}`,
assets: [],
});
it.each([
["a branch", "refs/heads/main-12-1"],
["a pull request", "refs/pull/95/head-12-1"],
["a plus sign", "refs/tags/v1.0.0+build.7-12-1"],
["an at sign", "refs/heads/release@eu-12-1"],
["Hangul", "refs/heads/기능-12-1"],
["one character", "r"],
["512 characters", "가".repeat(512)],
["512 characters outside the BMP", "\u{1F600}".repeat(512)],
["a space", "release candidate 1"],
["a zero-width joiner", "release‍1"],
])("accepts a release id with %s", (_, releaseId) => {
expect(decode("build-1", releaseId)).toMatchObject({ ok: true, manifest: { releaseId } });
});
it.each([
["no character", ""],
["a line feed", "release\n1"],
["a final line feed", "release-1\n"],
["a NUL", "release\u00001"],
["a DEL", "release\u007f1"],
["a tab", "release\t1"],
["a C1 control", "release\u00851"],
["the last C1 control", "release\u009f1"],
["513 characters", "r".repeat(513)],
])("refuses a release id with %s", (_, releaseId) => {
expect(decode("build-1", releaseId).ok).toBe(false);
});
it.each([
["a slash", "refs/heads/main-12-1"],
["129 characters", "b".repeat(129)],
])("refuses a build id with %s", (_, buildId) => {
expect(decode(buildId, "release-1").ok).toBe(false);
});
});
/**
* SW-02. Sharing only the extension table left the generator and the decoder
* with different path grammars: the generator emitted a URL for a directory
* containing an `@` or a space, and the decoder then refused the manifest it
* had just produced, failing the release build at install time.
*/
describe("SW-02 the generator and the decoder share one path grammar", () => {
// 00-03. The dist fixtures used to stay in /tmp.
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
async function distWith(
files: Readonly<Record<string, string>>,
): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), "sw-assets-"));
temporaryRoots.push(root);
for (const [relative, content] of Object.entries(files)) {
const absolute = path.join(root, relative);
await mkdir(path.dirname(absolute), { recursive: true });
await writeFile(absolute, content);
}
return root;
}
it("emits a manifest the runtime decoder accepts for every table entry", async () => {
const { collectStaticAssets } = await import(
"../../scripts/generate-service-worker-assets.ts"
);
const files: Record<string, string> = {};
for (const [index, extension] of Object.keys(
CACHEABLE_ASSET_CONTENT_TYPES,
).entries()) {
files[`assets/name-abcdefg${index}${extension}`] = `content-${index}`;
}
files["assets/nested/deep/name-abcdefgz.js"] = "nested";
const root = await distWith(files);
const manifest = await collectStaticAssets(root, "build-1", "release-1");
expect(manifest.assets.length).toBe(
Object.keys(CACHEABLE_ASSET_CONTENT_TYPES).length + 1,
);
expect(decodeStaticAssetManifest(manifest)).toMatchObject({ ok: true });
for (const asset of manifest.assets) {
expect(isCanonicalStaticAssetUrl(asset.url)).toBe(true);
}
});
// 1105/06-01. Vite copies `public/` files under their own names: to the
// dist root, and from `public/assets/` into the assets directory. A PWA
// icon such as `android-chrome-192x192.png` matches the hashed name
// pattern, but a product may change its bytes under the same name; a CDN
// that still serves the old bytes then fails every install with
// INTEGRITY_MISMATCH. So the generator precaches only the assets directory
// and, there, leaves out every file `public/` has (REV-FE-0043, in
// service-worker-asset-bounds.test.ts); this case is the dist root. The
// `public/` folder name is taken as fixed: a product that sets `publicDir`
// in vite.config.ts changes PUBLIC_DIRECTORY
// (scripts/lib/public-asset-directory.ts) too.
it("precaches only the assets directory, not public files at the dist root", async () => {
const { collectStaticAssets } = await import(
"../../scripts/generate-service-worker-assets.ts"
);
const root = await distWith({
"index.html": "page",
"config.json": "{}",
"release-manifest.json": "{}",
"apple-touch-icon.png": "icon",
"android-chrome-192x192.png": "icon",
"safari-pinned-tab.svg": "icon",
"favicon.svg": "icon",
"robots.txt": "robots",
"icons/maskable-512x512.png": "icon",
"assets/index-AbCdEf12.js": "entry",
"assets/index-AbCdEf12.css": "style",
});
const manifest = await collectStaticAssets(root, "build-1", "release-1");
expect(manifest.assets.map((asset) => asset.url)).toEqual([
"/assets/index-AbCdEf12.css",
"/assets/index-AbCdEf12.js",
]);
});
// 0929/06-02. dist is served under the router base path; a root URL made
// the worker's install request /assets/... and fail under /app/.
it("puts every asset URL under the router base path", async () => {
const { collectStaticAssets } = await import(
"../../scripts/generate-service-worker-assets.ts"
);
const root = await distWith({
"assets/index-abcdefgh.js": "entry",
"assets/nested/chunk-abcdefgz.css": "style",
});
const manifest = await collectStaticAssets(
root,
"build-1",
"release-1",
"/app/",
);
expect(manifest.assets.map((asset) => asset.url)).toEqual([
"/app/assets/index-abcdefgh.js",
"/app/assets/nested/chunk-abcdefgz.css",
]);
expect(decodeStaticAssetManifest(manifest)).toMatchObject({ ok: true });
});
it.each([
{ label: "an at sign", name: "bad@name-abcdefgh.js" },
{ label: "a space", name: "bad name-abcdefgh.js" },
{ label: "a percent escape", name: "bad%20name-abcdefgh.js" },
{ label: "a hash", name: "bad#name-abcdefgh.js" },
])(
"stops the build rather than emitting a path the decoder refuses ($label)",
async ({ name }) => {
const { collectStaticAssets } = await import(
"../../scripts/generate-service-worker-assets.ts"
);
const root = await distWith({
"assets/good-abcdefgh.js": "ok",
[`assets/${name}`]: "bad",
});
await expect(
collectStaticAssets(root, "build-1", "release-1"),
).rejects.toThrow(/not canonical/u);
},
);
it("agrees with the decoder on the whole path policy table", () => {
const cases: readonly (readonly [string, boolean])[] = [
["/assets/name-abcdefgh.js", true],
["/assets/nested/name-abcdefgh.js", true],
["/assets/bad@name-abcdefgh.js", false],
["/assets/bad name-abcdefgh.js", false],
["/assets/bad%20name-abcdefgh.js", false],
["/assets/bad#name-abcdefgh.js", false],
["/assets/../name-abcdefgh.js", false],
["/assets/./name-abcdefgh.js", false],
["assets/name-abcdefgh.js", false],
["/assets/\\name-abcdefgh.js", false],
["/assets/naïve-abcdefgh.js", false],
];
for (const [url, canonical] of cases) {
expect(isCanonicalStaticAssetUrl(url), url).toBe(canonical);
const decoded = decodeStaticAssetManifest({
schemaVersion: 1,
buildId: "build-1",
releaseId: "release-1",
setDigest: `sha256:${"a".repeat(64)}`,
assets: [
{
url,
sha256: `sha256:${"a".repeat(64)}`,
bytes: 4,
contentType: "text/javascript",
},
],
});
// The decoder still owns the digest check, so a canonical path may fail
// for other reasons; a non-canonical one must always fail.
if (!canonical) expect(decoded.ok, url).toBe(false);
}
});
});