From 7856725c728891bfc248e8089fa5081e4e66f54b Mon Sep 17 00:00:00 2001 From: Schluffe Date: Fri, 16 Oct 2026 13:49:17 +0200 Subject: [PATCH] Add hosted service-worker streaming downloads --- CHANGELOG.md | 10 ++++ README.md | 42 +++++++++++---- package.json | 1 + public/download/worker.js | 70 +++++++++++++++++++++++++ scripts/browser-check.ts | 40 ++++++++++++++- src/components/TransferPanel.vue | 24 ++++++--- src/lib/download.ts | 88 ++++++++++++++++++++++++++++++++ tests/download.test.ts | 86 +++++++++++++++++++++++++++++++ 8 files changed, 344 insertions(+), 17 deletions(-) create mode 100644 public/download/worker.js create mode 100644 src/lib/download.ts create mode 100644 tests/download.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a81b115..6b9fb78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- Added streaming downloads for the hosted app using a same-origin service + worker, with a 64 GiB cap and bounded buffering. Verified real 120 MiB downloads + in Chromium and Brave without the native file picker. +- Kept `file://` copies independent of hosted helpers; they continue to use the + native save picker or the 64 MiB in-memory option. +- Distinguished handing a file to the browser's download manager from confirming + that it was saved to disk. Added worker tests and a real-download browser check. + ## [0.0.3] - 2026-10-09 ### Added diff --git a/README.md b/README.md index 290a36f..76a9615 100644 --- a/README.md +++ b/README.md @@ -23,14 +23,21 @@ explicit opt-in by both people; no relay is configured automatically. Compare every byte. Cancel on any mismatch. Both people must explicitly confirm before the app sends the filename, size, MIME metadata, or contents. 4. The receiver sees the filename and size and explicitly accepts the file. - Supported browsers can stream directly to a chosen disk destination, up to - 64 GiB. Other browsers can receive files up to 64 MiB in memory and then offer - a download. Larger files require direct-to-disk support. Even capped memory - downloads may be too large on a memory-constrained device. + On the hosted app (HTTPS or localhost), **Receive as download** streams up to + 64 GiB into the browser's download manager using a same-origin service worker. + It requires transferable streams and service-worker support; Chromium and + Brave have been tested with 120 MiB files. Allow the download and keep the + receiving tab open. File contents are not uploaded to the web host. + **Choose destination & receive to disk** remains available with a supported + native file picker. **Receive in memory** retains its 64 MiB cap. Even capped + memory downloads may be too large on a memory-constrained device. 5. The sender waits for a receipt acknowledgment. For disk transfers, the receiver - sends this only after its writable stream closes successfully; for memory - transfers, after constructing the complete download. This does not prove a - human saved the memory download, nor that a malicious receiver told the truth. + sends this only after its writable stream closes successfully; for streaming + downloads, after handing all bytes to the browser; for memory transfers, + after constructing the complete download. A streaming receipt does not prove + the download manager successfully saved the file: check its final status in + Downloads. This also does not prove a human saved a memory download, nor that + a malicious receiver told the truth. The 64 GiB cap is not a tested size guarantee. Cancel, reset, changing the selected file, or switching Send/Receive closes the connection and aborts unfinished disk writes. Keep the tab open until receipt is @@ -146,6 +153,15 @@ Vue visibility. Test headers on the actual host; CSP is defense in depth and is not a substitute for trusting the host or a portable WebRTC egress filter. `robots.txt` and indexing metadata are crawler requests, not access control. +Deploy the complete `dist/` directory, including `download/worker.js`, served +with a JavaScript MIME type. The download worker has scope `download/` only: +it does not control the app page, cache the app, or proxy normal web requests. +It serves single-use, randomly named download URLs from incoming browser +streams, with bounded buffering. The default CSP above permits this; custom +policies must permit same-origin workers and frames. No third-party helper, +download backend, or additional hosting service is required. Closing/resetting +an unfinished transfer aborts it; interrupted transfers must restart. + ## Download and run locally Run `bun run build`, then open `dist/hellcon-local.html` directly in a browser. @@ -159,8 +175,12 @@ the app itself. The app still needs network access to connect peers on different machines, and the selected STUN or TURN servers must be reachable. A `file://` copy cannot use the host's managed TURN credential endpoint; enter your own relay details when -needed. Direct-to-disk receiving depends on browser support and may be unavailable -from a local file. The in-memory receive option remains available. +needed. Service-worker downloads are **disabled for `file://` copies**; there is +no hosted helper dependency in the local version. For large local transfers, +use desktop Chrome with its native save picker and select **Choose destination +& receive to disk**. Brave may disable that API even though it is Chromium-based. +Native disk access still depends on browser settings and platform support. +The 64 MiB in-memory receive option remains available. To self-host the regular multi-file build, serve the whole `dist/` directory, including `assets/`. Serve it over HTTPS for access from other machines. @@ -260,6 +280,7 @@ bun run typecheck bun run test bun run build bun run test:browser # local Chromium integration checks against dist/ +bun run test:download # real hosted downloads, including 120 MiB, with native picker disabled bun run test:cross-browser # Brave sender → Firefox receiver bun run preview # local build inspection only bun audit @@ -270,6 +291,9 @@ publishing a build. Protocol regression tests cover verification gating, malform messages, size limits, cancellation, receipt acknowledgment, and relay opt-in. The browser check requires Chromium at `/usr/bin/chromium` (override with `CHROMIUM_PATH`); it uses an isolated temporary profile and a loopback server. +Run `CHROMIUM_PATH=/usr/bin/brave bun run test:download` for the streaming +download check in Brave. Worker tests cover byte counts, backpressure, single-use +URLs, and browser/app cancellation; integration checks verify the actual saved bytes. The cross-browser check uses Brave and Firefox at `/usr/bin/brave` and `/usr/bin/firefox` (override with `BRAVE_PATH` and `FIREFOX_PATH`). It checks that the received file remains downloadable after the sender disconnects. diff --git a/package.json b/package.json index 697cdeb..b8de4df 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "preview": "vite preview", "test": "node --test tests/*.test.ts", "test:browser": "node scripts/browser-check.ts", + "test:download": "node scripts/browser-check.ts --stream-download", "test:cross-browser": "node scripts/cross-browser-check.ts", "typecheck": "vue-tsc --noEmit" }, diff --git a/public/download/worker.js b/public/download/worker.js new file mode 100644 index 0000000..8f67319 --- /dev/null +++ b/public/download/worker.js @@ -0,0 +1,70 @@ +/* Only handles single-use download URLs within this directory. No file uploads or cache. */ +const downloads = new Map(); +self.addEventListener('install', () => self.skipWaiting()); +self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); +self.addEventListener('message', event => { + const { type, id, name, size, stream } = event.data || {}; + const port = event.ports[0]; + if (type !== 'download' || !port || !/^[a-f0-9]{32}$/.test(id) || + typeof name !== 'string' || name.length > 255 || /[\r\n/\\]/.test(name) || + !Number.isSafeInteger(size) || size < 0 || size > 64 * 1024 ** 3 || + !(stream instanceof ReadableStream) || downloads.has(id)) return; + const reader = stream.getReader(); + let controller, finished = false, received = 0; + const finish = error => { + if (finished) return; + finished = true; + clearTimeout(timer); + downloads.delete(id); + if (error) { + controller?.error(error); + void reader.cancel(error.message).catch(() => {}); + } + port.postMessage({ type: error ? 'error' : 'complete', message: error?.message }); + port.close(); + }; + const timer = setTimeout(() => finish(new Error('Download did not start in time.')), 60000); + const body = new ReadableStream({ + start(value) { controller = value; }, + async pull() { + try { + const { done, value } = await reader.read(); + if (finished) return; + if (done) { + if (received !== size) throw new Error('Incomplete download.'); + controller.close(); finish(); + } else { + if (!(value instanceof Uint8Array) || value.byteLength > 16 * 1024 || received + value.byteLength > size) throw new Error('Invalid download data.'); + received += value.byteLength; + controller.enqueue(value); + } + } catch (error) { finish(error); } + }, + cancel() { finish(new Error('Download canceled in the browser.')); }, + }, { highWaterMark: 0 }); + port.onmessage = event => { + if (event.data?.type === 'abort') finish(new Error('Transfer canceled.')); + }; + downloads.set(id, { body, name, size, timer, port }); + port.postMessage({ type: 'ready', url: new URL(`file-${id}`, self.registration.scope).href }); +}); +self.addEventListener('fetch', event => { + const url = new URL(event.request.url); + const base = new URL(self.registration.scope); + if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname + 'file-')) return; + const id = url.pathname.slice((base.pathname + 'file-').length); + const download = downloads.get(id); + if (event.request.method !== 'GET' || !download) { + event.respondWith(new Response('Download expired.', { status: 404 })); return; + } + downloads.delete(id); + clearTimeout(download.timer); + download.port.postMessage({ type: 'started' }); + event.respondWith(new Response(download.body, { headers: { + 'Content-Type': 'application/octet-stream', + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(download.name.toWellFormed()).replace(/['()*]/g, char => '%' + char.charCodeAt(0).toString(16))}`, + 'Content-Length': String(download.size), + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', + } })); +}); diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index 8a775f4..bca6375 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -4,7 +4,8 @@ import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDis import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { createServer } from 'node:http'; -import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { mkdtemp, mkdir, readFile, rm, stat } from 'node:fs/promises'; +import { createReadStream } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, extname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; @@ -13,6 +14,7 @@ const axeSource = await readFile(join(root, 'node_modules/axe-core/axe.min.js'), const provider = process.argv.includes('--default-network') ? 'pagequit' : 'none'; const turn = process.argv.includes('--turn'); const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp'; +const streaming = process.argv.includes('--stream-download'); const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null; const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-')); const server = createServer(async (req, res) => { @@ -36,6 +38,7 @@ const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [ '--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank', ], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] }); interface ProtocolResults { + 'Browser.setDownloadBehavior': object; 'Target.createTarget': { targetId: string }; 'Target.attachToTarget': { sessionId: string }; 'Runtime.enable': object; @@ -94,6 +97,7 @@ async function page(url = origin) { await call('Runtime.enable', {}, sessionId); await call('Page.enable', {}, sessionId); await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId); + if (streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId); if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId); await call('Page.navigate', { url }, sessionId); for (let n = 0; n < 100; n++) { @@ -159,6 +163,38 @@ async function connect(sender: string, receiver: string, size: number) { } } try { + if (streaming) { + const downloads = join(profile, 'downloads'); + await mkdir(downloads); + await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); + const sender = await page(); + for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) { + const receiver = await page(); + await click(receiver, 'Receive'); + await connect(sender, receiver, size); + assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined'); + await click(receiver, 'Receive as download (up to 64 GiB)'); + await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file')); + assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/); + const destination = join(downloads, 'browser-test.bin'); + const deadline = Date.now() + 30000; + while (true) { + try { if ((await stat(destination)).size === size) break; } catch {} + if (Date.now() > deadline) throw new Error('Browser did not finish saving the download.'); + await new Promise(resolve => setTimeout(resolve, 100)); + } + let bytes = 0; + for await (const chunk of createReadStream(destination)) { + assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match'); + bytes += (chunk as Buffer).length; + } + assert.equal(bytes, size); + await rm(destination); + await click(sender, 'Reset'); + console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`); + } + assert.deepEqual(browserErrors, []); + } else { const sender = await page(), receiver = await page(); if (!turn) { assert.equal(await evaluate(sender, () => document.querySelector('#stun-provider')?.value), 'pagequit'); @@ -172,6 +208,7 @@ try { assert.equal(await evaluate(localReceiver, () => !!document.querySelector('#offer-input')), true); const localSender = await page(localUrl); await connect(localSender, localReceiver, 1024); + assert.equal(await evaluate(localReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent?.includes('Receive as download'))), false, 'file:// must not offer service-worker downloads'); await click(localReceiver, 'Receive in memory (up to 64 MiB)'); await wait(localReceiver, () => !!document.querySelector('a.download')); const data = await evaluate(localReceiver, async () => { @@ -231,6 +268,7 @@ try { console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.'); if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`); assert.deepEqual(browserErrors, []); + } } finally { browser.kill(); await new Promise(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); }); diff --git a/src/components/TransferPanel.vue b/src/components/TransferPanel.vue index f879956..a89960b 100644 --- a/src/components/TransferPanel.vue +++ b/src/components/TransferPanel.vue @@ -7,6 +7,7 @@ import NetworkSettings from './NetworkSettings.vue'; import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts'; import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts'; import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts'; +import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts'; type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState; interface Session { @@ -40,6 +41,8 @@ const defaultStun = location.protocol === 'file:' ? '' : import.meta.env.VITE_ST const settings = ref({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' }); const managedCredentials = ref(null); const canSaveToDisk = typeof window.showSaveFilePicker === 'function'; +const canStreamDownload = supportsStreamingDownload(); +const streamedDownload = ref(false); let active: Session | null = null; let copyTimer: ReturnType | undefined; const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value)); @@ -53,7 +56,7 @@ const status = computed(() => ({ 'choose-storage': 'Choose how to receive this file.', sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…', 'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…', - done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : 'File saved to disk.'), + done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'), closed: props.sending ? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.' : 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.', @@ -83,7 +86,7 @@ function reset(keepNetwork = false) { inputCode.value = outputCode.value = error.value = ''; fps.value = incoming.value = null; verified.value = copied.value = choosing.value = false; - progress.value = 0; step.value = 'idle'; + progress.value = 0; step.value = 'idle'; streamedDownload.value = false; } function fail(session: Session, err: unknown) { if (active !== session) return; @@ -216,19 +219,24 @@ function verify() { session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000); session.transfer?.verify(); } -async function acceptFile(toDisk: boolean) { +async function acceptFile(destination: 'disk' | 'memory' | 'download') { const session = active; if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return; choosing.value = true; error.value = ''; let writable: FileDestination | undefined; try { - if (toDisk) { + if (destination === 'download') { + writable = await createDownloadDestination(incoming.value, session.controller.signal); + if (active !== session) { await writable.abort(); return; } + } else if (destination === 'disk') { if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.'); const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name }); if (active !== session) return; writable = await handle.createWritable(); if (active !== session) { await writable.abort(); return; } } + streamedDownload.value = destination === 'download'; + session.diagnostics.record(`storage ${destination}`); session.transfer.accept(writable); } catch (err) { if (writable) await writable.abort().catch(() => {}); @@ -292,9 +300,11 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })

