Files
clean-architecture-frontend…/scripts/generate-service-worker-assets.ts
T
DongHyeonka 1c7c614b47 fix(service-worker): 사전 캐시를 Vite assets 폴더의 해시 파일로 제한한다
문제: 사전 캐시 수집기(`collectStaticAssets`)는 dist 전체를 돌고 파일
이름만 해시 정규식으로 본다. `public/` 파일은 이름 그대로 dist 루트에
복사되는데, `apple-touch-icon.png`, `android-chrome-192x192.png`,
`safari-pinned-tab.svg`는 정규식에 걸려 immutable 자산으로 들어간다(리뷰
06-R1). 제품이 같은 이름으로 아이콘을 바꾸고 CDN이 옛 바이트를 주면 새
릴리스 install이 INTEGRITY_MISMATCH로 통째로 거절된다. 이전 릴리스
fallback, 호스팅 정책 `/assets/*`, MIME probe, 레시피 문서는 모두
`assets/`만 가정한다.

고른 방법: 리뷰 06-01의 (a). 계약 모듈에 `BUILD_ASSET_DIRECTORY =
"assets/"` 하나를 두고, 수집기는 그 아래 파일만 받는다. 워커 fallback
(`service-worker-static-assets.ts`)과 probe(`hosting-probe.ts`)도 같은
상수를 읽는다. `build.assetsDir`를 바꿀 때(0925/06-08) 이 상수 한 곳만
고치면 된다. 수집기의 `.vite/` 제외는 새 조건이 덮으므로 지웠다. 레시피
문서에 루트 파일이 빠진다는 문장을 더했다.
버린 대안:
- 정규식을 Vite 해시 형식(8자 고정)으로 좁히기. 우연히 맞는 이름이 남는다.
- 문서만 고치기. 아이콘 문제가 그대로다.

위험·한계: 루트에 해시 이름 파일을 일부러 두는 제품은 그 파일이 사전
캐시에서 빠진다. Vite는 그런 파일을 만들지 않는다. 상수는 vite 설정에서
읽지 않는다. `build.assetsDir`를 바꾸는 제품은 상수도 같이 바꿔야 한다
(0925/06-08은 그대로 남는다).

검증: desktop batch에서 확인.
- node scripts/run-vitest.ts run tests/unit/service-worker-web-push-remediation.test.ts tests/unit/service-worker-runtime.test.ts tests/unit/hosting-probe.test.ts tests/unit/service-worker-build-output.test.ts
- RED: "precaches only the assets directory, not public files at the dist
  root"가 옛 수집기에서 루트 아이콘 세 개를 받아 실패한다.

Refs: 1105/06-01
2026-11-05 22:08:50 +09:00

178 lines
6.1 KiB
TypeScript

