Files
clean-architecture-frontend…/src/adapters/cache-storage/public-cache-codec.ts
T
DongHyeonka 44538819eb fix(adapters): 지난 리뷰에서 남은 adapter 결함과 시험 빈칸을 고친다
문제(2026-09-29·11-01·11-05 리뷰에서 남음·일부로 이월):
- 계속 읽히지 않는 release marker를 같은 manifest stage가 다시 쓰지 않아
  candidate와 rollback 대상이 다시 활성화되지 않는다(1105/02-02).
- 손상된 chunk 참조 행 하나가 orphan GC를 영구히 멈춘다(0929/05-01 ③).
- 롤백 중(옛 릴리스 탭) 승인된 계정 삭제가 새 릴리스가 올린 DB 앞에서
  실패한다(0929/05-05).
- lifecycle proof 정규식이 IndexedDB 16~128, OPFS 16~512로 갈렸다(05-06).
- canonical JSON 사본 셋과 sameScope 사본 둘(05-07).
- 한 origin의 앱 둘이 DB 이름으로 갈리는 근거가 문서에 없다(05-10).
- Web Storage의 TTL 모양·prototype 키·accessor 거절을 시험이 안 본다
  (1101/05-06).
- part buffer copy factor가 1까지 내려가 메모리 상한 식이 거짓이 된다
  (1101/01-03).
- 업링크 하한 64 KiB/s가 정책과 실행기에 따로 있다(0929/01-03).
- 닫힌 runtime의 abort()가 RESUME을 돌려주고 abort() 표가 없다(01-05).
- 로그인 뒤 돌아갈 주소가 router basename을 빼서 /app/ 배포가 앱 밖으로
  나간다(0929/08-08).

고른 방법:
- marker 읽기 실패(abort 말고)는 entry처럼 같은 stage가 덮어쓴다. 지우지
  않는다. 포트 주석의 "or lookup"을 고치고 운영 문서에 한 줄 적는다.
- 손상 참조 행은 참조로 보고 chunk를 남긴 뒤 수를 센다
  (corruptChunkReferences, DEGRADED 관측). 1101 결정 "손상 행은 건너뛰고
  센다"와 같다.
- 상태가 INCOMPATIBLE(새 schema)일 때 승인된 ACCOUNT_DELETION만 DB 전체를
  지운다. LOGOUT은 새 릴리스에 맡긴다.
- kernel에 canonical-json.ts·opaque-authority-proof.ts를 두고 사본이 그것을
  쓴다(실패 code는 호출자가 정한다). proof는 넓은 쪽(512)을 지킨다.
  sameOpfsScope는 OPFS 그룹 안 한 곳이다. INVENTORY 145.
- 05-10은 접두사 옵션 대신 registry가 주는 authorityToken을 앱 경계로
  정하고 문서와 시험으로 고정한다. 옵션은 지우기·유지보수 경로가 같은
  이름을 다시 계산해야 해서, 한 곳에서 빠지면 지웠다고 보고한 데이터가
  남는다.
- PART_BUFFER_COPIES(4) 하한, DEFAULT_MIN_TRANSFER_BYTES_PER_SECOND 한 값.
- 닫힌 runtime의 abort()는 NONE이고, 포트에 abort() recovery 표를 둔다.
- returnTo는 useHref로 만든 문서 경로이고 포트 주석에 기준을 적는다.
버린 대안: marker를 지우고 다시 받기 — 서빙 중인 release를 지운다
(STO-RR-04).

위험·한계: canonical JSON이 이제 cache·realtime에서도 NaN·Infinity를
거절한다(전에는 null로 썼다). Fileserver client(http 그룹)의 같은
64 KiB/s는 다른 그룹이라 이 상수를 import할 수 없고, 그 파일은 그룹 B
PR①이 고치는 파일이라 여기서 건드리지 않았다.

검증: desktop 결과는 PR 본문.

