Compare commits

..
2 Commits
Author SHA1 Message Date
Schluffe 7856725c72 Add hosted service-worker streaming downloads 2026-10-16 13:49:17 +02:00
Schluffe a53022d717 Checkpoint before hosted streaming downloads 2026-10-16 13:37:54 +02:00
8 changed files with 344 additions and 17 deletions

No files matched your search

+10
View File
@@ -1,5 +1,15 @@
# Changelog # 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 ## [0.0.3] - 2026-10-09
### Added ### Added
+33 -9
View File
@@ -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 Compare every byte. Cancel on any mismatch. Both people must explicitly
confirm before the app sends the filename, size, MIME metadata, or contents. 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. 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 On the hosted app (HTTPS or localhost), **Receive as download** streams up to
64 GiB. Other browsers can receive files up to 64 MiB in memory and then offer 64 GiB into the browser's download manager using a same-origin service worker.
a download. Larger files require direct-to-disk support. Even capped memory It requires transferable streams and service-worker support; Chromium and
downloads may be too large on a memory-constrained device. 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 5. The sender waits for a receipt acknowledgment. For disk transfers, the receiver
sends this only after its writable stream closes successfully; for memory sends this only after its writable stream closes successfully; for streaming
transfers, after constructing the complete download. This does not prove a downloads, after handing all bytes to the browser; for memory transfers,
human saved the memory download, nor that a malicious receiver told the truth. 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 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 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. not a substitute for trusting the host or a portable WebRTC egress filter.
`robots.txt` and indexing metadata are crawler requests, not access control. `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 ## Download and run locally
Run `bun run build`, then open `dist/hellcon-local.html` directly in a browser. 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 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 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 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 needed. Service-worker downloads are **disabled for `file://` copies**; there is
from a local file. The in-memory receive option remains available. 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, To self-host the regular multi-file build, serve the whole `dist/` directory,
including `assets/`. Serve it over HTTPS for access from other machines. including `assets/`. Serve it over HTTPS for access from other machines.
@@ -260,6 +280,7 @@ bun run typecheck
bun run test bun run test
bun run build bun run build
bun run test:browser # local Chromium integration checks against dist/ 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 test:cross-browser # Brave sender → Firefox receiver
bun run preview # local build inspection only bun run preview # local build inspection only
bun audit 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. messages, size limits, cancellation, receipt acknowledgment, and relay opt-in.
The browser check requires Chromium at `/usr/bin/chromium` (override with The browser check requires Chromium at `/usr/bin/chromium` (override with
`CHROMIUM_PATH`); it uses an isolated temporary profile and a loopback server. `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 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 `/usr/bin/firefox` (override with `BRAVE_PATH` and `FIREFOX_PATH`). It checks
that the received file remains downloadable after the sender disconnects. that the received file remains downloadable after the sender disconnects.
+1
View File
@@ -14,6 +14,7 @@
"preview": "vite preview", "preview": "vite preview",
"test": "node --test tests/*.test.ts", "test": "node --test tests/*.test.ts",
"test:browser": "node scripts/browser-check.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", "test:cross-browser": "node scripts/cross-browser-check.ts",
"typecheck": "vue-tsc --noEmit" "typecheck": "vue-tsc --noEmit"
}, },
+70
View File
@@ -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',
} }));
});
+39 -1
View File
@@ -4,7 +4,8 @@ import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDis
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process'; import { spawn } from 'node:child_process';
import { createServer } from 'node:http'; 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 { tmpdir } from 'node:os';
import { dirname, extname, join, resolve } from 'node:path'; import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url'; 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 provider = process.argv.includes('--default-network') ? 'pagequit' : 'none';
const turn = process.argv.includes('--turn'); const turn = process.argv.includes('--turn');
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp'; 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 vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null;
const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-')); const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
const server = createServer(async (req, res) => { 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', '--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] }); ], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
interface ProtocolResults { interface ProtocolResults {
'Browser.setDownloadBehavior': object;
'Target.createTarget': { targetId: string }; 'Target.createTarget': { targetId: string };
'Target.attachToTarget': { sessionId: string }; 'Target.attachToTarget': { sessionId: string };
'Runtime.enable': object; 'Runtime.enable': object;
@@ -94,6 +97,7 @@ async function page(url = origin) {
await call('Runtime.enable', {}, sessionId); await call('Runtime.enable', {}, sessionId);
await call('Page.enable', {}, sessionId); await call('Page.enable', {}, sessionId);
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, 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); if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url }, sessionId); await call('Page.navigate', { url }, sessionId);
for (let n = 0; n < 100; n++) { for (let n = 0; n < 100; n++) {
@@ -159,6 +163,38 @@ async function connect(sender: string, receiver: string, size: number) {
} }
} }
try { 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(); const sender = await page(), receiver = await page();
if (!turn) { if (!turn) {
assert.equal(await evaluate(sender, () => document.querySelector<HTMLSelectElement>('#stun-provider')?.value), 'pagequit'); assert.equal(await evaluate(sender, () => document.querySelector<HTMLSelectElement>('#stun-provider')?.value), 'pagequit');
@@ -172,6 +208,7 @@ try {
assert.equal(await evaluate(localReceiver, () => !!document.querySelector('#offer-input')), true); assert.equal(await evaluate(localReceiver, () => !!document.querySelector('#offer-input')), true);
const localSender = await page(localUrl); const localSender = await page(localUrl);
await connect(localSender, localReceiver, 1024); 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 click(localReceiver, 'Receive in memory (up to 64 MiB)');
await wait(localReceiver, () => !!document.querySelector('a.download')); await wait(localReceiver, () => !!document.querySelector('a.download'));
const data = await evaluate(localReceiver, async () => { 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.'); 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.`); if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`);
assert.deepEqual(browserErrors, []); assert.deepEqual(browserErrors, []);
}
} finally { } finally {
browser.kill(); browser.kill();
await new Promise<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); }); await new Promise<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); });
+17 -7
View File
@@ -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 { 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 { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts'; import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState; type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session { interface Session {
@@ -40,6 +41,8 @@ const defaultStun = location.protocol === 'file:' ? '' : import.meta.env.VITE_ST
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' }); const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
const managedCredentials = ref<IceOptions | null>(null); const managedCredentials = ref<IceOptions | null>(null);
const canSaveToDisk = typeof window.showSaveFilePicker === 'function'; const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
const canStreamDownload = supportsStreamingDownload();
const streamedDownload = ref(false);
let active: Session | null = null; let active: Session | null = null;
let copyTimer: ReturnType<typeof setTimeout> | undefined; let copyTimer: ReturnType<typeof setTimeout> | undefined;
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value)); const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
@@ -53,7 +56,7 @@ const status = computed(() => ({
'choose-storage': 'Choose how to receive this file.', 'choose-storage': 'Choose how to receive this file.',
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…', sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
'awaiting-receipt': 'Waiting for the receiver to confirm the complete 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 closed: props.sending
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.' ? '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.', : '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 = ''; inputCode.value = outputCode.value = error.value = '';
fps.value = incoming.value = null; fps.value = incoming.value = null;
verified.value = copied.value = choosing.value = false; 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) { function fail(session: Session, err: unknown) {
if (active !== session) return; 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.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
session.transfer?.verify(); session.transfer?.verify();
} }
async function acceptFile(toDisk: boolean) { async function acceptFile(destination: 'disk' | 'memory' | 'download') {
const session = active; const session = active;
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return; if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
choosing.value = true; error.value = ''; choosing.value = true; error.value = '';
let writable: FileDestination | undefined; let writable: FileDestination | undefined;
try { 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.'); if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name }); const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
if (active !== session) return; if (active !== session) return;
writable = await handle.createWritable(); writable = await handle.createWritable();
if (active !== session) { await writable.abort(); return; } if (active !== session) { await writable.abort(); return; }
} }
streamedDownload.value = destination === 'download';
session.diagnostics.record(`storage ${destination}`);
session.transfer.accept(writable); session.transfer.accept(writable);
} catch (err) { } catch (err) {
if (writable) await writable.abort().catch(() => {}); if (writable) await writable.abort().catch(() => {});
@@ -292,9 +300,11 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<div v-if="incoming && step === 'choose-storage'" class="incoming"> <div v-if="incoming && step === 'choose-storage'" class="incoming">
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p> <p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p> <p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile(true)">Choose destination & receive to disk</button> <button v-if="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download (up to 64 GiB)</button>
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile(false)">Receive in memory (up to 64 MiB)</button> <p v-if="canStreamDownload" class="status">Allow the browser download and keep this page open until the transfer finishes. Check Downloads for the final save result.</p>
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p> <button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile('disk')">Choose destination & receive to disk</button>
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button>
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
</div> </div>
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div> <div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
<p class="status" role="status">{{ status }}</p> <p class="status" role="status">{{ status }}</p>
+88
View File
@@ -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<FileDestination> {
if (!supportsStreamingDownload()) throw new Error('Streaming downloads require a supported browser and HTTPS or localhost.');
signal.throwIfAborted();
const stream = new TransformStream<Uint8Array, Uint8Array>();
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<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
const complete = new Promise<void>((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<void>((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; }
}
+86
View File
@@ -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<string, (event: any) => 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');
});