{{ incoming.name }} — {{ formatBytes(incoming.size) }}

Only accept files you expect. Encryption does not make their contents safe to open.

- - -

This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.

+ +

Allow the browser download and keep this page open until the transfer finishes. Check Downloads for the final save result.

+ + +

This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.

{{ status }}

diff --git a/src/lib/download.ts b/src/lib/download.ts new file mode 100644 index 0000000..09af772 --- /dev/null +++ b/src/lib/download.ts @@ -0,0 +1,88 @@ +import type { FileDestination, FileMetadata } from './transfer.ts'; + +export function supportsStreamingDownload() { + if (!['https:', 'http:'].includes(location.protocol) || !isSecureContext || + !navigator.serviceWorker || typeof TransformStream === 'undefined') return false; + const channel = new MessageChannel(); + const stream = new ReadableStream({ start(controller) { controller.close(); } }); + try { channel.port1.postMessage(stream, [stream]); return true; } + catch { return false; } + finally { channel.port1.close(); channel.port2.close(); } +} + +export async function createDownloadDestination(meta: FileMetadata, signal: AbortSignal): Promise { + if (!supportsStreamingDownload()) throw new Error('Streaming downloads require a supported browser and HTTPS or localhost.'); + signal.throwIfAborted(); + const stream = new TransformStream(); + const writer = stream.writable.getWriter(); + const channel = new MessageChannel(); + const frame = document.createElement('iframe'); + frame.hidden = true; frame.title = 'File download'; + let finished = false; + let stopWatchingWorker = () => {}; + let resolveReady!: () => void, rejectReady!: (error: Error) => void; + let resolveComplete!: () => void, rejectComplete!: (error: Error) => void; + const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; }); + const complete = new Promise((resolve, reject) => { resolveComplete = resolve; rejectComplete = reject; }); + void ready.catch(() => {}); void complete.catch(() => {}); void writer.closed.catch(() => {}); + const cleanup = () => { + clearTimeout(timer); + stopWatchingWorker(); + signal.removeEventListener('abort', canceled); + window.removeEventListener('pagehide', canceled); + channel.port1.close(); frame.remove(); + }; + const fail = (error: Error) => { + if (finished) return; + finished = true; + channel.port1.postMessage({ type: 'abort' }); + rejectReady(error); rejectComplete(error); + void writer.abort(error).catch(() => {}); + cleanup(); + }; + const canceled = () => fail(new DOMException('Transfer canceled.', 'AbortError')); + const timer = setTimeout(() => fail(new Error('Streaming download did not start. Check browser download permissions and try again.')), 30000); + signal.addEventListener('abort', canceled, { once: true }); + window.addEventListener('pagehide', canceled); + try { + const registration = await Promise.race([ + navigator.serviceWorker.register(new URL('./download/worker.js', location.href).href), + ready.then(() => { throw new Error('Unexpected download state.'); }), + ]); + const worker = registration.active || registration.installing || registration.waiting; + if (!worker) throw new Error('Download service worker is unavailable.'); + if (worker.state !== 'activated') await Promise.race([ + new Promise((resolve, reject) => { + const changed = () => { + if (worker.state === 'activated' || worker.state === 'redundant') { + worker.removeEventListener('statechange', changed); + worker.state === 'activated' ? resolve() : reject(new Error('Download service worker could not activate.')); + } + }; + stopWatchingWorker = () => worker.removeEventListener('statechange', changed); + worker.addEventListener('statechange', changed); changed(); + }), ready, + ]); + signal.throwIfAborted(); + if (finished) await ready; + const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join(''); + const url = new URL(`file-${id}`, registration.scope).href; + channel.port1.onmessage = event => { + if (event.data?.type === 'ready' && event.data.url === url) { + frame.src = url; document.body.append(frame); + } + if (event.data?.type === 'started') { clearTimeout(timer); resolveReady(); } + if (event.data?.type === 'error') fail(new Error(event.data.message || 'Download failed.')); + if (event.data?.type === 'complete' && !finished) { + finished = true; resolveComplete(); cleanup(); + } + }; + worker.postMessage({ type: 'download', id, name: meta.name, size: meta.size, stream: stream.readable }, [channel.port2, stream.readable]); + await ready; + return { + async write(data) { await writer.write(new Uint8Array(data)); }, + async close() { await writer.close(); await complete; }, + async abort() { canceled(); }, + }; + } catch (error) { fail(error instanceof Error ? error : new Error('Could not start download.')); throw error; } +} diff --git a/tests/download.test.ts b/tests/download.test.ts new file mode 100644 index 0000000..d433eb3 --- /dev/null +++ b/tests/download.test.ts @@ -0,0 +1,86 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +const source = readFileSync(new URL('../public/download/worker.js', import.meta.url), 'utf8'); +function worker() { + const listeners: Record void> = {}; + const scope = 'https://example.test/app/download/'; + const messages: Array<{ type: string; message?: string; url?: string }> = []; + const port = { postMessage: (message: typeof messages[number]) => messages.push(message), close() {}, onmessage: null as null | ((event: any) => void) }; + new Function('self', source)({ registration: { scope }, addEventListener(type: string, listener: (event: any) => void) { listeners[type] = listener; } }); + function start(stream: ReadableStream, size: number) { + listeners.message({ data: { type: 'download', id: 'a'.repeat(32), name: "report 'test'.bin", size, stream }, ports: [port] }); + assert.equal(messages[0]?.type, 'ready'); + } + async function fetch(url = messages[0]?.url) { + let response: Response | undefined; + listeners.fetch({ request: new Request(url!), respondWith(value: Response) { response = value; } }); + assert.ok(response); + return response; + } + return { start, fetch, messages, port }; +} + +test('download worker streams exact bytes, uses attachment headers, and consumes URLs once', async () => { + const w = worker(); + const stream = new TransformStream(); + w.start(stream.readable, 3); + const response = await w.fetch(); + assert.equal(response.headers.get('Content-Length'), '3'); + assert.match(response.headers.get('Content-Disposition')!, /attachment; filename\*=UTF-8''report%20%27test%27.bin/); + assert.equal(response.headers.get('Cache-Control'), 'no-store'); + assert.equal((await w.fetch()).status, 404); + const bytes = response.arrayBuffer(); + const writer = stream.writable.getWriter(); + await writer.write(Uint8Array.of(1, 2, 3)); + assert.equal(w.messages.some(message => message.type === 'complete'), false); + await writer.close(); + assert.deepEqual(new Uint8Array(await bytes), Uint8Array.of(1, 2, 3)); + assert.equal(w.messages.at(-1)?.type, 'complete'); +}); + +test('download backpressure blocks writes until the browser reads', async () => { + const w = worker(); + const stream = new TransformStream(); + w.start(stream.readable, 1); + const response = await w.fetch(); + let written = false; + const writer = stream.writable.getWriter(); + const write = writer.write(Uint8Array.of(7)).then(() => { written = true; }); + await new Promise(resolve => setTimeout(resolve, 10)); + assert.equal(written, false); + const bytes = response.arrayBuffer(); + await write; await writer.close(); await bytes; +}); + +for (const size of [0, 2]) test(`download rejects byte count mismatch (declared ${size})`, async () => { + const w = worker(); + w.start(new ReadableStream({ start(controller) { controller.enqueue(Uint8Array.of(7)); controller.close(); } }), size); + const response = await w.fetch(); + await assert.rejects(response.arrayBuffer()); + assert.equal(w.messages.at(-1)?.type, 'error'); + assert.equal(w.messages.some(message => message.type === 'complete'), false); +}); + +test('browser cancellation cancels the source and never reports completion', async () => { + const w = worker(); + let canceled = false; + w.start(new ReadableStream({ cancel() { canceled = true; } }), 100); + const response = await w.fetch(); + await response.body!.cancel(); + assert.equal(canceled, true); + assert.equal(w.messages.at(-1)?.type, 'error'); +}); + +test('app cancellation errors the browser response and cancels pending source reads', async () => { + const w = worker(); + let canceled = false; + w.start(new ReadableStream({ cancel() { canceled = true; } }), 100); + const response = await w.fetch(); + const read = response.arrayBuffer(); + w.port.onmessage!({ data: { type: 'abort' } }); + await assert.rejects(read, /canceled/); + assert.equal(canceled, true); + assert.equal(w.messages.at(-1)?.type, 'error'); +});