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, 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): Promise; }>; 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 { 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(); 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 { 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, 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; 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) && value.rollbackCandidateCacheNames.length <= policy.retainedPreviousReleaseCount && 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, ): 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, ): BrowserFailureResult { if (result.ok) { throw new TypeError("Expected a browser data failure."); } return result; } export async function sha256Hex( crypto: PublicCacheCryptoFacade, bytes: Uint8Array, ): Promise { 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 { if ( value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" ) { return JSON.stringify(value); } if (Array.isArray(value)) { return `[${value.map(stableJson).join(",")}]`; } if (typeof value === "object") { const record = value as Record; return `{${Object.keys(record) .sort() .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`) .join(",")}}`; } 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;