Files
tech-log-frontend/tests/unit/public-response-cache-codec.test.ts
DongHyeonka c80320dfc7 chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
2026-11-12 08:28:54 +09:00

327 lines
10 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
import { createDefaultPublicCachePolicy } from "../../src/adapters/cache-storage/public-cache-policy.ts";
import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts";
import {
MemoryCacheStorage,
digestHex,
immediateLock,
manifestFor,
} from "./public-response-cache-fixture.ts";
/**
* Q-6.2-11. Characterization of the manifest codec and response validation
* before they moved out of the adapter: every rejection keeps its code.
*/
const ORIGIN = "https://assets.example.test";
const policy = createDefaultPublicCachePolicy(ORIGIN);
const BYTES = new Uint8Array([1, 2, 3, 4]);
async function asset(
overrides: Partial<PublicCacheAsset> = {},
): Promise<PublicCacheAsset> {
return {
absoluteUrl: `${ORIGIN}/app.js`,
expectedByteLength: BYTES.byteLength,
expectedContentType: "application/javascript",
integrity: { algorithm: "SHA-256", digestHex: await digestHex(BYTES) },
...overrides,
};
}
function adapterWith(
respond: () => Response = () =>
new Response(Uint8Array.from(BYTES), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
}),
cacheStorage = new MemoryCacheStorage(),
) {
return createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async () => respond(),
});
}
async function stageCode(
assets: readonly PublicCacheAsset[],
respond?: () => Response,
): Promise<string> {
const manifest = {
releaseRegistryId: "codec-release",
assets,
manifestDigestHex: "0".repeat(64),
};
try {
Object.assign(manifest, await manifestFor("codec-release", assets, policy));
} catch {
// An invalid manifest has no digest; staging must still reject it.
}
const result = await adapterWith(respond).admin.stageRelease(manifest);
return result.ok ? "OK" : result.error.code;
}
describe("public cache codec and response validation (characterization)", () => {
it("keeps manifest normalization failure codes", async () => {
const valid = await asset();
expect(await stageCode([])).toBe("LIMIT_EXCEEDED");
expect(await stageCode([valid, valid])).toBe("CONFLICT");
expect(
await stageCode([
await asset({
integrity: { algorithm: "SHA-1" as "SHA-256", digestHex: "0" },
}),
]),
).toBe("INVALID_INPUT");
expect(
await stageCode([await asset({ expectedByteLength: -1 })]),
).toBe("INVALID_INPUT");
for (const absoluteUrl of [
"https://user:secret@assets.example.test/app.js",
"https://other.example.test/app.js",
`${ORIGIN}/app.js#fragment`,
`${ORIGIN}/app.js?token=secret`,
`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`,
]) {
expect(await stageCode([await asset({ absoluteUrl })])).toBe(
"POLICY_REJECTED",
);
}
expect(await stageCode([await asset({ absoluteUrl: "not a url" })])).toBe(
"INVALID_INPUT",
);
expect(
await stageCode([await asset({ expectedContentType: "text/html" })]),
).toBe("POLICY_REJECTED");
expect(
await stageCode([
await asset({ requestHeaders: [["authorization", "Bearer x"]] }),
]),
).toBe("POLICY_REJECTED");
expect(
await stageCode([
await asset({
requestHeaders: [["accept"] as unknown as readonly [string, string]],
}),
]),
).toBe("INVALID_INPUT");
const wrongDigest = await adapterWith().admin.stageRelease({
releaseRegistryId: "codec-release",
assets: [valid],
manifestDigestHex: "0".repeat(64),
});
expect(wrongDigest).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
const badRelease = await adapterWith().admin.stageRelease({
...(await manifestFor("codec-release", [valid], policy)),
releaseRegistryId: "bad release id",
});
expect(badRelease).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
});
it("keeps response validation failure codes", async () => {
const valid = await asset();
const response = (
headers: Record<string, string>,
body: Uint8Array = BYTES,
init: ResponseInit = {},
) => () =>
new Response(Uint8Array.from(body), {
...init,
headers: {
"cache-control": "public",
"content-type": "application/javascript",
...headers,
},
});
expect(await stageCode([valid], response({}))).toBe("OK");
expect(
await stageCode([valid], response({}, BYTES, { status: 203 })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "cache-control": "no-store" })),
).toBe("POLICY_REJECTED");
expect(await stageCode([valid], response({ pragma: "no-cache" }))).toBe(
"POLICY_REJECTED",
);
expect(
await stageCode([valid], response({ "www-authenticate": "Basic" })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "content-type": "text/html" })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "content-type": "text/css" })),
).toBe("INTEGRITY_FAILED");
expect(await stageCode([valid], response({ vary: "Cookie" }))).toBe(
"POLICY_REJECTED",
);
expect(
await stageCode([valid], response({ "content-length": "99999999999" })),
).toBe("LIMIT_EXCEEDED");
expect(
await stageCode([valid], response({}, new Uint8Array([1, 2, 3, 4, 5]))),
).toBe("INTEGRITY_FAILED");
expect(
await stageCode([valid], response({}, new Uint8Array([1, 2, 3]))),
).toBe("INTEGRITY_FAILED");
expect(
await stageCode([valid], response({}, new Uint8Array([4, 3, 2, 1]))),
).toBe("INTEGRITY_FAILED");
});
it("cancels a pending cached body read when the lookup is aborted", async () => {
const valid = await asset();
const manifest = await manifestFor("codec-release", [valid], policy);
const storage = new MemoryCacheStorage();
const adapter = adapterWith(undefined, storage);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
const name = [...storage.caches.keys()].find((key) =>
key.includes(":codec-release:"),
)!;
const cache = storage.caches.get(name)!;
const match = cache.match.bind(cache);
let cancelled = 0;
let pulled: (() => void) | undefined;
const bodyRequested = new Promise<void>((resolve) => {
pulled = resolve;
});
cache.match = async (request: RequestInfo | URL) => {
if (request instanceof Request && request.url === valid.absoluteUrl) {
return new Response(
new ReadableStream<Uint8Array>({
pull() {
pulled?.();
return new Promise<void>(() => {});
},
cancel() {
cancelled += 1;
},
}),
{
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
},
);
}
return await match(request);
};
const controller = new AbortController();
const lookup = adapter.responses.matchActiveExact({
absoluteUrl: valid.absoluteUrl,
signal: controller.signal,
});
await bodyRequested;
controller.abort();
expect(await lookup).toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
expect(cancelled).toBe(1);
});
it("keeps control JSON decoding failure codes", async () => {
const valid = await asset();
const manifest = await manifestFor("codec-release", [valid], policy);
const lookupAfter = async (
tamper: (storage: MemoryCacheStorage) => Promise<void>,
): Promise<string> => {
const storage = new MemoryCacheStorage();
const adapter = adapterWith(undefined, storage);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
await tamper(storage);
const result = await adapter.responses.matchActiveExact({
absoluteUrl: valid.absoluteUrl,
});
return result.ok ? "OK" : result.error.code;
};
const replace = async (
storage: MemoryCacheStorage,
path: "active" | "candidate",
body: BodyInit,
): Promise<void> => {
const name = [...storage.caches.keys()].find((key) =>
path === "active"
? key.endsWith(":control")
: key.includes(":codec-release:"),
)!;
await storage.caches
.get(name)!
.put(
new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/${path}`),
new Response(body, {
headers: { "content-type": "application/json" },
}),
);
};
expect(await lookupAfter(async () => {})).toBe("OK");
expect(
await lookupAfter((storage) => replace(storage, "active", "{not json")),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter((storage) =>
replace(storage, "active", new Uint8Array([0xff, 0xfe])),
),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter((storage) =>
replace(storage, "active", JSON.stringify({ schemaVersion: 2 })),
),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter(async (storage) => {
const name = [...storage.caches.keys()].find((key) =>
key.includes(":codec-release:"),
)!;
const cache = storage.caches.get(name)!;
const marker = await (await cache.match(
new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`),
))!.json();
await replace(
storage,
"candidate",
JSON.stringify({ ...marker, entryCount: 2 }),
);
}),
).toBe("CORRUPT_DATA");
expect(
await lookupAfter((storage) =>
replace(storage, "candidate", JSON.stringify({ verified: false })),
),
).toBe("CORRUPT_DATA");
});
});