Files
tech-log-frontend/tests/unit/browser-file-download.test.ts
T
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

1308 lines
37 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import type {
BrowserManagedDownloadCapabilityReceipt,
BrowserManagedDownloadCapabilityResolver,
DownloadDeliveryPort,
DownloadSource,
DownloadStrategy,
FileByteSource,
} from "../../src/application/ports/browser-file-storage/file.ts";
import {
DEFAULT_OBJECT_URL_RELEASE_GRACE_MS,
createDownloadDeliveryAdapter,
type SaveFileHandle,
} from "../../src/adapters/browser-files/download-delivery-adapter.ts";
import { ObjectUrlLeaseRegistry } from "../../src/adapters/browser-files/object-url-lease.ts";
import {
BrowserFilePolicyRegistry,
browserFilePolicyReference,
} from "../../src/adapters/browser-files/browser-file-policy-registry.ts";
const HARD_LIMITS = Object.freeze({
hardMaxObjectUrlBytes: 64,
hardMaxTransferBytes: 128,
});
const capabilityReceipt =
"capability:download-1" as BrowserManagedDownloadCapabilityReceipt;
const policyByStrategy = Object.freeze({
BROWSER_MANAGED: browserFilePolicyReference(
"download",
"browser-managed-pdf",
),
PROMPT_AND_STREAM: browserFilePolicyReference(
"download",
"prompt-and-stream-pdf",
),
BOUNDED_OBJECT_URL: browserFilePolicyReference(
"download",
"bounded-object-url-pdf",
),
});
const policies = new BrowserFilePolicyRegistry({
profiles: (
Object.entries(policyByStrategy) as Array<
[DownloadStrategy, (typeof policyByStrategy)[DownloadStrategy]]
>
).map(([strategy, reference]) => ({
reference,
download: {
strategy,
mediaType: "application/pdf",
safeExtension: ".pdf",
maxTransferBytes: 32,
maxBufferedBytes: 16,
integrity: "OPTIONAL" as const,
},
})),
hardLimits: {
maxInspectionBytes: 64,
maxRetainedFileBytes: 128,
maxPreviewBytes: 64,
maxObjectUrlBytes: 64,
maxTransferBytes: 128,
},
});
function capabilityResolver(
href: (resourceId: string) => string = () => "/unused",
overrides: Readonly<
Partial<{
capabilityReceipt: BrowserManagedDownloadCapabilityReceipt;
resourceId: string;
mediaType: string;
safeExtension: string;
maxBytes: number;
expectedSha256: string;
expiresAtEpochMs: number;
}>
> = {},
): BrowserManagedDownloadCapabilityResolver {
return {
resolve(input) {
return {
ok: true,
value: {
capabilityReceipt:
overrides.capabilityReceipt ??
input.capabilityReceipt,
href: href(input.resourceId),
resourceId:
overrides.resourceId ?? input.resourceId,
mediaType:
overrides.mediaType ?? "application/pdf",
safeExtension: overrides.safeExtension ?? ".pdf",
maxBytes: overrides.maxBytes ?? 32,
...(overrides.expectedSha256
? { expectedSha256: overrides.expectedSha256 }
: {}),
expiresAtEpochMs:
overrides.expiresAtEpochMs ??
Number.MAX_SAFE_INTEGER,
},
};
},
};
}
function successfulChunk(bytes: Uint8Array) {
return Object.freeze({ ok: true as const, value: bytes });
}
function byteSource(
chunks: readonly Uint8Array[],
byteLength: number | null = chunks.reduce(
(total, chunk) => total + chunk.byteLength,
0,
),
afterChunk?: (index: number) => void,
): FileByteSource {
return Object.freeze({
byteLength,
async *stream(
signal: AbortSignal,
): AsyncIterable<ReturnType<typeof successfulChunk>> {
for (const [index, chunk] of chunks.entries()) {
if (signal.aborted) {
throw new DOMException("aborted", "AbortError");
}
yield successfulChunk(chunk);
afterChunk?.(index);
}
},
});
}
function deliveryInput(
source: DownloadSource,
strategy: DownloadStrategy,
signal = new AbortController().signal,
) {
return {
policy: policyByStrategy[strategy],
source,
suggestedFileName: "../../invoice.exe.pdf",
maxTransferBytes: 32,
maxBufferedBytes: 16,
signal,
onProgress: vi.fn(),
} satisfies Parameters<DownloadDeliveryPort["deliver"]>[0];
}
function writableHandle(events: string[]): SaveFileHandle {
return Object.freeze({
async createWritable() {
return new WritableStream<Uint8Array>({
write(chunk) {
events.push(`write:${chunk.byteLength}`);
},
close() {
events.push("close");
},
abort() {
events.push("abort");
},
});
},
});
}
describe("browser download delivery", () => {
it("captures composition dependencies instead of re-reading mutable option objects", async () => {
const originalHandoff = vi.fn();
const replacedHandoff = vi.fn();
const originalResolve = vi.fn(
capabilityResolver(
() => "/downloads/composition-bound",
).resolve,
);
const replacedResolve = vi.fn(
capabilityResolver(
() => "https://evil.example/replaced",
).resolve,
);
const host = { handoff: originalHandoff };
const browserManagedCapabilities = {
resolve: originalResolve,
};
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host,
browserManagedCapabilities,
baseOrigin: "https://app.example",
createTransferId: () => "transfer:composition",
userActivation: { isActive: true },
});
host.handoff = replacedHandoff;
browserManagedCapabilities.resolve = replacedResolve;
expect(
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
),
).toMatchObject({
ok: true,
value: { kind: "BROWSER_HANDOFF" },
});
expect(originalResolve).toHaveBeenCalledOnce();
expect(replacedResolve).not.toHaveBeenCalled();
expect(originalHandoff).toHaveBeenCalledOnce();
expect(replacedHandoff).not.toHaveBeenCalled();
});
it("sanitizes browser-managed handoff and reports only handoff truth", async () => {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(
(resourceId) => `/downloads/${resourceId}`,
),
baseOrigin: "https://app.example",
createTransferId: () => "transfer:1",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
),
).toEqual({
ok: true,
value: { kind: "BROWSER_HANDOFF", transferId: "transfer:1" },
});
// STO-02. Parse once, then execute exactly what was validated.
expect(handoff).toHaveBeenCalledWith(
"https://app.example/downloads/artifact-1",
"invoice_exe.pdf",
);
});
it("executes the canonical target instead of a document-base-relative href", async () => {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
// A relative href the host would otherwise resolve against a hostile
// document <base href="https://evil.example/">.
browserManagedCapabilities: capabilityResolver(() => "downloads/a"),
baseOrigin: "https://app.example",
createTransferId: () => "transfer:1",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
),
).toMatchObject({ ok: true });
expect(handoff).toHaveBeenCalledWith(
"https://app.example/downloads/a",
"invoice_exe.pdf",
);
for (const [href] of handoff.mock.calls) {
expect(String(href).startsWith("https://app.example/")).toBe(true);
expect(String(href)).not.toContain("evil.example");
}
});
it("rejects cross-origin or query-bearing browser-managed targets", async () => {
// 02-08. Each href breaks one rule, so neither check hides the other.
for (const href of [
"https://evil.example/downloads/a",
"/downloads/a?token=secret",
]) {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(() => href),
baseOrigin: "https://app.example",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
),
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect(handoff).not.toHaveBeenCalled();
}
});
it("requires an exact, unexpired, server-bound synchronous capability receipt", async () => {
const source = {
kind: "BROWSER_MANAGED_RESOURCE" as const,
resourceId: "artifact-1",
capabilityReceipt,
};
const cases = [
{
resolver: capabilityResolver(() => "/unused", {
capabilityReceipt:
"capability:other" as BrowserManagedDownloadCapabilityReceipt,
}),
expectedCode: "POLICY_REJECTED",
},
{
resolver: capabilityResolver(undefined, {
resourceId: "artifact-2",
}),
expectedCode: "POLICY_REJECTED",
},
{
resolver: capabilityResolver(undefined, {
mediaType: "text/plain",
}),
expectedCode: "POLICY_REJECTED",
},
{
resolver: capabilityResolver(undefined, {
expiresAtEpochMs: 99,
}),
expectedCode: "EXPIRED_RESOURCE",
},
] as const;
for (const testCase of cases) {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: testCase.resolver,
now: () => 100,
baseOrigin: "https://app.example",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(source, "BROWSER_MANAGED"),
),
).toMatchObject({
ok: false,
error: { code: testCase.expectedCode },
});
expect(handoff).not.toHaveBeenCalled();
}
const missingReceipt = {
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
} as unknown as DownloadSource;
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(missingReceipt, "BROWSER_MANAGED"),
),
).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
});
it("streams with backpressure and succeeds only after close", async () => {
const events: string[] = [];
const controller = new AbortController();
const handle = writableHandle(events);
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => handle,
createTransferId: () => "transfer:stream",
progressMinIntervalMs: 0,
userActivation: { isActive: true },
});
const input = deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([
new Uint8Array([1, 2]),
new Uint8Array([3]),
]),
},
"PROMPT_AND_STREAM",
controller.signal,
);
expect(await adapter.deliver(input)).toEqual({
ok: true,
value: {
kind: "SAVED",
transferId: "transfer:stream",
bytesWritten: 3,
integrity: "NOT_PROVIDED",
},
});
expect(events).toEqual(["write:2", "write:1", "close"]);
expect(input.onProgress.mock.calls.map(([progress]) => progress.phase)).toEqual(
["PREPARING", "TRANSFERRING", "TRANSFERRING", "VERIFYING", "FINALIZING"],
);
});
it("calls an injected window save picker without rebinding its receiver", async () => {
const events: string[] = [];
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
// A Window operation throws "Illegal invocation" unless `this` is the
// Window. Web IDL maps an undefined `this` to the global object.
showSaveFilePicker: function (this: unknown) {
if (this !== undefined && this !== globalThis) {
throw new TypeError("Illegal invocation");
}
return Promise.resolve(writableHandle(events));
},
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1, 2])]),
},
"PROMPT_AND_STREAM",
),
),
).toMatchObject({ ok: true, value: { kind: "SAVED" } });
expect(events).toEqual(["write:2", "close"]);
});
it("snapshots the generated source before awaiting the save picker", async () => {
const events: string[] = [];
let resolvePicker:
| ((handle: SaveFileHandle) => void)
| undefined;
const originalStream = vi.fn(
async function* () {
yield successfulChunk(new Uint8Array([1, 2]));
},
);
const replacedStream = vi.fn(
async function* () {
yield successfulChunk(new Uint8Array([9]));
},
);
const bytes = {
byteLength: 2,
stream: originalStream,
};
const source = {
kind: "GENERATED" as const,
bytes,
};
const request = deliveryInput(
source,
"PROMPT_AND_STREAM",
);
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: () =>
new Promise((resolve) => {
resolvePicker = resolve;
}),
createTransferId: () => "transfer:snapshot",
userActivation: { isActive: true },
});
const pending = adapter.deliver(request);
bytes.byteLength = 1;
bytes.stream = replacedStream;
(
request as { source: DownloadSource }
).source = {
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "replaced",
capabilityReceipt,
};
resolvePicker?.(writableHandle(events));
expect(await pending).toMatchObject({
ok: true,
value: { kind: "SAVED", bytesWritten: 2 },
});
expect(originalStream).toHaveBeenCalledOnce();
expect(replacedStream).not.toHaveBeenCalled();
expect(events).toEqual(["write:2", "close"]);
});
it("does not turn a completed close into a late abort failure", async () => {
const controller = new AbortController();
const handle: SaveFileHandle = {
async createWritable() {
return new WritableStream<Uint8Array>({
close() {
controller.abort();
},
});
},
};
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => handle,
createTransferId: () => "transfer:committed",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1])]),
},
"PROMPT_AND_STREAM",
controller.signal,
),
),
).toMatchObject({
ok: true,
value: { kind: "SAVED", transferId: "transfer:committed" },
});
});
it("aborts the writable before close on integrity failure", async () => {
const events: string[] = [];
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => writableHandle(events),
createIntegrityVerifier: () => ({
update: () => {
events.push("hash");
},
verify: () => false,
}),
userActivation: { isActive: true },
});
const input = {
...deliveryInput(
{
kind: "GENERATED" as const,
bytes: byteSource([new Uint8Array([1, 2])]),
expectedSha256: "a".repeat(64),
},
"PROMPT_AND_STREAM",
),
};
expect(await adapter.deliver(input)).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
expect(events).toEqual(["hash", "write:2", "abort"]);
});
it("records a save-picker dismissal apart from a browser handoff (02-06)", async () => {
const records: unknown[] = [];
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(
(resourceId) => `/downloads/${resourceId}`,
),
showSaveFilePicker: async () => {
throw new DOMException("dismissed", "AbortError");
},
baseOrigin: "https://app.example",
userActivation: { isActive: true },
observer: { record: (observation) => records.push(observation) },
});
await adapter.deliver(
deliveryInput(
{
kind: "BROWSER_MANAGED_RESOURCE",
resourceId: "artifact-1",
capabilityReceipt,
},
"BROWSER_MANAGED",
),
);
await adapter.deliver(
deliveryInput(
{ kind: "GENERATED", bytes: byteSource([new Uint8Array([1])]) },
"PROMPT_AND_STREAM",
),
);
expect(records).toEqual([
{ operation: "DOWNLOAD", outcome: "SUCCEEDED" },
{ operation: "DOWNLOAD", outcome: "DISMISSED" },
]);
});
it("distinguishes save-picker dismissal from active cancellation", async () => {
const dismissed = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => {
throw new DOMException("dismissed", "AbortError");
},
userActivation: { isActive: true },
});
expect(
await dismissed.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1])]),
},
"PROMPT_AND_STREAM",
),
),
).toEqual({
ok: true,
value: { kind: "DISMISSED" },
});
const controller = new AbortController();
let rejectPicker:
| ((reason: DOMException) => void)
| undefined;
const aborted = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: () =>
new Promise((_, reject: (reason: DOMException) => void) => {
rejectPicker = reject;
}),
userActivation: { isActive: true },
});
const pending = aborted.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1])]),
},
"PROMPT_AND_STREAM",
controller.signal,
),
);
controller.abort();
rejectPicker?.(new DOMException("closed", "AbortError"));
expect(await pending).toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
});
it("bounds Blob buffering and revokes the lease after handoff", async () => {
const revoked: string[] = [];
const leases = new ObjectUrlLeaseRegistry({
createObjectURL: () => "blob:download-1",
revokeObjectURL: (url) => revoked.push(url),
});
let scheduled: (() => void) | undefined;
let scheduledDelay: number | undefined;
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(),
objectUrls: leases,
scheduler: {
setTimeout(callback, delayMs) {
scheduled = callback;
scheduledDelay = delayMs;
return 1;
},
},
createTransferId: () => "transfer:blob",
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([
new Uint8Array([1, 2]),
new Uint8Array([3]),
]),
},
"BOUNDED_OBJECT_URL",
),
),
).toEqual({
ok: true,
value: {
kind: "BROWSER_HANDOFF",
transferId: "transfer:blob",
},
});
expect(handoff).toHaveBeenCalledWith(
"blob:download-1",
"invoice_exe.pdf",
);
expect(leases.activeLeaseCount).toBe(1);
expect(scheduledDelay).toBe(
DEFAULT_OBJECT_URL_RELEASE_GRACE_MS,
);
scheduled?.();
expect(leases.activeLeaseCount).toBe(0);
expect(revoked).toEqual(["blob:download-1"]);
});
it("captures object URL methods at registry construction", () => {
const originalCreate = vi.fn(() => "blob:captured");
const originalRevoke = vi.fn();
const replacedCreate = vi.fn(() => "blob:replaced");
const replacedRevoke = vi.fn();
const urlApi = {
createObjectURL: originalCreate,
revokeObjectURL: originalRevoke,
};
const leases = new ObjectUrlLeaseRegistry(urlApi);
urlApi.createObjectURL = replacedCreate;
urlApi.revokeObjectURL = replacedRevoke;
const lease = leases.create(new Blob(["safe"]));
lease.release();
expect(lease.url).toBe("blob:captured");
expect(originalCreate).toHaveBeenCalledOnce();
expect(originalRevoke).toHaveBeenCalledWith(
"blob:captured",
);
expect(replacedCreate).not.toHaveBeenCalled();
expect(replacedRevoke).not.toHaveBeenCalled();
});
it("rejects a stream that crosses the bounded Blob cap", async () => {
const handoff = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
});
const input = {
...deliveryInput(
{
kind: "GENERATED" as const,
bytes: byteSource(
[new Uint8Array(10), new Uint8Array(10)],
null,
),
},
"BOUNDED_OBJECT_URL",
),
maxBufferedBytes: 16,
};
expect(await adapter.deliver(input)).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(handoff).not.toHaveBeenCalled();
});
it("resolves ABORTED and closes a late lease when a bounded source open is aborted", async () => {
const controller = new AbortController();
let releaseOpen: ((value: unknown) => void) | undefined;
const close = vi.fn();
const handoff = vi.fn();
const record = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
observer: { record },
// Ignores the signal and resolves only when the test says so.
openAuthorizedSource: () =>
new Promise((resolve) => {
releaseOpen = resolve;
}) as never,
});
const capability = Object.freeze({
capabilityReceipt: "capability-bounded-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/pdf",
byteLength: 3,
maxBytes: 3,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
});
const delivering = adapter.deliver(
deliveryInput(
{
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: capability as never,
},
"BOUNDED_OBJECT_URL",
controller.signal,
),
);
await new Promise((resolve) => setTimeout(resolve, 0));
controller.abort();
await expect(delivering).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
expect(record).toHaveBeenCalled();
releaseOpen?.({
ok: true,
value: {
byteLength: 3,
integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION",
capability,
close,
async *stream() {},
},
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(close).toHaveBeenCalledOnce();
expect(handoff).not.toHaveBeenCalled();
});
it("rejects caller limits above runtime hard caps before side effects", async () => {
const handoff = vi.fn();
const showSaveFilePicker = vi.fn(async () => writableHandle([]));
const stream = vi.fn(
async function* (): AsyncIterable<
ReturnType<typeof successfulChunk>
> {
yield successfulChunk(new Uint8Array([1]));
},
);
const adapter = createDownloadDeliveryAdapter({
hardMaxObjectUrlBytes: 8,
hardMaxTransferBytes: 12,
policies,
host: { handoff },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker,
userActivation: { isActive: true },
});
const source = {
kind: "GENERATED" as const,
bytes: { byteLength: null, stream },
};
expect(
await adapter.deliver({
...deliveryInput(source, "BOUNDED_OBJECT_URL"),
maxBufferedBytes: 9,
maxTransferBytes: 12,
}),
).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(
await adapter.deliver({
...deliveryInput(source, "PROMPT_AND_STREAM"),
maxBufferedBytes: 8,
maxTransferBytes: 13,
}),
).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(
await adapter.deliver({
...deliveryInput(
{
kind: "GENERATED",
bytes: { byteLength: 13, stream },
},
"PROMPT_AND_STREAM",
),
maxBufferedBytes: 8,
maxTransferBytes: 12,
}),
).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(stream).not.toHaveBeenCalled();
expect(showSaveFilePicker).not.toHaveBeenCalled();
expect(handoff).not.toHaveBeenCalled();
});
it("aborts streaming when actual bytes cross the transfer hard cap", async () => {
const events: string[] = [];
const adapter = createDownloadDeliveryAdapter({
hardMaxObjectUrlBytes: 8,
hardMaxTransferBytes: 8,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => writableHandle(events),
userActivation: { isActive: true },
});
expect(
await adapter.deliver({
...deliveryInput(
{
kind: "GENERATED",
bytes: byteSource(
[new Uint8Array(5), new Uint8Array(4)],
null,
),
},
"PROMPT_AND_STREAM",
),
maxBufferedBytes: 8,
maxTransferBytes: 8,
}),
).toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(events).toEqual(["write:5", "abort"]);
});
it("treats a declared-length mismatch as integrity failure", async () => {
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
});
expect(
await adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1])], 2),
},
"BOUNDED_OBJECT_URL",
),
),
).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
});
it("maps typed and defensive raw stream failures to closed download errors", async () => {
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
});
const common = {
...deliveryInput(
{
kind: "GENERATED" as const,
bytes: {
byteLength: null,
async *stream() {
yield {
ok: false as const,
error: {
code: "NOT_READABLE" as const,
operation: "FILE_READ" as const,
retryable: true,
recovery: "REOPEN" as const,
},
};
},
},
},
"BOUNDED_OBJECT_URL",
),
};
expect(await adapter.deliver(common)).toMatchObject({
ok: false,
error: {
code: "NOT_READABLE",
operation: "DOWNLOAD",
},
});
expect(
await adapter.deliver({
...common,
source: {
kind: "GENERATED",
bytes: {
byteLength: null,
async *stream(signal: AbortSignal) {
if (signal.aborted) {
yield {
ok: false as const,
error: {
code: "ABORTED" as const,
operation: "FILE_READ" as const,
retryable: false,
recovery: "NONE" as const,
},
};
return;
}
throw new DOMException(
"native detail",
"NotReadableError",
);
},
},
},
}),
).toMatchObject({
ok: false,
error: {
code: "NOT_READABLE",
operation: "DOWNLOAD",
},
});
});
it("closes a lease that resolves in the same turn as the abort (Q-6.2-7)", async () => {
const controller = new AbortController();
let releaseOpen: ((value: unknown) => void) | undefined;
const close = vi.fn();
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
userActivation: { isActive: true },
openAuthorizedSource: () =>
new Promise((resolve) => {
releaseOpen = resolve;
}) as never,
});
const capability = Object.freeze({
capabilityReceipt: "capability-gap-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/pdf",
byteLength: 3,
maxBytes: 3,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
});
const delivering = adapter.deliver(
deliveryInput(
{
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: capability as never,
},
"BOUNDED_OBJECT_URL",
controller.signal,
),
);
await new Promise((resolve) => setTimeout(resolve, 0));
// The lease lands after the abort but before the delivery's own cleanup.
controller.abort();
releaseOpen?.({
ok: true,
value: {
byteLength: 3,
integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION",
capability,
close,
async *stream() {},
},
});
await expect(delivering).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(close).toHaveBeenCalledOnce();
});
it("aborts a writable that arrives after the delivery was aborted (Q-6.2-7)", async () => {
const controller = new AbortController();
const events: string[] = [];
let createWritableCalled: (() => void) | undefined;
const writableRequested = new Promise<void>((resolve) => {
createWritableCalled = resolve;
});
let releaseWritable:
| ((writable: WritableStream<Uint8Array>) => void)
| undefined;
const adapter = createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(),
showSaveFilePicker: async () => ({
createWritable() {
createWritableCalled?.();
return new Promise<WritableStream<Uint8Array>>((resolve) => {
releaseWritable = resolve;
});
},
}),
userActivation: { isActive: true },
});
const delivering = adapter.deliver(
deliveryInput(
{
kind: "GENERATED",
bytes: byteSource([new Uint8Array([1])]),
},
"PROMPT_AND_STREAM",
controller.signal,
),
);
await writableRequested;
controller.abort();
await expect(delivering).resolves.toMatchObject({
ok: false,
error: { code: "ABORTED" },
});
// Chrome keeps a `.crswap` file for an open writable until it is aborted.
releaseWritable?.(
new WritableStream<Uint8Array>({
abort() {
events.push("abort");
},
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(events).toEqual(["abort"]);
});
it("keeps input validation failure codes (Q-6.2-11 characterization)", async () => {
const adapter = (
overrides: Partial<Parameters<typeof createDownloadDeliveryAdapter>[0]> = {},
) =>
createDownloadDeliveryAdapter({
...HARD_LIMITS,
policies,
host: { handoff: vi.fn() },
browserManagedCapabilities: capabilityResolver(
(resourceId) => `/downloads/${resourceId}`,
),
baseOrigin: "https://app.example",
showSaveFilePicker: async () => writableHandle([]),
userActivation: { isActive: true },
...overrides,
});
const code = async (
source: DownloadSource,
strategy: DownloadStrategy,
overrides: Partial<Parameters<typeof createDownloadDeliveryAdapter>[0]> = {},
): Promise<string> => {
const result = await adapter(overrides).deliver(
deliveryInput(source, strategy),
);
return result.ok ? result.value.kind : result.error.code;
};
const generated = (
bytes: FileByteSource = byteSource([new Uint8Array([1])]),
expectedSha256?: string,
): DownloadSource => ({
kind: "GENERATED",
bytes,
...(expectedSha256 === undefined ? {} : { expectedSha256 }),
});
const managed = (resourceId: string): DownloadSource => ({
kind: "BROWSER_MANAGED_RESOURCE",
resourceId,
capabilityReceipt,
});
expect(await code(generated(), "BOUNDED_OBJECT_URL")).toBe(
"BROWSER_HANDOFF",
);
expect(
await code({ kind: "UNKNOWN" } as never, "BOUNDED_OBJECT_URL"),
).toBe("INVALID_INPUT");
expect(
await code(
generated({ byteLength: 1, stream: "no" } as never),
"BOUNDED_OBJECT_URL",
),
).toBe("INVALID_INPUT");
expect(
await code(
generated(byteSource([new Uint8Array([1])], -1)),
"BOUNDED_OBJECT_URL",
),
).toBe("INTEGRITY_FAILED");
expect(
await code(generated(undefined, "not-a-digest"), "BOUNDED_OBJECT_URL"),
).toBe("INVALID_INPUT");
expect(await code(generated(), "BROWSER_MANAGED")).toBe(
"POLICY_REJECTED",
);
expect(await code(managed("artifact-1"), "BOUNDED_OBJECT_URL")).toBe(
"POLICY_REJECTED",
);
expect(await code(managed(""), "BROWSER_MANAGED")).toBe("INVALID_INPUT");
expect(await code(managed("has space"), "BROWSER_MANAGED")).toBe(
"INVALID_INPUT",
);
expect(
await code(generated(), "BOUNDED_OBJECT_URL", {
userActivation: { isActive: false },
}),
).toBe("PERMISSION_DENIED");
expect(
await code(generated(), "BOUNDED_OBJECT_URL", {
filenameMaxUtf8Bytes: 2,
}),
).toBe("INVALID_INPUT");
expect(
await code(generated(), "BOUNDED_OBJECT_URL", {
createTransferId: () => "transfer with space",
}),
).toBe("UNAVAILABLE");
expect(
await code(managed("artifact-1"), "BROWSER_MANAGED", {
browserManagedCapabilities: capabilityResolver(
() => "https://user:secret@app.example/downloads/artifact-1",
),
}),
).toBe("POLICY_REJECTED");
expect(
await code(managed("artifact-1"), "BROWSER_MANAGED", {
browserManagedCapabilities: capabilityResolver(undefined, {
expiresAtEpochMs: 1,
}),
}),
).toBe("EXPIRED_RESOURCE");
expect(
await code(managed("artifact-1"), "BROWSER_MANAGED", {
browserManagedCapabilities: capabilityResolver(undefined, {
mediaType: "text/html",
}),
}),
).toBe("POLICY_REJECTED");
});
});