public-response-cache-adapter.ts (1986 lines) and download-delivery-adapter.ts (1491 lines) mixed the facade with codecs and validators. Moved verbatim: - cache-storage/public-cache-codec.ts: manifest normalization and canonical digest input, marker/active-pointer validation, bounded control JSON, owned cache names, CacheValidationFailure -> Result mapping. - cache-storage/public-cache-response-validation.ts: response admission (status, directives, Content-Type, Vary, bounded body, digest). - browser-files/download-input-validation.ts: request snapshot, input/limit checks, presigned and browser-managed capability validation, handoff target. The adapters drop to 1164 and 1157 lines. Two non-verbatim edits: validateDownloadInput takes a structural DownloadInputValidationOptions instead of DownloadDeliveryAdapterOptions (no import cycle), and readBodyBounded races reads on the kernel createAbortableOperation instead of its own abort listener. Moving it out of a primitive-importing file would otherwise have raised the hand-rolled abort ratchet to 20/19; the abort outcome (ABORTED, reader cancelled) is unchanged. Verified: characterization tests added first and passing before the move (cache manifest/response/control-JSON failure codes, lookup abort during a pending body read; download input validation codes); a line diff confirms the moved code is verbatim apart from the two edits above. Inventory 139/139, lane gates, check:browser-file-storage-boundaries pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
240 lines
7.5 KiB
TypeScript
240 lines
7.5 KiB
TypeScript
import type { PublicCacheHeader } from "../../application/ports/browser-file-storage/cache-storage-ports.ts";
|
|
import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts";
|
|
import { browserDataSuccess } from "../browser-file-storage/result.ts";
|
|
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
|
import {
|
|
CacheValidationFailure,
|
|
cancelReaderSafely,
|
|
exceptionFailure,
|
|
normalizeContentType,
|
|
sha256Hex,
|
|
type NormalizedAsset,
|
|
type PublicCacheCryptoFacade,
|
|
} from "./public-cache-codec.ts";
|
|
import type { PublicCacheRuntimePolicy } from "./public-cache-policy.ts";
|
|
|
|
/**
|
|
* Q-6.2-11. Admission of a network or cached response for one manifest asset:
|
|
* status, cache directives, content type, Vary, bounded body read and digest.
|
|
* Moved verbatim out of the adapter.
|
|
*/
|
|
|
|
export type CacheReadResult = Readonly<{
|
|
bytes: Uint8Array;
|
|
headers: readonly PublicCacheHeader[];
|
|
}>;
|
|
|
|
export async function readAndValidateResponse(
|
|
response: Response,
|
|
asset: NormalizedAsset,
|
|
policy: PublicCacheRuntimePolicy,
|
|
crypto: PublicCacheCryptoFacade,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<BrowserDataResult<CacheReadResult>> {
|
|
try {
|
|
if (
|
|
response.status !== 200 ||
|
|
!response.ok ||
|
|
response.redirected ||
|
|
response.type === "opaque" ||
|
|
response.type === "opaqueredirect" ||
|
|
response.type === "error" ||
|
|
(response.url.length > 0 &&
|
|
new URL(response.url).href !== asset.absoluteUrl)
|
|
) {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
const cacheControl = response.headers.get("cache-control") ?? "";
|
|
const directives = new Set(
|
|
cacheControl
|
|
.split(",")
|
|
.map((part) => part.trim().split("=", 1)[0]?.toLowerCase())
|
|
.filter((part): part is string => Boolean(part)),
|
|
);
|
|
if (
|
|
directives.has("private") ||
|
|
directives.has("no-store") ||
|
|
directives.has("no-cache") ||
|
|
(response.headers.get("pragma") ?? "")
|
|
.toLowerCase()
|
|
.includes("no-cache") ||
|
|
response.headers.has("set-cookie") ||
|
|
response.headers.has("set-cookie2") ||
|
|
response.headers.has("www-authenticate")
|
|
) {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
const contentType = response.headers.get("content-type");
|
|
if (!contentType || !policy.isContentTypeAllowed(contentType)) {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
if (
|
|
normalizeContentType(contentType, policy) !==
|
|
asset.expectedContentType
|
|
) {
|
|
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
|
}
|
|
validateVary(response.headers.get("vary"), asset, policy);
|
|
const declaredLength = response.headers.get("content-length");
|
|
if (
|
|
declaredLength !== null &&
|
|
(!/^\d+$/u.test(declaredLength) ||
|
|
Number(declaredLength) > policy.maxEntryBytes)
|
|
) {
|
|
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
|
}
|
|
|
|
const bytes = await readBodyBounded(
|
|
response,
|
|
asset.expectedByteLength,
|
|
policy.maxEntryBytes,
|
|
signal,
|
|
);
|
|
const digestHex = await sha256Hex(crypto, bytes);
|
|
if (digestHex !== asset.digestHex) {
|
|
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
|
}
|
|
const headers = sanitizedResponseHeaders(response.headers, policy);
|
|
return browserDataSuccess({ bytes, headers });
|
|
} catch (error) {
|
|
return exceptionFailure(error, "CACHE_STAGE");
|
|
}
|
|
}
|
|
|
|
export async function readBodyBounded(
|
|
response: Response,
|
|
expectedByteLength: number,
|
|
maxEntryBytes: number,
|
|
signal: AbortSignal | undefined,
|
|
): Promise<Uint8Array> {
|
|
if (expectedByteLength > maxEntryBytes) {
|
|
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
|
}
|
|
if (!response.body) {
|
|
if (expectedByteLength === 0) return new Uint8Array();
|
|
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
|
}
|
|
const output = new Uint8Array(expectedByteLength);
|
|
const reader = response.body.getReader();
|
|
let offset = 0;
|
|
// The kernel owner ends a pending read on abort instead of a listener pair.
|
|
const owner = createAbortableOperation({ signal });
|
|
const abortRead = (): CacheValidationFailure => {
|
|
cancelReaderSafely(reader, "Public cache body read was aborted.");
|
|
return new CacheValidationFailure("ABORTED");
|
|
};
|
|
try {
|
|
while (true) {
|
|
if (owner.signal.aborted) throw abortRead();
|
|
const raced = await owner.race(reader.read());
|
|
if (raced.kind === "REJECTED") throw raced.reason;
|
|
if (raced.kind === "TERMINAL" || owner.signal.aborted) {
|
|
throw abortRead();
|
|
}
|
|
const part = raced.value;
|
|
if (part.done) break;
|
|
if (
|
|
!(part.value instanceof Uint8Array) ||
|
|
offset + part.value.byteLength > expectedByteLength ||
|
|
offset + part.value.byteLength > maxEntryBytes
|
|
) {
|
|
cancelReaderSafely(
|
|
reader,
|
|
"Public cache body exceeded its read budget.",
|
|
);
|
|
throw new CacheValidationFailure(
|
|
offset + part.value.byteLength > maxEntryBytes
|
|
? "LIMIT_EXCEEDED"
|
|
: "INTEGRITY_FAILED",
|
|
);
|
|
}
|
|
output.set(part.value, offset);
|
|
offset += part.value.byteLength;
|
|
}
|
|
} finally {
|
|
owner.close();
|
|
reader.releaseLock();
|
|
}
|
|
if (offset !== expectedByteLength) {
|
|
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
|
}
|
|
return output;
|
|
}
|
|
|
|
export function validateVary(
|
|
vary: string | null,
|
|
asset: NormalizedAsset,
|
|
policy: PublicCacheRuntimePolicy,
|
|
): void {
|
|
const expected = new Set(
|
|
asset.requestHeaders.map(([name]) => name.toLowerCase()),
|
|
);
|
|
const actual = new Set<string>();
|
|
if (!vary) {
|
|
if (expected.size > 0) {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
return;
|
|
}
|
|
const allowed = new Set(policy.allowedVaryHeaderNames);
|
|
for (const item of vary.split(",")) {
|
|
const name = item.trim().toLowerCase();
|
|
// Browser-managed: Accept-Encoding is a forbidden request header, so no
|
|
// script-built Request carries it. Stored and lookup requests both lack it
|
|
// and Cache.match still matches exactly. nginx `gzip_vary` and most CDNs
|
|
// send it on every compressible asset.
|
|
if (name === "accept-encoding") continue;
|
|
if (
|
|
name === "*" ||
|
|
name === "authorization" ||
|
|
name === "cookie" ||
|
|
!allowed.has(name)
|
|
) {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
actual.add(name);
|
|
}
|
|
if (
|
|
actual.size !== expected.size ||
|
|
[...actual].some((name) => !expected.has(name))
|
|
) {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
}
|
|
|
|
export function sanitizedResponseHeaders(
|
|
headers: Headers,
|
|
policy: PublicCacheRuntimePolicy,
|
|
): readonly PublicCacheHeader[] {
|
|
const allowed = new Set(policy.allowedResponseHeaderNames);
|
|
const sanitized: PublicCacheHeader[] = [];
|
|
for (const [name, value] of headers.entries()) {
|
|
if (!allowed.has(name)) {
|
|
if (policy.unknownResponseHeaderAction === "REJECT") {
|
|
throw new CacheValidationFailure("POLICY_REJECTED");
|
|
}
|
|
continue;
|
|
}
|
|
sanitized.push(Object.freeze([name, value]));
|
|
}
|
|
return Object.freeze(sanitized);
|
|
}
|
|
|
|
export function createNativeRequest(
|
|
asset: NormalizedAsset,
|
|
signal?: AbortSignal,
|
|
): Request {
|
|
return new Request(asset.absoluteUrl, {
|
|
method: "GET",
|
|
headers: new Headers(
|
|
asset.requestHeaders.map(([name, value]) => [name, value]),
|
|
),
|
|
credentials: "omit",
|
|
cache: "no-store",
|
|
redirect: "error",
|
|
referrerPolicy: "no-referrer",
|
|
mode: "same-origin",
|
|
signal,
|
|
});
|
|
}
|