Refs: 1105/02-02, 0929/05-01, 0929/05-05, 0929/05-06, 0929/05-07, 0929/05-10, 1101/05-06, 1101/01-03, 0929/01-03, 0929/01-05, 0929/08-08
2026-11-13 20:17:04 +09:00

647 lines
18 KiB
TypeScript

import { canonicalJson } from "../platform/canonical-json.ts";
import type {
PublicCacheAsset,
PublicCacheHeader,
PublicCacheReleaseManifest,
} from "../../application/ports/browser-file-storage/cache-storage-ports.ts";
import type {
BrowserDataFailure,
BrowserDataFailureCode,
BrowserDataOperation,
BrowserDataResult,
} from "../../application/ports/browser-file-storage/shared.ts";
import {
browserDataFailure,
mapBrowserDataException,
} from "../browser-file-storage/result.ts";
import {
isAllowedPublicCacheOrigin,
MAX_RETAINED_PREVIOUS_RELEASE_COUNT,
type PublicCacheRuntimePolicy,
} from "./public-cache-policy.ts";
/**
* Q-6.2-11. Release manifest, marker and active-pointer codec for the public
* response cache: normalization, canonical digest input, bounded control JSON
* decoding, owned cache naming, and the mapping of a validation failure to a
* browser-data Result. Moved verbatim out of the adapter.
*/
export type PublicCacheCryptoFacade = Readonly<{
digestSha256(bytes: Uint8Array<ArrayBuffer>): Promise<ArrayBuffer>;
}>;
export type NormalizedAsset = Readonly<{
absoluteUrl: string;
expectedByteLength: number;
expectedContentType: string;
digestHex: string;
requestHeaders: readonly PublicCacheHeader[];
}>;
export type NormalizedReleaseManifest = Readonly<{
releaseRegistryId: string;
manifestDigestHex: string;
assets: readonly NormalizedAsset[];
}>;
export type ReleaseMarker = Readonly<{
schemaVersion: 1;
verified: true;
releaseRegistryId: string;
manifestDigestHex: string;
entryCount: number;
totalBytes: number;
stagedAtEpochMs: number;
assets: readonly NormalizedAsset[];
}>;
export type ActiveReleasePointer = Readonly<{
schemaVersion: 1;
releaseRegistryId: string;
manifestDigestHex: string;
candidateCacheName: string;
rollbackCandidateCacheNames: readonly string[];
activatedAtEpochMs: number;
}>;
export type BrowserFailureResult = Readonly<{
ok: false;
error: BrowserDataFailure;
}>;
export class CacheValidationFailure extends Error {
readonly code: BrowserDataFailureCode;
constructor(code: BrowserDataFailureCode) {
super("Public cache validation failed.");
this.name = "CacheValidationFailure";
this.code = code;
}
}
export async function normalizeAndVerifyManifest(
manifest: PublicCacheReleaseManifest,
policy: PublicCacheRuntimePolicy,
crypto: PublicCacheCryptoFacade,
): Promise<NormalizedReleaseManifest> {
const snapshot = Object.freeze({
releaseRegistryId: manifest.releaseRegistryId,
manifestDigestHex: manifest.manifestDigestHex,
assets: normalizeAssets(manifest.assets, policy),
});
if (
!policy.isReleaseRegistryIdAllowed(snapshot.releaseRegistryId) ||
!SHA256_HEX.test(snapshot.manifestDigestHex)
) {
throw new CacheValidationFailure("INVALID_INPUT");
}
const actualDigest = await sha256Hex(
crypto,
new TextEncoder().encode(
canonicalManifest(snapshot.releaseRegistryId, snapshot.assets),
),
);
if (actualDigest !== snapshot.manifestDigestHex) {
throw new CacheValidationFailure("INTEGRITY_FAILED");
}
return snapshot;
}
export function normalizeAssets(
assets: readonly PublicCacheAsset[],
policy: PublicCacheRuntimePolicy,
): readonly NormalizedAsset[] {
if (
!Array.isArray(assets) ||
assets.length < 1 ||
assets.length > policy.maxEntriesPerRelease
) {
throw new CacheValidationFailure("LIMIT_EXCEEDED");
}
const normalized = assets.map((asset) =>
normalizeAsset(asset, policy),
);
const keys = normalized.map(assetKey);
if (new Set(keys).size !== keys.length) {
throw new CacheValidationFailure("CONFLICT");
}
const declaredTotal = normalized.reduce(
(total, asset) => total + asset.expectedByteLength,
0,
);
if (
!Number.isSafeInteger(declaredTotal) ||
declaredTotal > policy.maxReleaseBytes
) {
throw new CacheValidationFailure("LIMIT_EXCEEDED");
}
return Object.freeze(normalized);
}
export function normalizeAsset(
asset: PublicCacheAsset,
policy: PublicCacheRuntimePolicy,
): NormalizedAsset {
if (
!asset ||
typeof asset !== "object" ||
!Number.isSafeInteger(asset.expectedByteLength) ||
asset.expectedByteLength < 0 ||
asset.expectedByteLength > policy.maxEntryBytes ||
asset.integrity?.algorithm !== "SHA-256" ||
!SHA256_HEX.test(asset.integrity.digestHex)
) {
throw new CacheValidationFailure("INVALID_INPUT");
}
return Object.freeze({
absoluteUrl: normalizePublicUrl(asset.absoluteUrl, policy),
expectedByteLength: asset.expectedByteLength,
expectedContentType: normalizeContentType(
asset.expectedContentType,
policy,
),
digestHex: asset.integrity.digestHex,
requestHeaders: normalizeRequestHeaders(
asset.requestHeaders,
policy,
),
});
}
export function normalizeLookupRequest(
absoluteUrl: string,
requestHeaders: readonly PublicCacheHeader[] | undefined,
policy: PublicCacheRuntimePolicy,
): NormalizedAsset {
return {
absoluteUrl: normalizePublicUrl(absoluteUrl, policy),
expectedByteLength: 0,
expectedContentType: "",
digestHex: ZERO_SHA256,
requestHeaders: normalizeRequestHeaders(requestHeaders, policy),
};
}
export function normalizeContentType(
input: string,
policy: PublicCacheRuntimePolicy,
): string {
if (
typeof input !== "string" ||
input.length < 1 ||
input.length > 256 ||
/[\r\n\0]/u.test(input) ||
!policy.isContentTypeAllowed(input)
) {
throw new CacheValidationFailure("POLICY_REJECTED");
}
return input
.split(";")
.map((part) => part.trim())
.filter((part) => part.length > 0)
.map((part, index) =>
index === 0 ? part.toLowerCase() : part,
)
.join("; ");
}
export function normalizePublicUrl(
input: string,
policy: PublicCacheRuntimePolicy,
): string {
if (typeof input !== "string" || input.length > 2_048) {
throw new CacheValidationFailure("INVALID_INPUT");
}
let url: URL;
try {
url = new URL(input);
} catch {
throw new CacheValidationFailure("INVALID_INPUT");
}
if (
url.origin !== policy.origin ||
!isAllowedPublicCacheOrigin(url) ||
url.username.length > 0 ||
url.password.length > 0 ||
url.hash.length > 0 ||
url.href === markerRequestUrl(policy) ||
url.href === activePointerRequestUrl(policy)
) {
throw new CacheValidationFailure("POLICY_REJECTED");
}
const forbidden = new Set(policy.forbiddenQueryParameterNames);
const allowed = new Set(policy.allowedQueryParameterNames);
const seenNames = new Set<string>();
for (const [rawName, value] of url.searchParams.entries()) {
const name = rawName.toLowerCase();
if (
forbidden.has(name) ||
!allowed.has(name) ||
seenNames.has(name) ||
!policy.isQueryParameterValueAllowed(name, value)
) {
throw new CacheValidationFailure("POLICY_REJECTED");
}
seenNames.add(name);
}
return url.href;
}
export function normalizeRequestHeaders(
input: readonly PublicCacheHeader[] | undefined,
policy: PublicCacheRuntimePolicy,
): readonly PublicCacheHeader[] {
const allowed = new Set(policy.allowedRequestHeaderNames);
const forbidden = new Set([
"authorization",
"cookie",
"proxy-authorization",
"range",
]);
const headers = new Headers();
for (const pair of input ?? []) {
if (
!Array.isArray(pair) ||
pair.length !== 2 ||
typeof pair[0] !== "string" ||
typeof pair[1] !== "string"
) {
throw new CacheValidationFailure("INVALID_INPUT");
}
const name = pair[0].toLowerCase();
if (
forbidden.has(name) ||
!allowed.has(name) ||
pair[1].length > 1_024 ||
/[\r\n\0]/u.test(pair[1])
) {
throw new CacheValidationFailure("POLICY_REJECTED");
}
headers.append(name, pair[1].trim());
}
return Object.freeze(
[...headers.entries()]
.sort(([left], [right]) => left.localeCompare(right))
.map(
([name, value]) =>
Object.freeze([name, value]) as PublicCacheHeader,
),
);
}
export async function readBoundedJson(
response: Response,
maximumBytes: number,
): Promise<unknown> {
const contentLength = response.headers.get("content-length");
if (
!Number.isSafeInteger(maximumBytes) ||
maximumBytes <= 0 ||
(contentLength !== null &&
(!/^\d+$/u.test(contentLength) ||
Number(contentLength) > maximumBytes))
) {
throw new CacheValidationFailure("CORRUPT_DATA");
}
if (!response.body) {
throw new CacheValidationFailure("CORRUPT_DATA");
}
const reader = response.body.getReader();
// Q-6.2-6. Chunks are kept as read; the budget is enforced on their total,
// never by preallocating it.
const chunks: Uint8Array[] = [];
let byteLength = 0;
let completelyRead = false;
try {
while (true) {
const chunk = await reader.read();
if (chunk.done) {
completelyRead = true;
break;
}
if (chunk.value.byteLength > maximumBytes - byteLength) {
throw new CacheValidationFailure("CORRUPT_DATA");
}
chunks.push(chunk.value);
byteLength += chunk.value.byteLength;
}
} catch (error) {
if (!completelyRead) {
cancelReaderSafely(
reader,
"Cache control JSON exceeded its read budget.",
);
}
throw error;
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(byteLength);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
let text: string;
try {
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
throw new CacheValidationFailure("CORRUPT_DATA");
}
try {
return JSON.parse(text);
} catch {
throw new CacheValidationFailure("CORRUPT_DATA");
}
}
export function cancelReaderSafely(
reader: ReadableStreamDefaultReader<Uint8Array>,
reason: string,
): void {
try {
void reader.cancel(reason).catch(() => undefined);
} catch {
// Cancellation is best effort once the bounded consumer has stopped.
}
}
export function isReleaseMarker(
value: unknown,
policy: PublicCacheRuntimePolicy,
): value is ReleaseMarker {
if (
!value ||
typeof value !== "object" ||
!("schemaVersion" in value) ||
value.schemaVersion !== 1 ||
!("verified" in value) ||
value.verified !== true ||
!("releaseRegistryId" in value) ||
typeof value.releaseRegistryId !== "string" ||
!policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) ||
!("manifestDigestHex" in value) ||
typeof value.manifestDigestHex !== "string" ||
!SHA256_HEX.test(value.manifestDigestHex) ||
!("entryCount" in value) ||
typeof value.entryCount !== "number" ||
!Number.isSafeInteger(value.entryCount) ||
!("totalBytes" in value) ||
typeof value.totalBytes !== "number" ||
!Number.isSafeInteger(value.totalBytes) ||
!("stagedAtEpochMs" in value) ||
typeof value.stagedAtEpochMs !== "number" ||
!Number.isSafeInteger(value.stagedAtEpochMs) ||
!("assets" in value) ||
!Array.isArray(value.assets) ||
value.assets.length > policy.maxEntriesPerRelease
) {
return false;
}
try {
const normalized = normalizeAssets(
value.assets.map((asset) => markerAssetToPublicAsset(asset)),
policy,
);
return stableJson(normalized) === stableJson(value.assets);
} catch {
return false;
}
}
export function markerAssetToPublicAsset(value: unknown): PublicCacheAsset {
if (!value || typeof value !== "object") {
throw new CacheValidationFailure("CORRUPT_DATA");
}
const asset = value as Partial<NormalizedAsset>;
return {
absoluteUrl: asset.absoluteUrl ?? "",
expectedByteLength: asset.expectedByteLength ?? -1,
expectedContentType: asset.expectedContentType ?? "",
integrity: {
algorithm: "SHA-256",
digestHex: asset.digestHex ?? "",
},
requestHeaders: asset.requestHeaders,
};
}
export function isActivePointer(
value: unknown,
policy: PublicCacheRuntimePolicy,
): value is ActiveReleasePointer {
return Boolean(
value &&
typeof value === "object" &&
"schemaVersion" in value &&
value.schemaVersion === 1 &&
"releaseRegistryId" in value &&
typeof value.releaseRegistryId === "string" &&
policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) &&
"manifestDigestHex" in value &&
typeof value.manifestDigestHex === "string" &&
SHA256_HEX.test(value.manifestDigestHex) &&
"candidateCacheName" in value &&
typeof value.candidateCacheName === "string" &&
value.candidateCacheName ===
releaseCacheName(
policy,
value.releaseRegistryId,
value.manifestDigestHex,
) &&
"rollbackCandidateCacheNames" in value &&
Array.isArray(value.rollbackCandidateCacheNames) &&
// 0929/02-01. The list length is not checked against the current
// `retainedPreviousReleaseCount`: a pointer written under a larger value
// is still a good pointer. The next activation trims the list (`slice`).
// The ceiling is the policy's own maximum.
value.rollbackCandidateCacheNames.length <=
MAX_RETAINED_PREVIOUS_RELEASE_COUNT &&
new Set(value.rollbackCandidateCacheNames).size ===
value.rollbackCandidateCacheNames.length &&
value.rollbackCandidateCacheNames.every(
(name) =>
typeof name === "string" &&
name !== value.candidateCacheName &&
isOwnedReleaseCacheName(name, policy),
) &&
"activatedAtEpochMs" in value &&
typeof value.activatedAtEpochMs === "number" &&
Number.isSafeInteger(value.activatedAtEpochMs),
);
}
export function isOwnedReleaseCacheName(
name: string,
policy: PublicCacheRuntimePolicy,
): boolean {
if (!name.startsWith(`${policy.ownedCachePrefix}release:`)) {
return false;
}
const remainder = name.slice(
`${policy.ownedCachePrefix}release:`.length,
);
const separator = remainder.lastIndexOf(":");
if (separator < 1) return false;
const releaseRegistryId = remainder.slice(0, separator);
const digestHex = remainder.slice(separator + 1);
return (
policy.isReleaseRegistryIdAllowed(releaseRegistryId) &&
SHA256_HEX.test(digestHex)
);
}
export function canonicalManifest(
releaseRegistryId: string,
assets: readonly NormalizedAsset[],
): string {
return [
"ca-public-cache-manifest-v1",
`release:${releaseRegistryId}`,
...[...assets]
.sort((left, right) => assetKey(left).localeCompare(assetKey(right)))
.map(
(asset) =>
`${assetKey(asset)}:${asset.expectedByteLength}:${JSON.stringify(asset.expectedContentType)}:${asset.digestHex}`,
),
"",
].join("\n");
}
export function assetKey(
asset: Pick<NormalizedAsset, "absoluteUrl" | "requestHeaders">,
): string {
return JSON.stringify([asset.absoluteUrl, asset.requestHeaders]);
}
export function markerRequest(policy: PublicCacheRuntimePolicy): Request {
return new Request(markerRequestUrl(policy), { method: "GET" });
}
export function activePointerRequest(policy: PublicCacheRuntimePolicy): Request {
return new Request(activePointerRequestUrl(policy), { method: "GET" });
}
export function markerRequestUrl(policy: PublicCacheRuntimePolicy): string {
return `${policy.origin}/.well-known/ca-public-cache-v1/candidate`;
}
export function activePointerRequestUrl(policy: PublicCacheRuntimePolicy): string {
return `${policy.origin}/.well-known/ca-public-cache-v1/active`;
}
export function controlCacheName(policy: PublicCacheRuntimePolicy): string {
return `${policy.ownedCachePrefix}control`;
}
export function releaseCacheName(
policy: PublicCacheRuntimePolicy,
releaseRegistryId: string,
manifestDigestHex: string,
): string {
return `${policy.ownedCachePrefix}release:${releaseRegistryId}:${manifestDigestHex}`;
}
export function jsonResponse(value: unknown): Response {
return new Response(JSON.stringify(value), {
status: 200,
headers: {
"cache-control": "no-store",
"content-type": "application/json; charset=utf-8",
},
});
}
export function validationFailure(
error: unknown,
operation: BrowserDataOperation,
): BrowserFailureResult {
return error instanceof CacheValidationFailure
? failureForCode(error.code, operation)
: asFailure(browserDataFailure("INVALID_INPUT", operation));
}
export function exceptionFailure(
error: unknown,
operation: BrowserDataOperation,
): BrowserFailureResult {
if (error instanceof CacheValidationFailure) {
return failureForCode(error.code, operation);
}
const mapped = mapBrowserDataException(error, operation);
if (mapped.ok) {
return asFailure(
browserDataFailure("UNAVAILABLE", operation, {
retryable: true,
recovery: "RETRY",
}),
);
}
return mapped;
}
export function failureForCode(
code: BrowserDataFailureCode,
operation: BrowserDataOperation,
): BrowserFailureResult {
if (code === "ABORTED") {
return asFailure(browserDataFailure(code, operation));
}
if (code === "INTEGRITY_FAILED" || code === "CORRUPT_DATA") {
return asFailure(
browserDataFailure(code, operation, { recovery: "REHYDRATE" }),
);
}
if (code === "QUOTA_EXCEEDED") {
return asFailure(
browserDataFailure(code, operation, {
retryable: true,
recovery: "ONLINE_ONLY",
}),
);
}
if (code === "BLOCKED" || code === "UNAVAILABLE") {
return asFailure(
browserDataFailure(code, operation, {
retryable: true,
recovery: "RETRY",
}),
);
}
return asFailure(browserDataFailure(code, operation));
}
export function asFailure(
result: BrowserDataResult<never>,
): BrowserFailureResult {
if (result.ok) {
throw new TypeError("Expected a browser data failure.");
}
return result;
}
export async function sha256Hex(
crypto: PublicCacheCryptoFacade,
bytes: Uint8Array<ArrayBuffer>,
): Promise<string> {
const digest = await crypto.digestSha256(bytes);
let hex = "";
for (const byte of new Uint8Array(digest)) {
hex += byte.toString(16).padStart(2, "0");
}
return hex;
}
export function stableJson(value: unknown): string {
return canonicalJson(value, () => {
throw new CacheValidationFailure("CORRUPT_DATA");
});
}
export const SHA256_HEX = /^[a-f0-9]{64}$/u;
export const ZERO_SHA256 = "0".repeat(64);
export const MAX_CONTROL_JSON_BYTES = 2 * 1024 * 1024;