Compare commits

..
2 Commits
Author SHA1 Message Date
Schluffe 1bfeb9843a add missing ws.js and introduce save check for both sides 2026-10-22 23:29:55 +02:00
Schluffe ff7b84af02 Fix large file download 2026-10-22 22:57:41 +02:00
5 changed files with 566 additions and 157 deletions

No files matched your search

+15 -48
View File
@@ -1,57 +1,24 @@
# TODO
## Next: service worker streaming download
## Ideas
Stream received bytes straight into the browser's download manager instead of staging them in OPFS.
Needs one new file (service workers can only be registered from a real same-origin script).
- Removes the OPFS staging copy, so the file no longer takes twice the disk space.
- Removes the OPFS quota cap (~10 GiB per site, 2000 MiB in Chromium incognito).
- Fixes "Opening another tab breaks existing downloads" below completely.
## Review findings
### [P2] Opening another tab breaks existing downloads
`clearStorage()` runs on startup and deletes every OPFS entry. OPFS is shared by all tabs of the
origin, so it also deletes the file behind another tab's not yet clicked download link.
- Real fix: Web Locks. Each tab holds a lock named after every file it received (released by the
browser when the tab closes or crashes). Cleanup only removes entries whose lock is free
(`navigator.locks.request(name, { ifAvailable: true }, ...)`).
- Fixed by the service worker download: no OPFS staging, nothing to clean up.
### [P2] Disk writes have no flow control
Chunks go data channel → main thread → worker message queue → disk without waiting for writes. If
storage is slower than the network (SD card, HDD, throttled background tab), queued buffers grow
without bound in RAM.
- Real fix: application level acknowledgements. The receiving side cannot pause a data channel,
so the worker reports its written offset, the receiver sends it to the sender over the data
channel, and the sender keeps at most a fixed window (e.g. 8 MiB) unacknowledged, on top of the
existing `bufferedAmount` check.
- Not fixed by the service worker: stream backpressure stops at the receiver, it still has to
reach the sender.
- Bonus: the acknowledged offset is the basis for resuming interrupted transfers.
### [P2] Storage failures don't stop the transfer
A write failure is only logged on the receiver. The sender keeps sending and reports "sent", which
only means "handed to the send buffer".
- Real fix:
1. Check `navigator.storage.estimate()` against the announced size before accepting, optionally
`navigator.storage.persist()` (raises Firefox's limit after a prompt).
2. Report errors to the sender (`{ error }` message or closing the channel), sender stops.
3. Receiver sends "done" only after the final flush, sender shows "delivered" only then.
- Partly fixed by the service worker: the quota failure goes away, but download errors and user
cancels still have to be reported to the sender.
- Points 2 and 3 share the receiver → sender control channel with the flow control fix, build them
together.
- Resume interrupted transfers: the receiver already reports how much the download manager has
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
finished or failed download though, so a resume would have to start a new one.
## Open observations
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
logs "download failed: connection lost", but the download stays "in progress" until the user
cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
complete despite `Content-Length`. Chromium fails the download, but only once the connection
counts as failed (~16 s), because its data channel never fires `close` for a vanished peer.
- Firefox also saves a truncated file as complete when it stops the service worker in the middle of
a download (after 30 s without events). The receiver's pings (`KEEPALIVE`) prevent that, covered by
`large: firefox survives a 40 s stall`. A browser that stops it anyway would still never show
"download complete" or "delivered", only its download manager would be wrong.
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite),
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again.
+277 -23
View File
@@ -1,15 +1,19 @@
import { createHash, randomBytes } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { open as openFile, writeFile } from 'node:fs/promises';
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
import { chromium, expect, firefox, test, type Browser, type BrowserType, type Page } from '@playwright/test';
import { createServer, type ViteDevServer } from 'vite';
// Runs against the real public trackers and STUN servers from src/main.ts.
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
const SIZE = 5_000_000;
// Opt-in with LARGE=1: beyond the 2000 MiB Chromium stores in incognito-like contexts, and far
// beyond what the old in-memory receiver handled.
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
// staging could store in incognito-like contexts.
const LARGE_SIZE = 2.5 * 2 ** 30;
// Big enough that the transfer still runs while a test updates sw.js, cancels or disconnects.
const RUNNING_SIZE = 100_000_000;
// WINDOW in src/main.ts.
const WINDOW = 8 * 2 ** 20;
// Each mode connects a sender page that already picked a file to a receiver page.
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
@@ -52,12 +56,28 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
let server: ViteDevServer;
let url: string;
const browsers: Browser[] = [];
// Appended to sw.js, so raising it makes the browser see an update, like a deploy.
let swVersion = 0;
test.describe.configure({ mode: 'parallel' });
test.setTimeout(60_000);
test.beforeAll(async () => {
server = await createServer({ logLevel: 'silent', server: { port: 0 } });
server = await createServer({
logLevel: 'silent',
server: { port: 0 },
plugins: [
{
name: 'sw-version',
configureServer({ middlewares }) {
middlewares.use('/sw.js', async (_, res) => {
res.setHeader('Content-Type', 'text/javascript');
res.end(`${await readFile('public/sw.js', 'utf8')}\n// ${swVersion}\n`);
});
},
},
],
});
await server.listen();
url = server.resolvedUrls!.local[0]!;
});
@@ -67,11 +87,13 @@ test.afterAll(async () => {
await server.close();
});
async function open(name: string, sockets: string[]) {
// init runs in the page before the app.
async function open(name: string, sockets: string[], init?: () => void) {
const browser = await BROWSERS[name]!.launch();
browsers.push(browser);
const page = await (await browser.newContext()).newPage();
page.on('websocket', (ws) => sockets.push(ws.url()));
if (init) await page.addInitScript(init);
await page.goto(url);
return page;
}
@@ -84,9 +106,86 @@ async function hash(path: string) {
const log = (page: Page) => page.locator('#log').textContent();
// Sends the file at source and verifies security check, OPFS storage and the downloaded bytes.
async function transfer(mode: string, sender: Page, receiver: Page, source: string, size: number) {
// Init script for a receiver: holds back its { read } reports to the sender until release(), as if
// the download manager read nothing, and counts the bytes that arrive. It runs in the hidden frames
// too, only the app's own window counts.
function holdReads() {
if (window !== window.top) return;
const page = window as unknown as { received: number; release: () => void };
const held: [RTCDataChannel, string][] = [];
let holding = true;
page.received = 0;
const send = RTCDataChannel.prototype.send as (this: RTCDataChannel, data: unknown) => void;
RTCDataChannel.prototype.send = function (this: RTCDataChannel, data: unknown) {
if (holding && typeof data === 'string' && data.includes('"read"')) return void held.push([this, data]);
send.call(this, data);
};
// Registered before the app's handlers, so the chunks are counted before it transfers them away.
const PeerConnection = RTCPeerConnection;
window.RTCPeerConnection = class extends PeerConnection {
constructor(config?: RTCConfiguration) {
super(config);
this.addEventListener('datachannel', ({ channel }) =>
channel.addEventListener('message', ({ data }) => (page.received += data.byteLength ?? 0)),
);
}
};
page.release = () => {
holding = false;
for (const [channel, data] of held) send.call(channel, data);
};
}
// Init script for a sender: keeps its data channels in window.channels, so a test can send on them
// like a peer that skips the security check.
function recordChannels() {
const page = window as unknown as { channels: RTCDataChannel[] };
page.channels = [];
const create = RTCPeerConnection.prototype.createDataChannel;
RTCPeerConnection.prototype.createDataChannel = function (this: RTCPeerConnection, ...args) {
const channel = create.apply(this, args);
page.channels.push(channel);
return channel;
};
}
const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received);
const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release());
// Changes sw.js and has the page's browser install it, as after a deploy while the tab is open.
async function updateWorker(page: Page) {
await expect
.poll(() => page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.active))
.toBe(true);
swVersion++;
await page.evaluate(async () => {
const registration = (await navigator.serviceWorker.getRegistration('download/'))!;
Object.assign(window, { previous: registration.active });
await registration.update();
});
}
// Whether the updated sw.js took over from the one that was active when updateWorker ran.
const updated = (page: Page) =>
page.evaluate(
async () =>
(await navigator.serviceWorker.getRegistration('download/'))!.active !==
(window as { previous?: ServiceWorker }).previous,
);
// Runs fn and attaches both logs to the report, also when it fails. A closed page has none left.
async function withLogs(sender: Page, receiver: Page, fn: () => Promise<void>) {
try {
await fn();
} finally {
for (const [name, page] of [['sender', sender], ['receiver', receiver]] as const) {
await test.info().attach(`${name} log`, { body: (await log(page).catch(() => null)) ?? '' });
}
}
}
// Connects and verifies that both sides show the same security check, swapped.
async function connect(mode: string, sender: Page, receiver: Page, source: string) {
await sender.setInputFiles('input[type=file]', source);
await MODES[mode]!(sender, receiver);
@@ -96,27 +195,51 @@ async function transfer(mode: string, sender: Page, receiver: Page, source: stri
});
await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!);
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
await expect(sender.locator('#log')).toContainText('waiting for the security check');
await expect(receiver.locator('#log')).not.toContainText('receiving');
for (const page of [sender, receiver]) {
await expect(page.locator('#log')).toContainText('waiting for the security check');
}
}
// Resolves with the download, which starts on its own as soon as the file is announced, and the
// receiver log at that moment.
const downloadStarts = (receiver: Page) =>
receiver
.waitForEvent('download', { timeout: test.info().timeout })
.then(async (download) => ({ download, logAtStart: await log(receiver) }));
// Connects and confirms the security check on both sides.
async function start(mode: string, sender: Page, receiver: Page, source: string) {
await connect(mode, sender, receiver, source);
const started = downloadStarts(receiver);
await sender.click('#confirm');
await expect(receiver.locator('#download')).toBeVisible({ timeout: test.info().timeout });
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
await expect(receiver.locator('#log')).not.toContainText('receiving');
await receiver.click('#confirm');
return started;
}
// The receiver must have written the file to OPFS, not collected it in RAM.
const stored = await receiver.evaluate(async () => {
const sizes = [];
const root = await navigator.storage.getDirectory();
for await (const handle of root.values()) sizes.push((await (handle as FileSystemFileHandle).getFile()).size);
return sizes;
});
expect(stored).toEqual([size]);
// Sends the file at source and verifies the downloaded bytes. during runs once the download started.
async function transfer(
mode: string,
sender: Page,
receiver: Page,
source: string,
size: number,
during?: () => Promise<void>,
) {
await withLogs(sender, receiver, async () => {
const { download, logAtStart } = await start(mode, sender, receiver, source);
// Streamed, not staged: 2.5 GiB can't arrive before the download manager takes over.
if (size === LARGE_SIZE) expect(logAtStart).not.toContain('received');
await during?.();
const [download] = await Promise.all([receiver.waitForEvent('download'), receiver.click('#download')]);
expect(download.suggestedFilename()).toBe(source.split('/').pop());
expect(await hash(await download.path())).toBe(await hash(source));
} finally {
await test.info().attach('sender log', { body: (await log(sender)) ?? '' });
await test.info().attach('receiver log', { body: (await log(receiver)) ?? '' });
}
await expect(receiver.locator('#log')).toContainText('download complete');
await expect(sender.locator('#log')).toContainText('delivered');
// Removed hidden pages release the service worker for updates.
await expect(receiver.locator('iframe')).toHaveCount(0);
});
}
for (const mode of Object.keys(MODES)) {
@@ -138,6 +261,137 @@ for (const mode of Object.keys(MODES)) {
}
for (const name of Object.keys(BROWSERS)) {
test(`update: ${name} receives after sw.js changed`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(SIZE));
await updateWorker(receiver);
await expect.poll(() => updated(receiver)).toBe(true);
await transfer('offline', sender!, receiver!, source, SIZE);
});
test(`update: ${name} keeps a running download when sw.js changes`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(RUNNING_SIZE));
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
// Paused at the window, so the transfer is guaranteed to still run during the update.
await expect.poll(() => received(receiver!)).toBe(WINDOW);
await updateWorker(receiver!);
// The update has to wait instead of replacing the worker that feeds the download.
await expect
.poll(() => receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting))
.toBe(true);
expect(await updated(receiver!)).toBe(false);
await release(receiver!);
});
// Released once the download is complete, so the update takes over.
await expect.poll(() => updated(receiver)).toBe(true);
});
test(`cancel: ${name} stops receiving when the download is cancelled`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
await withLogs(sender!, receiver!, async () => {
const { download } = await start('offline', sender!, receiver!, source);
await download.cancel();
// A transfer that already finished would report no failure.
expect(await download.failure()).toBe('canceled');
await expect(receiver!.locator('#log')).toContainText('download cancelled');
await expect(receiver!.locator('iframe')).toHaveCount(0);
expect(await log(receiver!)).not.toContain('download complete');
// The window keeps the sender from having sent everything before it hears about the cancel.
await expect(sender!.locator('#log')).toContainText('receiver stopped: download cancelled');
expect(await log(sender!)).not.toMatch(/ sent$/m);
});
});
test(`flow: ${name} sender waits while the download manager reads nothing`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(RUNNING_SIZE));
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
await expect.poll(() => received(receiver!)).toBe(WINDOW);
// Proving that nothing more comes needs a moment, the sender fills the window in milliseconds.
await receiver!.waitForTimeout(1000);
expect(await received(receiver!)).toBe(WINDOW);
await release(receiver!);
});
});
test(`check: ${name} accepts nothing before the receiver confirmed`, async () => {
const [sender, receiver] = await Promise.all([open(name, [], recordChannels), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(SIZE));
await withLogs(sender!, receiver!, async () => {
let downloads = 0;
receiver!.on('download', () => downloads++);
await connect('offline', sender!, receiver!, source);
// What a man in the middle could send without waiting for anyone's confirmation.
await sender!.evaluate(() => {
const [channel] = (window as unknown as { channels: RTCDataChannel[] }).channels;
channel!.send(JSON.stringify({ name: 'injected.bin', size: 4 }));
channel!.send(new Uint8Array(4));
});
await sender!.click('#confirm');
await expect(sender!.locator('#log')).toContainText("waiting for the receiver's security check");
// Proving that nothing starts needs a moment, a download would start within milliseconds.
await receiver!.waitForTimeout(1000);
expect(await log(receiver!)).not.toContain('receiving');
expect(await log(sender!)).not.toContain('sending');
expect(downloads).toBe(0);
const started = downloadStarts(receiver!);
await receiver!.click('#confirm');
const { download } = await started;
expect(download.suggestedFilename()).toBe('payload.bin');
expect(await hash(await download.path())).toBe(await hash(source));
await expect(sender!.locator('#log')).toContainText('delivered');
expect(downloads).toBe(1);
});
});
test(`disconnect: ${name} fails the download when the sender vanishes`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
await withLogs(sender!, receiver!, async () => {
const { download } = await start('offline', sender!, receiver!, source);
await sender!.context().close();
// Chromium only notices once the connection counts as failed, after ~16 s.
await expect(receiver!.locator('#log')).toContainText('download failed: connection lost', {
timeout: 30_000,
});
await expect(receiver!.locator('iframe')).toHaveCount(0);
// Firefox leaves the download stalled instead of failing it, see TODO.md.
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
});
});
}
for (const name of Object.keys(BROWSERS)) {
test(`large: ${name} survives a 40 s stall`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(120_000);
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(RUNNING_SIZE));
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
await expect.poll(() => received(receiver!)).toBe(WINDOW);
// Past the 30 s after which Firefox stops a service worker without events.
await receiver!.waitForTimeout(40_000);
await release(receiver!);
});
});
test(`large: ${name} sends 2.5 GiB`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(300_000);
+77
View File
@@ -0,0 +1,77 @@
// Streams received files into the browser's download manager. It is the only script besides the app
// because service workers can only be registered from a same-origin script URL. Registered with the
// scope download/ by src/main.ts, it sees no other requests.
// Downloads by id while the page sends chunks: the queue, the stream controller, its wake up, the
// reply port and how many bytes the download manager has read.
const downloads = new Map();
// Responses by download id, until the download navigation fetches them. Each is served only once.
const responses = new Map();
function open(id, { name, size }, port) {
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
const body = new ReadableStream(
{
start: (controller) => (download.controller = controller),
// With highWaterMark 0 the download manager pulls only when it wants more, so reaching the end
// marker here means it has read every byte.
async pull(controller) {
while (!download.chunks.length) await new Promise((resolve) => (download.wake = resolve));
const chunk = download.chunks.shift();
if (chunk) {
download.read += chunk.byteLength;
// Every MiB, src/main.ts forwards it to the sender for its flow control window.
if (download.read - download.reported >= 2 ** 20) port.postMessage((download.reported = download.read));
return controller.enqueue(chunk);
}
controller.close();
downloads.delete(id);
port.postMessage('finished');
},
// The user cancelled the download.
cancel: () => {
downloads.delete(id);
port.postMessage('cancelled');
},
},
{ highWaterMark: 0 },
);
downloads.set(id, download);
// RFC 8187 encoding, which leaves nothing in the name that could end the header value.
const encoded = encodeURIComponent(name.toWellFormed()).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16)}`);
const headers = {
'Content-Type': 'application/octet-stream',
'Content-Length': String(size),
'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
};
responses.set(id, new Response(body, { headers }));
port.postMessage('ready');
}
// The page posts the metadata with a reply port first, then every chunk as its own message and
// finally done (queued as the end marker null) or an error. Pings come in between.
self.addEventListener('message', ({ data, ports: [port] }) => {
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/main.ts.
if (data.ping) return;
if (port) return open(data.id, data, port);
const download = downloads.get(data.id);
if (!download) return;
if (data.error) {
download.controller.error(new Error(data.error));
downloads.delete(data.id);
download.port.postMessage('failed');
} else {
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
download.wake();
}
});
self.addEventListener('fetch', (event) => {
const id = new URL(event.request.url).pathname.split('/').pop();
// download/ itself is the empty page src/main.ts keeps open to hold this worker during a transfer.
if (!id) return event.respondWith(new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }));
const response = responses.get(id);
responses.delete(id);
event.respondWith(response ?? new Response('download expired', { status: 404 }));
});
+6 -10
View File
@@ -23,22 +23,20 @@ const answer = ref('');
const receiveCode = ref('');
const check = ref<Check>();
const confirmSend = ref<() => void>();
const download = ref<{ name: string; url: string }>();
const confirmCheck = ref<() => void>();
const log = ref<string[]>([]);
const events: Events = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
file: (name, url) => (download.value = { name, url }),
check: (result, confirm) => {
check.value = result;
confirmSend.value = confirm;
confirmCheck.value = confirm;
},
};
function onConfirm() {
confirmSend.value?.();
confirmSend.value = undefined;
confirmCheck.value?.();
confirmCheck.value = undefined;
}
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
@@ -112,12 +110,10 @@ function onReceive() {
<p v-if="check">
Security check, you: <output id="check-local">{{ check.local }}</output>, peer:
<output id="check-remote">{{ check.remote }}</output>. The other side must show the same two codes swapped.
<button v-if="confirmSend" id="confirm" @click="onConfirm">Codes match, send</button>
<output id="check-remote">{{ check.remote }}</output>. The other side must show the same two codes swapped. Both sides confirm, nothing is transferred before.
<button v-if="confirmCheck" id="confirm" @click="onConfirm">Codes match</button>
</p>
<p v-if="download"><a id="download" :href="download.url" :download="download.name">{{ download.name }}</a></p>
<h2>Log</h2>
<pre id="log">{{ log.join('\n') }}</pre>
</main>
+191 -76
View File
@@ -16,6 +16,12 @@ export const settings = { stun: true };
const CHUNK_SIZE = 16 * 1024;
const MAX_BUFFERED = 1024 * 1024;
// The receiving side can't pause a data channel, so it reports how much the download manager has
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM.
const WINDOW = 8 * 1024 * 1024;
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
const KEEPALIVE = 10_000;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
@@ -23,9 +29,8 @@ export type Check = { local: string; remote: string };
export type Events = {
log: (message: string) => void;
file: (name: string, url: string) => void;
// confirm is only passed on the sender side, the file is sent once it is called.
check: (check: Check, confirm?: () => void) => void;
// Called on both sides, confirm once the user compared the codes and they match.
check: (check: Check, confirm: () => void) => void;
};
function createPeerConnection() {
@@ -88,100 +93,220 @@ function securityCheck(pc: RTCPeerConnection): Check {
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
}
// With confirm, resolves once the user compared the codes, so nothing is sent to a man in the middle.
function connected(pc: RTCPeerConnection, via: string, events: Events, confirm = false) {
// Resolves once the user compared the codes. Both sides wait for it: the sender sends nothing to a man
// in the middle, the receiver accepts no file from one.
function connected(pc: RTCPeerConnection, via: string, events: Events) {
events.log(`connected via ${via}`);
if (confirm) events.log('waiting for the security check');
return new Promise<void>((resolve) => events.check(securityCheck(pc), confirm ? resolve : undefined));
events.log('waiting for the security check');
return new Promise<void>((resolve) => events.check(securityCheck(pc), resolve));
}
async function sendFile(channel: RTCDataChannel, file: File, events: Events) {
// Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers
// with { read } progress, { done } once the download manager read the last byte, or { error } when
// its download was cancelled or failed.
async function sendFile(
pc: RTCPeerConnection,
channel: RTCDataChannel,
file: File,
events: Events,
checked: Promise<void>,
) {
if (channel.readyState !== 'open') {
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
}
let read = 0;
let accepted = false;
let sending = false;
let stopped = false;
// Every event the send loop can wait for calls this.
let wake = () => {};
const stop = (message: string) => {
if (stopped) return;
stopped = true;
events.log(message);
wake();
};
channel.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.ok) accepted = true;
// Before that, nothing else can come from a receiver that passed its check.
else if (!sending) return;
if (message.read) read = message.read;
if (message.done) {
events.log('delivered');
// Finished, a later close is no loss.
stopped = true;
}
if (message.error) stop(`receiver stopped: ${message.error}`);
wake();
};
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
channel.addEventListener('close', () => stop('connection lost'));
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && stop('connection lost'));
channel.addEventListener('bufferedamountlow', () => wake());
await checked;
if (!accepted && !stopped) events.log("waiting for the receiver's security check");
while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
sending = true;
events.log(`sending ${file.name} (${file.size} bytes)`);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
if (channel.bufferedAmount > MAX_BUFFERED) {
await new Promise((resolve) => channel.addEventListener('bufferedamountlow', resolve, { once: true }));
while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
await new Promise<void>((resolve) => (wake = resolve));
}
channel.send(await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer());
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
if (stopped) return;
channel.send(chunk);
}
events.log('sent');
}
// Runs in a dedicated worker, because OPFS sync access handles only exist there. It is started from
// a Blob URL so the app stays one script, which means it must not use anything outside its body.
function storageWorker() {
type SyncHandle = { write(data: ArrayBuffer, options: { at: number }): number; flush(): void; close(): void };
let handle: SyncHandle;
let offset = 0;
let queue = Promise.resolve();
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests.
const downloads = registerDownloads();
// Opening is async, the queue keeps chunks from overtaking it and each other.
self.onmessage = ({ data }: MessageEvent) => {
queue = queue
.then(async () => {
if (data.open) {
const root = await navigator.storage.getDirectory();
const file = await root.getFileHandle(data.open, { create: true });
handle = await (file as unknown as { createSyncAccessHandle(): Promise<SyncHandle> }).createSyncAccessHandle();
} else if (data.chunk) {
// Over quota some browsers write less instead of throwing.
const written = handle.write(data.chunk, { at: offset });
offset += written;
if (written !== data.chunk.byteLength) throw new Error(`storage full after ${offset} bytes`);
} else {
handle.flush();
handle.close();
self.postMessage({ done: true });
// Only the first visit has to wait here, updates are picked up per transfer by holdWorker.
async function registerDownloads() {
const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' });
const pending = registration.installing ?? registration.waiting;
if (!registration.active && pending) {
await new Promise((resolve) =>
pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)),
);
}
})
.catch((error) => {
self.postMessage({ error: String(error) });
self.close();
if (!registration.active) throw new Error('service worker did not activate');
}
// Awaited before receiving starts, so a browser without service workers fails before connecting.
function downloadsReady(events: Events) {
return downloads.catch((error) => {
events.log(`downloads unavailable: ${error}`);
throw error;
});
};
}
const STORAGE_WORKER = URL.createObjectURL(new Blob([`(${storageWorker})()`], { type: 'text/javascript' }));
// Received files are written to OPFS instead of RAM and stay there until the next visit, because the
// download link reads from them.
async function clearStorage() {
const root = await navigator.storage.getDirectory();
for await (const name of root.keys()) await root.removeEntry(name);
// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling
// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that
// worker in the middle of the download.
async function holdWorker() {
await downloads;
const frame = document.createElement('iframe');
frame.hidden = true;
frame.src = 'download/';
document.body.append(frame);
await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true }));
const worker = frame.contentWindow!.navigator.serviceWorker.controller;
if (!worker) {
frame.remove();
throw new Error('service worker did not take over');
}
return { frame, worker };
}
function receiveFile(channel: RTCDataChannel, events: Events) {
// Accepts nothing until checked resolved, then tells the sender with { ok }.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, checked: Promise<void>) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
let worker: Worker | undefined;
let received = 0;
let confirmed = false;
let ended = false;
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
let worker: Promise<ServiceWorker | void> = Promise.resolve();
const post = (message: object, transfer: Transferable[] = []) =>
worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
// To the sender, see sendFile.
const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message));
async function stored() {
worker!.terminate();
const root = await navigator.storage.getDirectory();
const file = await (await root.getFileHandle(id)).getFile();
events.log('received');
events.file(meta!.name, URL.createObjectURL(file));
let keepalive: ReturnType<typeof setInterval> | undefined;
// Releases the worker, so a waiting update can take over.
function release() {
clearInterval(keepalive);
for (const frame of frames) frame.remove();
}
// The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the
// download running instead of failing it.
function fail(reason: string) {
if (ended) return;
ended = true;
post({ error: reason });
reply({ error: reason });
events.log(`download failed: ${reason}`);
}
function startDownload() {
worker = holdWorker().then(({ frame, worker }) => {
frames.push(frame);
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
worker.addEventListener('statechange', () => {
if (worker.state !== 'redundant') return;
fail('service worker stopped');
release();
});
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => {
if (typeof data === 'number') return reply({ read: data });
if (data === 'ready' && !ended) {
// A navigation, not fetch(): only navigations hand the response to the download manager.
const download = document.createElement('iframe');
download.hidden = true;
download.src = `download/${id}`;
document.body.append(download);
frames.push(download);
return;
}
if (data === 'finished') {
events.log('download complete');
reply({ done: true });
}
if (data === 'cancelled' && !ended) {
events.log('download cancelled');
reply({ error: 'download cancelled' });
}
ended = true;
release();
};
worker.postMessage({ id, ...meta }, [port2]);
return worker;
}, (error) => fail(String(error)));
}
checked.then(() => {
confirmed = true;
reply({ ok: true });
events.log('waiting for the sender');
});
channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => {
if (ended || !confirmed) return;
if (typeof data === 'string') {
meta = JSON.parse(data);
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
worker = new Worker(STORAGE_WORKER);
worker.onmessage = ({ data }) => (data.error ? events.log(`storage failed: ${data.error}`) : stored());
worker.postMessage({ open: id });
startDownload();
} else {
received += data.byteLength;
worker!.postMessage({ chunk: data }, [data]);
post({ chunk: data }, [data]);
}
if (meta && received === meta.size) {
post({ done: true });
events.log('received');
}
if (meta && received === meta.size) worker!.postMessage({ done: true });
};
// Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished
// peer only closes the channel in Firefox, Chromium just fails the connection.
function lost() {
if (meta && received < meta.size) fail('connection lost');
}
channel.addEventListener('close', lost);
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
}
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
@@ -189,10 +314,7 @@ function receiveFile(channel: RTCDataChannel, events: Events) {
export async function createOffer(file: File, events: Events) {
const pc = createPeerConnection();
const channel = pc.createDataChannel('file');
channel.onopen = async () => {
await connected(pc, 'manual exchange', events, true);
sendFile(channel, file, events);
};
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, 'manual exchange', events));
await pc.setLocalDescription();
await gatherIce(pc);
@@ -203,11 +325,9 @@ export async function createOffer(file: File, events: Events) {
}
export async function answerOffer(offer: string, events: Events) {
await downloadsReady(events);
const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) => {
connected(pc, 'manual exchange', events);
receiveFile(channel, events);
};
pc.ondatachannel = ({ channel }) => receiveFile(pc, channel, events, connected(pc, 'manual exchange', events));
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
await pc.setLocalDescription();
await gatherIce(pc);
@@ -233,10 +353,7 @@ export async function sendViaTracker(file: File, events: Events) {
if (!msg.offer || pc) return;
events.log(`offer via ${url}`);
const peer = (pc = createPeerConnection());
peer.ondatachannel = async ({ channel }) => {
await connected(peer, url, events, true);
sendFile(channel, file, events);
};
peer.ondatachannel = ({ channel }) => sendFile(peer, channel, file, events, connected(peer, url, events));
await peer.setRemoteDescription(msg.offer);
await peer.setLocalDescription();
await gatherIce(peer);
@@ -254,6 +371,7 @@ export async function sendViaTracker(file: File, events: Events) {
// Receiver sends one offer per tracker; the first data channel that opens wins.
export async function receiveViaTracker(code: string, events: Events) {
await downloadsReady(events);
const hash = await infoHash(code);
const peerId = randomBinary(20);
let isConnected = false;
@@ -265,9 +383,8 @@ export async function receiveViaTracker(code: string, events: Events) {
channel.onopen = () => {
if (isConnected) return pc.close();
isConnected = true;
connected(pc, url, events);
receiveFile(pc, channel, events, connected(pc, url, events));
};
receiveFile(channel, events);
pc.setLocalDescription()
.then(() => gatherIce(pc))
@@ -293,7 +410,5 @@ export async function receiveViaTracker(code: string, events: Events) {
}
}
clearStorage();
// Mounted last: App.vue imports the core from this module.
createApp(App).mount('#app');