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 at8210d48. 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 at8210d48first 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)
1073 lines
30 KiB
TypeScript
1073 lines
30 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type {
|
|
FileVerificationReceipt,
|
|
LocalFileRef,
|
|
} from "../../src/application/ports/browser-file-storage/file.ts";
|
|
import { BrowserFileVault } from "../../src/adapters/browser-files/browser-file-vault.ts";
|
|
import {
|
|
BrowserTransientPreview,
|
|
ObjectUrlLeaseRegistry,
|
|
} from "../../src/adapters/browser-files/object-url-lease.ts";
|
|
import {
|
|
sanitizeSuggestedFileName,
|
|
type RegisteredFileInspectionPolicy,
|
|
type RegisteredFileSelectionPolicy,
|
|
} from "../../src/adapters/browser-files/file-policy.ts";
|
|
import {
|
|
BrowserFilePolicyRegistry,
|
|
browserFilePolicyReference,
|
|
} from "../../src/adapters/browser-files/browser-file-policy-registry.ts";
|
|
|
|
const pngSelectionPolicy: RegisteredFileSelectionPolicy = Object.freeze({
|
|
policyId: "avatar-v1",
|
|
purpose: "avatar",
|
|
classification: "PERSONAL",
|
|
multiple: false,
|
|
maxCount: 1,
|
|
maxFileBytes: 1_024,
|
|
maxTotalBytes: 1_024,
|
|
allowEmpty: false,
|
|
accept: Object.freeze([
|
|
Object.freeze({
|
|
mediaType: "image/png",
|
|
extensions: Object.freeze([".png"]),
|
|
}),
|
|
]),
|
|
});
|
|
|
|
const pngInspectionPolicy: RegisteredFileInspectionPolicy = Object.freeze({
|
|
policyId: "avatar-v1",
|
|
maxInspectionBytes: 16,
|
|
acceptedSignatures: Object.freeze([
|
|
Object.freeze({
|
|
mediaType: "image/png",
|
|
extensions: Object.freeze([".png"]),
|
|
patterns: Object.freeze([
|
|
Object.freeze({
|
|
offset: 0,
|
|
bytes: Object.freeze([
|
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
]),
|
|
}),
|
|
]),
|
|
}),
|
|
]),
|
|
});
|
|
const pngPolicy = browserFilePolicyReference(
|
|
"avatar",
|
|
"inspect-and-preview-png",
|
|
);
|
|
|
|
function pngPolicies(
|
|
maxPreviewBytes = 10,
|
|
): BrowserFilePolicyRegistry {
|
|
return new BrowserFilePolicyRegistry({
|
|
profiles: [
|
|
{
|
|
reference: pngPolicy,
|
|
inspection: pngInspectionPolicy,
|
|
preview: {
|
|
allowedMediaTypes: ["image/png"],
|
|
maxPreviewBytes,
|
|
},
|
|
},
|
|
],
|
|
hardLimits: {
|
|
maxInspectionBytes: 64 * 1024,
|
|
maxRetainedFileBytes: 2_048,
|
|
maxPreviewBytes,
|
|
maxObjectUrlBytes: 2_048,
|
|
maxTransferBytes: 2_048,
|
|
},
|
|
});
|
|
}
|
|
|
|
async function verifiedPngPreview(
|
|
leases: ObjectUrlLeaseRegistry,
|
|
reportedType = "image/png",
|
|
) {
|
|
const policies = pngPolicies();
|
|
const vault = new BrowserFileVault({ policies });
|
|
const captured = vault.captureFiles(
|
|
[
|
|
new File(
|
|
[new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])],
|
|
"preview.png",
|
|
{ type: reportedType, lastModified: 1 },
|
|
),
|
|
],
|
|
{ ...pngSelectionPolicy, accept: Object.freeze([]) },
|
|
);
|
|
if (!captured.ok || !captured.value[0]) throw new Error("capture");
|
|
const ref = captured.value[0].ref;
|
|
const inspected = await vault.inspect({
|
|
ref,
|
|
policy: pngPolicy,
|
|
signal: new AbortController().signal,
|
|
});
|
|
if (!inspected.ok || !inspected.value.verificationReceipt) {
|
|
throw new Error("inspect");
|
|
}
|
|
const verificationReceipt = inspected.value.verificationReceipt;
|
|
const preview = new BrowserTransientPreview({
|
|
files: vault,
|
|
policies,
|
|
leases,
|
|
hardMaxPreviewBytes: 10,
|
|
});
|
|
return {
|
|
preview,
|
|
request: (signal: AbortSignal) => ({
|
|
ref,
|
|
verificationReceipt,
|
|
policy: pngPolicy,
|
|
signal,
|
|
}),
|
|
};
|
|
}
|
|
|
|
describe("browser file content policy", () => {
|
|
it("neutralizes path, bidi, device-name and executable filename tricks", () => {
|
|
expect(
|
|
sanitizeSuggestedFileName("..\\CON\u202Egpj.exe", {
|
|
safeExtension: ".pdf",
|
|
}),
|
|
).toBe("CONgpj.pdf");
|
|
expect(
|
|
sanitizeSuggestedFileName("invoice.exe.pdf", {
|
|
safeExtension: ".pdf",
|
|
}),
|
|
).toBe("invoice_exe.pdf");
|
|
expect(
|
|
sanitizeSuggestedFileName("CON.txt", {
|
|
safeExtension: ".txt",
|
|
}),
|
|
).toBe("download.txt");
|
|
expect(
|
|
sanitizeSuggestedFileName("report.tar.gz", {
|
|
safeExtension: ".tar.gz",
|
|
}),
|
|
).toBe("report.tar.gz");
|
|
|
|
const bounded = sanitizeSuggestedFileName("가".repeat(100), {
|
|
safeExtension: ".txt",
|
|
maxUtf8Bytes: 24,
|
|
});
|
|
expect(new TextEncoder().encode(bounded).byteLength).toBeLessThanOrEqual(
|
|
24,
|
|
);
|
|
expect(
|
|
sanitizeSuggestedFileName("😀", {
|
|
safeExtension: ".bin",
|
|
maxUtf8Bytes: 5,
|
|
}),
|
|
).toBe("d.bin");
|
|
});
|
|
|
|
it("truncates a huge filename in linear time with the same result (Q-6.2-10)", () => {
|
|
const policy = { safeExtension: ".pdf", maxUtf8Bytes: 180 } as const;
|
|
expect(
|
|
sanitizeSuggestedFileName(`${"a".repeat(175)} bbbb.pdf`, policy),
|
|
).toBe(`${"a".repeat(175)}.pdf`);
|
|
expect(
|
|
sanitizeSuggestedFileName(`${"가".repeat(100)}.pdf`, policy),
|
|
).toBe(`${"가".repeat(58)}.pdf`);
|
|
expect(
|
|
sanitizeSuggestedFileName(`${"😀".repeat(50)}.pdf`, policy),
|
|
).toBe(`${"😀".repeat(44)}.pdf`);
|
|
|
|
// A server-supplied name used to be re-encoded whole once per dropped
|
|
// code point: O(n^2), so a 100k-character name froze the tab.
|
|
const encode = vi.spyOn(TextEncoder.prototype, "encode");
|
|
try {
|
|
expect(
|
|
sanitizeSuggestedFileName("x".repeat(5_000), policy),
|
|
).toBe(`${"x".repeat(176)}.pdf`);
|
|
expect(encode.mock.calls.length).toBeLessThan(10);
|
|
} finally {
|
|
encode.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("keeps native files behind opaque refs and performs bounded reads", async () => {
|
|
const policies = pngPolicies();
|
|
const vault = new BrowserFileVault({
|
|
policies,
|
|
createReference: () => "file:opaque-1",
|
|
});
|
|
const bytes = new Uint8Array([
|
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2,
|
|
]);
|
|
const captured = vault.captureFiles(
|
|
[
|
|
new File([bytes], "portrait.png", {
|
|
type: "image/png",
|
|
lastModified: 100,
|
|
}),
|
|
],
|
|
pngSelectionPolicy,
|
|
);
|
|
expect(captured.ok).toBe(true);
|
|
if (!captured.ok) return;
|
|
const candidate = captured.value[0];
|
|
expect(candidate).toBeDefined();
|
|
if (!candidate) return;
|
|
expect(candidate.ref).not.toContain(candidate.displayName);
|
|
|
|
const signal = new AbortController().signal;
|
|
expect(
|
|
await vault.inspect({
|
|
ref: candidate.ref,
|
|
policy: pngPolicy,
|
|
signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
detectedMediaType: "image/png",
|
|
normalizedExtension: ".png",
|
|
signature: "MATCHED",
|
|
},
|
|
});
|
|
expect(
|
|
await vault.readRange({
|
|
ref: candidate.ref,
|
|
offset: 8,
|
|
length: 2,
|
|
signal,
|
|
}),
|
|
).toEqual({ ok: true, value: new Uint8Array([1, 2]) });
|
|
|
|
const opened = await vault.openSource({
|
|
ref: candidate.ref,
|
|
signal,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (opened.ok) {
|
|
const streamed: number[] = [];
|
|
for await (const chunk of opened.value.stream(signal)) {
|
|
expect(chunk.ok).toBe(true);
|
|
if (chunk.ok) streamed.push(...chunk.value);
|
|
}
|
|
expect(streamed).toEqual([...bytes]);
|
|
}
|
|
|
|
vault.release(candidate.ref);
|
|
expect(vault.activeVerificationCount).toBe(0);
|
|
expect(
|
|
await vault.readRange({
|
|
ref: candidate.ref,
|
|
offset: 0,
|
|
length: 1,
|
|
signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "NOT_FOUND", recovery: "RESELECT" },
|
|
});
|
|
});
|
|
|
|
it("snapshots vault requests before asynchronous file resolution", async () => {
|
|
const references = ["file:a", "file:b"];
|
|
const policies = pngPolicies(32);
|
|
const vault = new BrowserFileVault({
|
|
policies,
|
|
createReference: () =>
|
|
references.shift() ?? "file:unexpected",
|
|
createVerificationReceipt: () => "verification:a",
|
|
});
|
|
const pngHeader = [
|
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
];
|
|
const captured = vault.captureFiles(
|
|
[
|
|
new File(
|
|
[new Uint8Array([...pngHeader, 1, 2])],
|
|
"a.png",
|
|
{ type: "image/png", lastModified: 1 },
|
|
),
|
|
new File(
|
|
[new Uint8Array([...pngHeader, 9, 8])],
|
|
"b.png",
|
|
{ type: "image/png", lastModified: 2 },
|
|
),
|
|
],
|
|
{
|
|
...pngSelectionPolicy,
|
|
multiple: true,
|
|
maxCount: 2,
|
|
maxTotalBytes: 2_048,
|
|
},
|
|
);
|
|
expect(captured.ok).toBe(true);
|
|
if (
|
|
!captured.ok ||
|
|
!captured.value[0] ||
|
|
!captured.value[1]
|
|
) {
|
|
return;
|
|
}
|
|
const [first, second] = captured.value;
|
|
const active = new AbortController();
|
|
const replacement = new AbortController();
|
|
replacement.abort();
|
|
|
|
const readRequest = {
|
|
ref: first.ref,
|
|
offset: 8,
|
|
length: 1,
|
|
signal: active.signal,
|
|
};
|
|
const pendingRead = vault.readRange(readRequest);
|
|
readRequest.ref = second.ref;
|
|
readRequest.offset = 9;
|
|
readRequest.signal = replacement.signal;
|
|
expect(await pendingRead).toEqual({
|
|
ok: true,
|
|
value: new Uint8Array([1]),
|
|
});
|
|
|
|
const inspectionRequest = {
|
|
ref: first.ref,
|
|
policy: pngPolicy,
|
|
signal: active.signal,
|
|
};
|
|
const pendingInspection = vault.inspect(inspectionRequest);
|
|
inspectionRequest.ref = second.ref;
|
|
inspectionRequest.policy = browserFilePolicyReference(
|
|
"forged",
|
|
"forged",
|
|
);
|
|
inspectionRequest.signal = replacement.signal;
|
|
expect(await pendingInspection).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
byteLength: 10,
|
|
verificationReceipt: "verification:a",
|
|
},
|
|
});
|
|
|
|
const sourceRequest = {
|
|
ref: first.ref,
|
|
signal: active.signal,
|
|
};
|
|
const pendingSource = vault.openSource(sourceRequest);
|
|
sourceRequest.ref = second.ref;
|
|
sourceRequest.signal = replacement.signal;
|
|
const opened = await pendingSource;
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
const streamed: number[] = [];
|
|
for await (const chunk of opened.value.stream(active.signal)) {
|
|
expect(chunk.ok).toBe(true);
|
|
if (chunk.ok) streamed.push(...chunk.value);
|
|
}
|
|
expect(streamed).toEqual([...pngHeader, 1, 2]);
|
|
});
|
|
|
|
it("snapshots file handles and loader methods before awaiting them", async () => {
|
|
const policies = pngPolicies();
|
|
let reference = 0;
|
|
const vault = new BrowserFileVault({
|
|
policies,
|
|
createReference: () => `file:handle-${reference++}`,
|
|
});
|
|
let resolveFirst: ((file: File) => void) | undefined;
|
|
const firstFile = new File(["a"], "a.txt", {
|
|
type: "text/plain",
|
|
lastModified: 1,
|
|
});
|
|
const secondFile = new File(["b"], "b.txt", {
|
|
type: "text/plain",
|
|
lastModified: 2,
|
|
});
|
|
const originalFirst = vi.fn(
|
|
() =>
|
|
new Promise<File>((resolve) => {
|
|
resolveFirst = resolve;
|
|
}),
|
|
);
|
|
const originalSecond = vi.fn(async () => secondFile);
|
|
const replaced = vi.fn(async () =>
|
|
new File(["x"], "x.txt"),
|
|
);
|
|
const firstHandle = {
|
|
kind: "file" as const,
|
|
name: "a.txt",
|
|
getFile: originalFirst,
|
|
};
|
|
const secondHandle = {
|
|
kind: "file" as const,
|
|
name: "b.txt",
|
|
getFile: originalSecond,
|
|
};
|
|
const handles = [firstHandle, secondHandle];
|
|
const pending = vault.captureHandles(
|
|
handles,
|
|
{
|
|
...pngSelectionPolicy,
|
|
multiple: true,
|
|
maxCount: 2,
|
|
accept: Object.freeze([]),
|
|
},
|
|
new AbortController().signal,
|
|
);
|
|
|
|
firstHandle.getFile = replaced;
|
|
secondHandle.getFile = replaced;
|
|
handles.splice(1, 1, {
|
|
kind: "file",
|
|
name: "x.txt",
|
|
getFile: replaced,
|
|
});
|
|
resolveFirst?.(firstFile);
|
|
|
|
const result = await pending;
|
|
expect(result).toMatchObject({
|
|
ok: true,
|
|
value: [
|
|
{ displayName: "a.txt" },
|
|
{ displayName: "b.txt" },
|
|
],
|
|
});
|
|
expect(originalFirst).toHaveBeenCalledOnce();
|
|
expect(originalSecond).toHaveBeenCalledOnce();
|
|
expect(replaced).not.toHaveBeenCalled();
|
|
if (!result.ok || !result.value[1]) return;
|
|
expect(
|
|
await vault.resolveFile(
|
|
result.value[1].ref,
|
|
new AbortController().signal,
|
|
),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: secondFile,
|
|
});
|
|
expect(originalSecond).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("marks MIME/extension/signature disagreement and stale handles", async () => {
|
|
const refs = ["file:mismatch", "file:stale"];
|
|
const policies = pngPolicies();
|
|
const vault = new BrowserFileVault({
|
|
policies,
|
|
createReference: () => refs.shift() ?? "file:unexpected",
|
|
});
|
|
const permissive = {
|
|
...pngSelectionPolicy,
|
|
accept: Object.freeze([]),
|
|
};
|
|
const mismatch = vault.captureFiles(
|
|
[
|
|
new File(
|
|
[
|
|
new Uint8Array([
|
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
]),
|
|
],
|
|
"portrait.jpg",
|
|
{ type: "image/jpeg", lastModified: 100 },
|
|
),
|
|
],
|
|
permissive,
|
|
);
|
|
expect(mismatch.ok).toBe(true);
|
|
if (!mismatch.ok || !mismatch.value[0]) return;
|
|
expect(
|
|
await vault.inspect({
|
|
ref: mismatch.value[0].ref,
|
|
policy: pngPolicy,
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
detectedMediaType: "image/png",
|
|
signature: "MISMATCHED",
|
|
verificationReceipt: null,
|
|
},
|
|
});
|
|
|
|
let current = new File([new Uint8Array([1])], "state.bin", {
|
|
lastModified: 1,
|
|
});
|
|
const handle = {
|
|
kind: "file" as const,
|
|
name: "state.bin",
|
|
getFile: vi.fn(async () => current),
|
|
};
|
|
const handleCapture = await vault.captureHandles(
|
|
[handle],
|
|
permissive,
|
|
new AbortController().signal,
|
|
);
|
|
expect(handleCapture.ok).toBe(true);
|
|
if (!handleCapture.ok || !handleCapture.value[0]) return;
|
|
current = new File([new Uint8Array([1, 2])], "state.bin", {
|
|
lastModified: 2,
|
|
});
|
|
expect(
|
|
await vault.resolveFile(
|
|
handleCapture.value[0].ref,
|
|
new AbortController().signal,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "STALE_RESULT", recovery: "RESELECT" },
|
|
});
|
|
});
|
|
|
|
it("owns preview object URL leases and rejects active content", async () => {
|
|
const revoked: string[] = [];
|
|
const createObjectURL = vi.fn(() => "blob:test-1");
|
|
const leases = new ObjectUrlLeaseRegistry({
|
|
createObjectURL,
|
|
revokeObjectURL: (url) => revoked.push(url),
|
|
});
|
|
const policies = pngPolicies();
|
|
const vault = new BrowserFileVault({
|
|
policies,
|
|
createReference: () => "file:preview",
|
|
createVerificationReceipt: () => "verification:preview",
|
|
});
|
|
const capture = vault.captureFiles(
|
|
[
|
|
new File(
|
|
[
|
|
new Uint8Array([
|
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
]),
|
|
],
|
|
"preview.png",
|
|
{
|
|
type: "image/png",
|
|
lastModified: 1,
|
|
},
|
|
),
|
|
],
|
|
pngSelectionPolicy,
|
|
);
|
|
expect(capture.ok).toBe(true);
|
|
if (!capture.ok || !capture.value[0]) return;
|
|
const inspected = await vault.inspect({
|
|
ref: capture.value[0].ref,
|
|
policy: pngPolicy,
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(inspected.ok).toBe(true);
|
|
if (!inspected.ok || !inspected.value.verificationReceipt) return;
|
|
const verificationReceipt =
|
|
inspected.value.verificationReceipt;
|
|
const preview = new BrowserTransientPreview({
|
|
files: vault,
|
|
policies,
|
|
leases,
|
|
hardMaxPreviewBytes: 10,
|
|
observer: {
|
|
record() {
|
|
throw new Error("ignored");
|
|
},
|
|
},
|
|
});
|
|
const created = await preview.create({
|
|
ref: capture.value[0].ref,
|
|
verificationReceipt,
|
|
policy: pngPolicy,
|
|
maxPreviewBytes: 10,
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(created.ok).toBe(true);
|
|
if (created.ok) {
|
|
created.value.release();
|
|
created.value.release();
|
|
}
|
|
expect(revoked).toEqual(["blob:test-1"]);
|
|
expect(leases.activeLeaseCount).toBe(0);
|
|
|
|
expect(
|
|
await preview.create({
|
|
ref: capture.value[0].ref,
|
|
verificationReceipt,
|
|
policy: pngPolicy,
|
|
maxPreviewBytes: 11,
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "LIMIT_EXCEEDED" },
|
|
});
|
|
expect(createObjectURL).toHaveBeenCalledOnce();
|
|
|
|
expect(
|
|
await preview.create({
|
|
ref: capture.value[0].ref as LocalFileRef,
|
|
verificationReceipt:
|
|
"verification:forged" as FileVerificationReceipt,
|
|
policy: pngPolicy,
|
|
maxPreviewBytes: 10,
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "POLICY_REJECTED" },
|
|
});
|
|
});
|
|
|
|
it("returns ABORTED without a lease when the caller aborts right after create() (02-01)", async () => {
|
|
const revoked: string[] = [];
|
|
let urlSequence = 0;
|
|
const leases = new ObjectUrlLeaseRegistry({
|
|
createObjectURL: () => `blob:aborted-${urlSequence++}`,
|
|
revokeObjectURL: (url) => revoked.push(url),
|
|
});
|
|
const { preview, request } = await verifiedPngPreview(leases);
|
|
|
|
const controller = new AbortController();
|
|
// Same-turn abort: the effect cleanup of a React StrictMode double effect.
|
|
const pending = preview.create(request(controller.signal));
|
|
controller.abort();
|
|
|
|
expect(await pending).toMatchObject({
|
|
ok: false,
|
|
error: { code: "ABORTED", operation: "PREVIEW" },
|
|
});
|
|
expect(leases.activeLeaseCount).toBe(0);
|
|
expect(urlSequence).toBe(0);
|
|
expect(revoked).toEqual([]);
|
|
});
|
|
|
|
it("reports a preview that finds every lease slot in use as retryable (02-04)", async () => {
|
|
let urlSequence = 0;
|
|
const leases = new ObjectUrlLeaseRegistry(
|
|
{
|
|
createObjectURL: () => `blob:slot-${urlSequence++}`,
|
|
revokeObjectURL() {},
|
|
},
|
|
{
|
|
hardMaxActiveLeases: 1,
|
|
hardMaxSingleLeaseBytes: 16,
|
|
hardMaxAggregateLeaseBytes: 16,
|
|
},
|
|
);
|
|
const { preview, request } = await verifiedPngPreview(leases);
|
|
const held = leases.create(new Blob([new Uint8Array(1)]));
|
|
|
|
expect(
|
|
await preview.create(request(new AbortController().signal)),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
code: "LIMIT_EXCEEDED",
|
|
retryable: true,
|
|
recovery: "RETRY",
|
|
},
|
|
});
|
|
held.release();
|
|
expect(
|
|
await preview.create(request(new AbortController().signal)),
|
|
).toMatchObject({ ok: true });
|
|
});
|
|
|
|
it("types the preview Blob from the signature, not from File.type (02-08)", async () => {
|
|
const blobs: Blob[] = [];
|
|
const leases = new ObjectUrlLeaseRegistry({
|
|
createObjectURL: (blob) => {
|
|
blobs.push(blob);
|
|
return "blob:typed";
|
|
},
|
|
revokeObjectURL() {},
|
|
});
|
|
// An empty File.type still passes the signature check, so only the typed
|
|
// slice decides how the browser interprets the object URL.
|
|
const { preview, request } = await verifiedPngPreview(leases, "");
|
|
|
|
expect(
|
|
await preview.create(request(new AbortController().signal)),
|
|
).toMatchObject({ ok: true, value: { mediaType: "image/png" } });
|
|
expect(blobs.map((blob) => blob.type)).toEqual(["image/png"]);
|
|
});
|
|
|
|
it("cannot weaken the built-in active-content preview denylist", async () => {
|
|
const htmlPolicy = browserFilePolicyReference(
|
|
"active-content",
|
|
"preview-html",
|
|
);
|
|
const policies = new BrowserFilePolicyRegistry({
|
|
profiles: [
|
|
{
|
|
reference: htmlPolicy,
|
|
inspection: {
|
|
policyId: "html-signature-v1",
|
|
maxInspectionBytes: 6,
|
|
acceptedSignatures: [
|
|
{
|
|
mediaType: "text/html",
|
|
extensions: [".html"],
|
|
patterns: [
|
|
{
|
|
offset: 0,
|
|
bytes: [60, 104, 116, 109, 108],
|
|
},
|
|
],
|
|
},
|
|
],
|
|
},
|
|
preview: {
|
|
allowedMediaTypes: ["text/html"],
|
|
maxPreviewBytes: 10,
|
|
},
|
|
},
|
|
],
|
|
hardLimits: {
|
|
maxInspectionBytes: 64 * 1024,
|
|
maxRetainedFileBytes: 1_024,
|
|
maxPreviewBytes: 10,
|
|
maxObjectUrlBytes: 1_024,
|
|
maxTransferBytes: 1_024,
|
|
},
|
|
});
|
|
const vault = new BrowserFileVault({
|
|
policies,
|
|
createReference: () => "file:html",
|
|
createVerificationReceipt: () => "verification:html",
|
|
});
|
|
const captured = vault.captureFiles(
|
|
[
|
|
new File([new TextEncoder().encode("<html>")], "page.html", {
|
|
type: "text/html",
|
|
lastModified: 1,
|
|
}),
|
|
],
|
|
{
|
|
...pngSelectionPolicy,
|
|
accept: Object.freeze([]),
|
|
},
|
|
);
|
|
expect(captured.ok).toBe(true);
|
|
if (!captured.ok || !captured.value[0]) return;
|
|
const inspected = await vault.inspect({
|
|
ref: captured.value[0].ref,
|
|
policy: htmlPolicy,
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(inspected.ok).toBe(true);
|
|
if (!inspected.ok || !inspected.value.verificationReceipt) return;
|
|
const createObjectURL = vi.fn(() => "blob:must-not-exist");
|
|
const preview = new BrowserTransientPreview({
|
|
files: vault,
|
|
policies,
|
|
hardMaxPreviewBytes: 10,
|
|
hardForbiddenMediaTypes: new Set(["image/jpeg"]),
|
|
leases: new ObjectUrlLeaseRegistry({
|
|
createObjectURL,
|
|
revokeObjectURL() {},
|
|
}),
|
|
});
|
|
|
|
expect(
|
|
await preview.create({
|
|
ref: captured.value[0].ref,
|
|
verificationReceipt: inspected.value.verificationReceipt,
|
|
policy: htmlPolicy,
|
|
maxPreviewBytes: 10,
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "POLICY_REJECTED" },
|
|
});
|
|
expect(createObjectURL).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects count and zero-byte policy violations before retaining refs", () => {
|
|
const vault = new BrowserFileVault({
|
|
policies: pngPolicies(),
|
|
});
|
|
expect(vault.captureFiles([], pngSelectionPolicy)).toMatchObject({
|
|
ok: false,
|
|
error: { code: "INVALID_INPUT" },
|
|
});
|
|
expect(
|
|
vault.captureFiles(
|
|
[new File([], "empty.png", { type: "image/png" })],
|
|
pngSelectionPolicy,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "LIMIT_EXCEEDED" },
|
|
});
|
|
expect(vault.activeReferenceCount).toBe(0);
|
|
});
|
|
|
|
it("caps retained bytes while reference slots remain (02-08)", () => {
|
|
let referenceSequence = 0;
|
|
const vault = new BrowserFileVault({
|
|
policies: pngPolicies(),
|
|
createReference: () => `file:bytes-${referenceSequence++}`,
|
|
hardMaxActiveReferences: 8,
|
|
hardMaxRetainedBytes: 3,
|
|
});
|
|
const permissive = {
|
|
...pngSelectionPolicy,
|
|
accept: Object.freeze([]),
|
|
};
|
|
expect(
|
|
vault.captureFiles(
|
|
[new File([new Uint8Array(2)], "one.bin")],
|
|
permissive,
|
|
),
|
|
).toMatchObject({ ok: true });
|
|
expect(
|
|
vault.captureFiles(
|
|
[new File([new Uint8Array(2)], "two.bin")],
|
|
permissive,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "LIMIT_EXCEEDED" },
|
|
});
|
|
expect(vault.activeReferenceCount).toBe(1);
|
|
expect(vault.retainedByteLength).toBe(2);
|
|
});
|
|
|
|
it("caps retained files and aggregate object URL leases", () => {
|
|
let referenceSequence = 0;
|
|
const vault = new BrowserFileVault({
|
|
policies: pngPolicies(),
|
|
createReference: () => `file:bounded-${referenceSequence++}`,
|
|
hardMaxActiveReferences: 1,
|
|
hardMaxRetainedBytes: 3,
|
|
});
|
|
const permissive = {
|
|
...pngSelectionPolicy,
|
|
accept: Object.freeze([]),
|
|
};
|
|
const first = vault.captureFiles(
|
|
[new File([new Uint8Array(2)], "one.bin")],
|
|
permissive,
|
|
);
|
|
expect(first.ok).toBe(true);
|
|
expect(vault.retainedByteLength).toBe(2);
|
|
expect(
|
|
vault.captureFiles(
|
|
[new File([new Uint8Array(2)], "two.bin")],
|
|
permissive,
|
|
),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "LIMIT_EXCEEDED" },
|
|
});
|
|
if (first.ok && first.value[0]) vault.release(first.value[0].ref);
|
|
expect(vault.retainedByteLength).toBe(0);
|
|
|
|
let urlSequence = 0;
|
|
const leases = new ObjectUrlLeaseRegistry(
|
|
{
|
|
createObjectURL: () => `blob:bounded-${urlSequence++}`,
|
|
revokeObjectURL() {},
|
|
},
|
|
{
|
|
hardMaxActiveLeases: 1,
|
|
hardMaxSingleLeaseBytes: 6,
|
|
hardMaxAggregateLeaseBytes: 6,
|
|
},
|
|
);
|
|
const lease = leases.create(new Blob([new Uint8Array(6)]));
|
|
expect(leases.aggregateLeaseByteLength).toBe(6);
|
|
expect(() =>
|
|
leases.create(new Blob([new Uint8Array(1)])),
|
|
).toThrowError(DOMException);
|
|
lease.release();
|
|
expect(leases.aggregateLeaseByteLength).toBe(0);
|
|
});
|
|
|
|
it("converts native stream exceptions to closed chunk failures", async () => {
|
|
const file = new File([new Uint8Array([1])], "broken.bin", {
|
|
lastModified: 1,
|
|
});
|
|
Object.defineProperty(file, "stream", {
|
|
value: () =>
|
|
new ReadableStream<Uint8Array>({
|
|
pull() {
|
|
throw new DOMException("native detail", "NotReadableError");
|
|
},
|
|
}),
|
|
});
|
|
const vault = new BrowserFileVault({
|
|
policies: pngPolicies(),
|
|
createReference: () => "file:broken",
|
|
});
|
|
const captured = vault.captureFiles(
|
|
[file],
|
|
{ ...pngSelectionPolicy, accept: Object.freeze([]) },
|
|
);
|
|
expect(captured.ok).toBe(true);
|
|
if (!captured.ok || !captured.value[0]) return;
|
|
const opened = await vault.openSource({
|
|
ref: captured.value[0].ref,
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
|
|
const results = [];
|
|
for await (const result of opened.value.stream(
|
|
new AbortController().signal,
|
|
)) {
|
|
results.push(result);
|
|
}
|
|
expect(results).toEqual([
|
|
{
|
|
ok: false,
|
|
error: {
|
|
code: "NOT_READABLE",
|
|
operation: "FILE_READ",
|
|
retryable: true,
|
|
recovery: "REOPEN",
|
|
},
|
|
},
|
|
]);
|
|
});
|
|
|
|
it("keeps the shared token, limit and media-type checks (Q-6.2-12 characterization)", () => {
|
|
const policies = pngPolicies();
|
|
const file = new File([new Uint8Array([1])], "a.png", {
|
|
type: "image/png",
|
|
lastModified: 1,
|
|
});
|
|
expect(
|
|
new BrowserFileVault({
|
|
policies,
|
|
createReference: () => "file with space",
|
|
}).captureFiles([file], pngSelectionPolicy),
|
|
).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } });
|
|
expect(
|
|
new BrowserFileVault({
|
|
policies,
|
|
createReference: () => `file:${"x".repeat(123)}`,
|
|
}).captureFiles([file], pngSelectionPolicy),
|
|
).toMatchObject({ ok: true });
|
|
expect(
|
|
() => new BrowserFileVault({ policies, hardMaxRangeBytes: 0 }),
|
|
).toThrow(TypeError);
|
|
|
|
const revoked: string[] = [];
|
|
const registry = new ObjectUrlLeaseRegistry({
|
|
createObjectURL: () => "",
|
|
revokeObjectURL: (url) => revoked.push(url),
|
|
});
|
|
expect(() => registry.create(new Blob([new Uint8Array([1])]))).toThrow(
|
|
"Object URL allocation failed",
|
|
);
|
|
expect(revoked).toEqual([]);
|
|
expect(
|
|
() =>
|
|
new ObjectUrlLeaseRegistry(URL, {
|
|
hardMaxActiveLeases: 1.5,
|
|
hardMaxSingleLeaseBytes: 1,
|
|
hardMaxAggregateLeaseBytes: 1,
|
|
}),
|
|
).toThrow(TypeError);
|
|
|
|
const download = (mediaType: string, maxTransferBytes = 8) =>
|
|
new BrowserFilePolicyRegistry({
|
|
profiles: [
|
|
{
|
|
reference: browserFilePolicyReference("files", "download"),
|
|
download: {
|
|
strategy: "BOUNDED_OBJECT_URL",
|
|
mediaType,
|
|
safeExtension: ".bin",
|
|
maxTransferBytes,
|
|
maxBufferedBytes: 8,
|
|
integrity: "OPTIONAL",
|
|
},
|
|
},
|
|
],
|
|
hardLimits: {
|
|
maxInspectionBytes: 64,
|
|
maxRetainedFileBytes: 64,
|
|
maxPreviewBytes: 64,
|
|
maxObjectUrlBytes: 64,
|
|
maxTransferBytes: 64,
|
|
},
|
|
});
|
|
expect(() => download("application/octet-stream")).not.toThrow();
|
|
expect(() => download("application/*")).toThrow(TypeError);
|
|
expect(() => download("application/octet-stream", 0)).toThrow(TypeError);
|
|
});
|
|
|
|
it("ends a pending native read on caller abort and on vault dispose", async () => {
|
|
const pendingStream = () => {
|
|
const state = { cancelled: 0 };
|
|
const file = new File([new Uint8Array([1])], "slow.bin", {
|
|
lastModified: 1,
|
|
});
|
|
Object.defineProperty(file, "stream", {
|
|
value: () =>
|
|
new ReadableStream<Uint8Array>({
|
|
pull: () => new Promise<void>(() => {}),
|
|
cancel() {
|
|
state.cancelled += 1;
|
|
},
|
|
}),
|
|
});
|
|
return { file, state };
|
|
};
|
|
const open = async (vault: BrowserFileVault, file: File) => {
|
|
const captured = vault.captureFiles(
|
|
[file],
|
|
{ ...pngSelectionPolicy, accept: Object.freeze([]) },
|
|
);
|
|
if (!captured.ok || !captured.value[0]) throw new Error("capture");
|
|
const opened = await vault.openSource({
|
|
ref: captured.value[0].ref,
|
|
signal: new AbortController().signal,
|
|
});
|
|
if (!opened.ok) throw new Error("open");
|
|
return opened.value;
|
|
};
|
|
const collect = async (
|
|
stream: AsyncIterable<unknown>,
|
|
): Promise<unknown[]> => {
|
|
const results: unknown[] = [];
|
|
for await (const result of stream) results.push(result);
|
|
return results;
|
|
};
|
|
|
|
const aborted = pendingStream();
|
|
const callerVault = new BrowserFileVault({
|
|
policies: pngPolicies(),
|
|
createReference: () => "file:caller-abort",
|
|
});
|
|
const controller = new AbortController();
|
|
const callerRead = collect(
|
|
(await open(callerVault, aborted.file)).stream(controller.signal),
|
|
);
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
controller.abort();
|
|
expect(await callerRead).toMatchObject([
|
|
{ ok: false, error: { code: "ABORTED", operation: "FILE_READ" } },
|
|
]);
|
|
expect(aborted.state.cancelled).toBe(1);
|
|
|
|
const disposed = pendingStream();
|
|
const disposedVault = new BrowserFileVault({
|
|
policies: pngPolicies(),
|
|
createReference: () => "file:vault-dispose",
|
|
});
|
|
const disposedRead = collect(
|
|
(await open(disposedVault, disposed.file)).stream(
|
|
new AbortController().signal,
|
|
),
|
|
);
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
disposedVault.dispose();
|
|
expect(await disposedRead).toMatchObject([
|
|
{ ok: false, error: { code: "UNAVAILABLE", operation: "FILE_READ" } },
|
|
]);
|
|
expect(disposed.state.cancelled).toBe(1);
|
|
});
|
|
});
|