Files
tech-log-frontend/tests/browser-capabilities/browser-files.spec.ts
T
DongHyeonka c524a21463 test(browser): 다운로드 시험이 브라우저가 파일을 받은 뒤 런타임을 정리한다
이 시험은 BOUNDED_OBJECT_URL 다운로드로 Blob을 앵커에 넘기고, 브라우저의
download 이벤트를 기다린다. 그런데 deliver()가 handoff를 마치자마자
.finally(() => runtime.dispose())가 돈다. dispose()는 살아 있는 object URL을
즉시 해제한다(평소에는 30초 유예를 두지만 dispose는 정리라서 예외다).
WebKit은 앵커 클릭 뒤 다운로드를 비동기로 시작하므로, URL이 먼저 해제되면
다운로드가 시작되지 않는다. 그러면 download 이벤트 없이 30초 시험 제한으로
떨어진다. 2026-11-12 capability 실행 4번 중 1번 WebKit에서 이렇게 떨어졌다.

런타임을 전역에 두고, 다운로드 내용을 다 읽은 뒤 페이지에서 dispose한다.
제품의 해제 규칙(30초 유예, dispose 즉시 해제)은 바꾸지 않는다. 실제
화면에서 런타임은 다운로드 직후 버려지지 않는다.

검증: WebKit에서 --repeat-each=20으로 20회 모두 통과. 고치기 전 같은
조건 10회에서는 이 시험이 실패하지 않아 재현율은 낮다. 근거는 위 실패
로그와 dispose의 즉시 해제 코드(download-delivery-adapter.ts)다.
2026-11-12 18:38:30 +09:00

465 lines
14 KiB
TypeScript