import { createHash } from "node:crypto";
import {
CACHEABLE_ASSET_CONTENT_TYPES,
canonicalStaticManifestBytes,
decodeStaticAssetManifest,
isCanonicalStaticAssetUrl,
} from "../src/contracts/service-worker-static-manifest.ts";
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { getBuildConfig } from "../src/contracts/env.ts";
import {
BUILD_ASSET_DIRECTORY,
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
} from "../src/contracts/service-worker.ts";
/**
* §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed
* asset list under `BUILD_ASSET_DIRECTORY` the Service Worker will verify at
* install time.
*
* `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are
* the runtime config and release manifest, which are network-only (§18.4).
*/
/** Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). */
export const SERVICE_WORKER_ASSETS_OUTPUT =
".generated/frontend-runtime/service-worker-assets.ts";
// SW-RR-03. The generator and the shared decoder read the same table, so a
// manifest this script produces can never be one the runtime contract refuses.
const CACHEABLE_EXTENSIONS = CACHEABLE_ASSET_CONTENT_TYPES;
const EXCLUDED_FILES: ReadonlySet<string> = new Set([
"index.html",
SERVICE_WORKER_SCRIPT_PATH,
"config.json",
"release-manifest.json",
"runtime-config.schema.json",
]);
/**
* Vite emits content-hashed names under its assets directory; only those may
* be treated as immutable. A `public/` file copied to the dist root keeps its
* own name even when it looks hashed (`android-chrome-192x192.png`), and a
* product may change its bytes under that name (1105/06-01).
*/
const HASHED_NAME = HASHED_STATIC_ASSET_NAME;
/**
* `basePath` is the router base path (`VITE_ROUTER_BASE_PATH`): dist, and so
* every asset, is served under it (0929/06-02).
*/
export async function collectStaticAssets(
distDirectory: string,
buildId: string,
releaseId: string,
basePath = "/",
): Promise<StaticAssetManifestV1> {
const files = await walk(distDirectory, distDirectory);
const assets: StaticAssetManifestV1["assets"][number][] = [];
for (const relative of files.sort()) {
const base = path.basename(relative);
if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) {
continue;
}
if (EXCLUDED_FILES.has(base)) continue;
const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
if (!contentType || !HASHED_NAME.test(base)) continue;
const absolute = path.join(distDirectory, relative);
const bytes = await readFile(absolute);
if (bytes.byteLength > SERVICE_WORKER_BOUNDS.singleAssetBytes) {
throw new Error(`Static asset exceeds its byte bound: ${relative}`);
}
// SW-02. The URL is checked against the same predicate the runtime decoder
// applies. Emitting a path the decoder will refuse turned a correct build
// into a runtime contract failure discovered only at install time.
const url = `${basePath}${relative.split(path.sep).join("/")}`;
if (!isCanonicalStaticAssetUrl(url)) {
throw new Error(
`Static asset path is not canonical for the service worker manifest: ${relative}`,
);
}
assets.push({
url,
sha256: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
bytes: bytes.byteLength,
contentType,
});
}
if (assets.length > SERVICE_WORKER_BOUNDS.assets) {
throw new Error("Static asset count exceeds its bound.");
}
const totalBytes = assets.reduce((sum, asset) => sum + asset.bytes, 0);
if (totalBytes > SERVICE_WORKER_BOUNDS.assetSetBytes) {
throw new Error("Static asset set exceeds its byte bound.");
}
// SW-05. The canonical byte serialization lives in the shared runtime-neutral
// codec so the worker can recompute the identical digest with WebCrypto.
const setDigest: `sha256:${string}` = `sha256:${createHash("sha256")
.update(canonicalStaticManifestBytes(assets))
.digest("hex")}`;
const manifest: StaticAssetManifestV1 = {
schemaVersion: 1,
buildId,
releaseId,
setDigest,
assets,
};
// SW-02. Every manifest this generator returns has already passed the exact
// decoder the runtime will apply to it, so the build stops here rather than
// at install time.
const decoded = decodeStaticAssetManifest(manifest);
if (!decoded.ok) {
throw new Error(
`Generated service worker manifest is not decodable: ${decoded.error.reason}`,
);
}
return manifest;
}
async function walk(root: string, current: string): Promise<string[]> {
const entries = await readdir(current, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
files.push(...(await walk(root, absolute)));
} else if ((await stat(absolute)).isFile()) {
files.push(path.relative(root, absolute));
}
}
return files;
}
async function main(): Promise<void> {
const distDirectory = process.argv[2] ?? "dist";
const buildId = process.env.VITE_BUILD_ID ?? "local-build";
const releaseId = process.env.RELEASE_ID ?? "local-release";
const manifest = await collectStaticAssets(
distDirectory,
buildId,
releaseId,
getBuildConfig(process.env).routerBasePath,
);
const source = [
"// Generated by scripts/generate-service-worker-assets.ts. Do not edit.",
"",
'import type { StaticAssetManifestV1 } from "../../src/contracts/service-worker.ts";',
"",
`export const SERVICE_WORKER_ASSETS: StaticAssetManifestV1 = ${JSON.stringify(
manifest,
null,
2,
)} as const;`,
"",
].join("\n");
await mkdir(path.dirname(SERVICE_WORKER_ASSETS_OUTPUT), { recursive: true });
await writeFile(SERVICE_WORKER_ASSETS_OUTPUT, source, "utf8");
process.stdout.write(
`service worker assets: ${manifest.assets.length} file(s) ${manifest.setDigest}\n`,
);
}
if (process.argv[1]?.endsWith("generate-service-worker-assets.ts")) {
await main();
}