import { expect, test } from "../support/browser/strict-browser-test.ts";
test("selects, inspects, streams, and previews a real browser File", async ({
page,
}) => {
await page.goto("/");
await page.evaluate(async () => {
const modulePath =
"/src/adapters/browser-files/index.ts";
const {
createBrowserFileRuntime,
browserFilePolicyReference,
} = await import(/* @vite-ignore */ modulePath);
const input = document.createElement("input");
input.id = "capability-file-input";
input.type = "file";
const label = document.createElement("label");
label.htmlFor = input.id;
label.textContent = "PNG file";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Choose test file";
document.body.append(label, input, button);
const filePolicy = browserFilePolicyReference(
"avatar",
"select-inspect-preview-png",
);
const runtime = createBrowserFileRuntime({
input,
policies: [
{
reference: filePolicy,
selection: {
policyId: "avatar-v1",
purpose: "avatar",
classification: "PERSONAL",
multiple: false,
maxCount: 1,
maxFileBytes: 1024,
maxTotalBytes: 1024,
allowEmpty: false,
accept: [
{
mediaType: "image/png",
extensions: [".png"],
},
],
},
inspection: {
policyId: "png-signature-v1",
maxInspectionBytes: 16,
acceptedSignatures: [
{
mediaType: "image/png",
extensions: [".png"],
patterns: [
{
offset: 0,
bytes: [137, 80, 78, 71, 13, 10, 26, 10],
},
],
},
],
},
preview: {
allowedMediaTypes: ["image/png"],
maxPreviewBytes: 1024,
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: Object.freeze({ handoff() {} }),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
const state = globalThis as typeof globalThis & {
__browserFileResult?: Promise<unknown>;
};
button.addEventListener("click", () => {
state.__browserFileResult = (async () => {
const selected = await runtime.baselinePicker.select({
policy: filePolicy,
});
if (
!selected.ok ||
selected.value.kind !== "SELECTED" ||
selected.value.files.length !== 1
) {
runtime.dispose();
return selected;
}
const candidate = selected.value.files[0]!;
const signal = new AbortController().signal;
const inspected = await runtime.content.inspect({
ref: candidate.ref,
policy: filePolicy,
signal,
});
const range = await runtime.content.readRange({
ref: candidate.ref,
offset: 1,
length: 4,
signal,
});
const opened = await runtime.content.openSource({
ref: candidate.ref,
signal,
});
const streamed: number[] = [];
if (opened.ok) {
for await (const chunk of opened.value.stream(signal)) {
if (chunk.ok) streamed.push(...chunk.value);
}
}
const verificationReceipt = inspected.ok
? inspected.value.verificationReceipt
: null;
if (!verificationReceipt) {
runtime.dispose();
return inspected;
}
const preview = await runtime.previews.create({
ref: candidate.ref,
verificationReceipt,
policy: filePolicy,
maxPreviewBytes: 1024,
signal,
});
let previewBytes: number[] = [];
let previewProtocol: string | null = null;
if (preview.ok) {
previewProtocol = new URL(preview.value.url).protocol;
previewBytes = Array.from(
new Uint8Array(await (await fetch(preview.value.url)).arrayBuffer()),
);
preview.value.release();
}
runtime.baselinePicker.release(candidate.ref);
runtime.dispose();
return {
selected,
inspected,
range: range.ok ? Array.from(range.value) : range,
streamed,
preview: preview.ok ? { ok: true } : preview,
previewBytes,
previewProtocol,
};
})();
});
});
const chooserPromise = page.waitForEvent("filechooser");
await page.getByRole("button", { name: "Choose test file" }).click();
const chooser = await chooserPromise;
const bytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1, 2, 3, 4]);
await chooser.setFiles({
name: "sample.png",
mimeType: "image/png",
buffer: bytes,
});
const result = await page.evaluate(async () => {
const state = globalThis as typeof globalThis & {
__browserFileResult?: Promise<unknown>;
};
return await state.__browserFileResult;
});
expect(result).toMatchObject({
selected: {
ok: true,
value: {
kind: "SELECTED",
files: [{ sizeBytes: bytes.byteLength, source: "NATIVE_INPUT" }],
},
},
inspected: {
ok: true,
value: {
byteLength: bytes.byteLength,
detectedMediaType: "image/png",
signature: "MATCHED",
},
},
range: [80, 78, 71, 13],
streamed: Array.from(bytes),
preview: { ok: true },
previewBytes: Array.from(bytes),
previewProtocol: "blob:",
});
});
test("hands a bounded generated Blob to the real browser download path", async ({
page,
}) => {
await page.goto("/");
await page.evaluate(async () => {
const modulePath = "/src/adapters/browser-files/index.ts";
const {
createBrowserFileRuntime,
createAnchorDownloadHost,
browserFilePolicyReference,
} = await import(/* @vite-ignore */ modulePath);
const input = document.createElement("input");
input.type = "file";
input.id = "unused-download-input";
const label = document.createElement("label");
label.htmlFor = input.id;
label.textContent = "Unused file control";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Download generated file";
document.body.append(label, input, button);
const downloadPolicy = browserFilePolicyReference(
"generated-export",
"bounded-object-url-bin",
);
const runtime = createBrowserFileRuntime({
input,
policies: [
{
reference: downloadPolicy,
download: {
strategy: "BOUNDED_OBJECT_URL",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 1024,
maxBufferedBytes: 1024,
integrity: "OPTIONAL",
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: createAnchorDownloadHost(document),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
const state = globalThis as typeof globalThis & {
__browserDownloadResult?: Promise<unknown>;
__browserDownloadRuntime?: { dispose(): void };
};
state.__browserDownloadRuntime = runtime;
button.addEventListener("click", () => {
state.__browserDownloadResult = runtime.downloads
.deliver({
policy: downloadPolicy,
source: {
kind: "GENERATED",
bytes: {
byteLength: 5,
async *stream() {
yield {
ok: true as const,
value: new Uint8Array([1, 2]),
};
yield {
ok: true as const,
value: new Uint8Array([3, 4, 5]),
};
},
},
},
suggestedFileName: "report",
maxTransferBytes: 1024,
maxBufferedBytes: 1024,
signal: new AbortController().signal,
onProgress() {},
});
});
});
const downloadPromise = page.waitForEvent("download");
await page
.getByRole("button", { name: "Download generated file" })
.click();
const download = await downloadPromise;
const stream = await download.createReadStream();
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk));
}
// dispose() revokes every live object URL at once. It used to run as soon
// as deliver() handed the URL to the anchor; WebKit starts the download
// after that, so it sometimes met a revoked URL and never started (no
// "download" event within the test timeout). The runtime is disposed once
// the browser has the file.
const result = await page.evaluate(async () => {
const state = globalThis as typeof globalThis & {
__browserDownloadResult?: Promise<unknown>;
__browserDownloadRuntime?: { dispose(): void };
};
const delivered = await state.__browserDownloadResult;
state.__browserDownloadRuntime?.dispose();
return delivered;
});
expect(download.suggestedFilename()).toBe("report.bin");
expect(Buffer.concat(chunks)).toEqual(Buffer.from([1, 2, 3, 4, 5]));
expect(result).toMatchObject({
ok: true,
value: {
kind: "BROWSER_HANDOFF",
},
});
});
/**
* R3-6 / STO-08. The enhanced picker keeps `window.showOpenFilePicker` and
* calls it later. Called with the options object as receiver it would reject
* with "Illegal invocation" (TypeError → UNAVAILABLE). This spec passes the
* real, unbound function and an injected `isActive: true` reading so the app's
* own activation precheck lets the call through; with no real user gesture the
* browser must then reject with its activation error (SecurityError →
* PERMISSION_DENIED). Browsers without the API return UNSUPPORTED, because
* the capability evidence gate forbids skipped cases.
*/
test("calls the real showOpenFilePicker without a receiver and gets the activation error", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const system = (globalThis as typeof globalThis & {
showOpenFilePicker?: (options?: unknown) => Promise<unknown>;
}).showOpenFilePicker;
if (typeof system !== "function") return { kind: "UNSUPPORTED" as const };
// Playwright evaluates with a user gesture, so wait until that transient
// activation expires (5s in Chromium) to get a real "no gesture" call.
const deadline = performance.now() + 10_000;
while (navigator.userActivation.isActive && performance.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
const activationExpired = !navigator.userActivation.isActive;
const errorName = async (call: () => Promise<unknown>) => {
try {
await call();
return "RESOLVED";
} catch (error) {
return error instanceof Error ? error.name : String(error);
}
};
// Controls: the native activation error, and what a wrong receiver does.
const directWithoutGesture = await errorName(() => system());
const wrongReceiver = await errorName(() =>
Reflect.apply(system, {}, []) as Promise<unknown>,
);
const modulePath = "/src/adapters/browser-files/index.ts";
const { createBrowserFileRuntime, browserFilePolicyReference } =
(await import(
/* @vite-ignore */ modulePath
)) as typeof import("../../src/adapters/browser-files/index.ts");
const input = document.createElement("input");
input.type = "file";
const filePolicy = browserFilePolicyReference("avatar", "enhanced-unbound");
const runtime = createBrowserFileRuntime({
input,
showOpenFilePicker: system as never,
userActivation: { isActive: true },
policies: [
{
reference: filePolicy,
selection: {
policyId: "avatar-v1",
purpose: "avatar",
classification: "PERSONAL",
multiple: false,
maxCount: 1,
maxFileBytes: 1024,
maxTotalBytes: 1024,
allowEmpty: false,
accept: [{ mediaType: "image/png", extensions: [".png"] }],
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: Object.freeze({ handoff() {} }),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
if (!runtime.enhancedPicker) {
throw new Error("Enhanced picker was not composed.");
}
try {
const selected = await runtime.enhancedPicker.select({
policy: filePolicy,
});
return {
kind: "SUPPORTED" as const,
activationExpired,
directWithoutGesture,
wrongReceiver,
selected,
};
} finally {
runtime.dispose();
}
});
if (result.kind === "UNSUPPORTED") {
expect(result).toEqual({ kind: "UNSUPPORTED" });
return;
}
expect(result.activationExpired).toBe(true);
expect(result.directWithoutGesture).toBe("SecurityError");
expect(result.wrongReceiver).toBe("TypeError");
expect(result.selected).toMatchObject({
ok: false,
error: { code: "PERMISSION_DENIED", operation: "FILE_SELECT" },
});
});