diff --git a/e2e.spec.ts b/e2e.spec.ts index a7a0be5..d31890d 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -136,6 +136,19 @@ function holdReads() { }; } +// 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()); @@ -171,9 +184,8 @@ async function withLogs(sender: Page, receiver: Page, fn: () => Promise) { } } -// Connects, verifies the security check and confirms it. Returns the download, which starts on its -// own as soon as the file is announced, and the receiver log at that moment. -async function start(mode: string, sender: Page, receiver: Page, source: string) { +// 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); @@ -183,13 +195,26 @@ async function start(mode: string, sender: Page, receiver: Page, source: string) }); 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'); + } +} - const started = receiver +// 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(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; } @@ -299,6 +324,39 @@ for (const name of Object.keys(BROWSERS)) { }); }); + 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'); diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..2edeeba --- /dev/null +++ b/public/sw.js @@ -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('', { 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 })); +}); diff --git a/src/App.vue b/src/App.vue index 65e181e..99e0d9d 100644 --- a/src/App.vue +++ b/src/App.vue @@ -23,20 +23,20 @@ const answer = ref(''); const receiveCode = ref(''); const check = ref(); -const confirmSend = ref<() => void>(); +const confirmCheck = ref<() => void>(); const log = ref([]); const events: Events = { log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`), 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) | undefined; @@ -110,8 +110,8 @@ function onReceive() {

Security check, you: {{ check.local }}, peer: - {{ check.remote }}. The other side must show the same two codes swapped. - + {{ check.remote }}. The other side must show the same two codes swapped. Both sides confirm, nothing is transferred before. +

Log

diff --git a/src/main.ts b/src/main.ts index 247a148..8f21bae 100644 --- a/src/main.ts +++ b/src/main.ts @@ -29,8 +29,8 @@ export type Check = { local: string; remote: string }; export type Events = { log: (message: 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() { @@ -93,20 +93,30 @@ 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((resolve) => events.check(securityCheck(pc), confirm ? resolve : undefined)); + events.log('waiting for the security check'); + return new Promise((resolve) => events.check(securityCheck(pc), resolve)); } -// The receiver 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) { +// 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, +) { 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 = () => {}; @@ -118,6 +128,9 @@ async function sendFile(pc: RTCPeerConnection, channel: RTCDataChannel, file: Fi }; 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'); @@ -132,6 +145,12 @@ async function sendFile(pc: RTCPeerConnection, channel: RTCDataChannel, file: Fi 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((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 })); @@ -188,11 +207,13 @@ async function holdWorker() { return { frame, worker }; } -function receiveFile(pc: RTCPeerConnection, 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) { const id = crypto.randomUUID(); const frames: HTMLIFrameElement[] = []; let meta: { name: string; size: number } | 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 = Promise.resolve(); @@ -257,9 +278,15 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve }, (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) return; + if (ended || !confirmed) return; if (typeof data === 'string') { meta = JSON.parse(data); events.log(`receiving ${meta!.name} (${meta!.size} bytes)`); @@ -287,10 +314,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve 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(pc, channel, file, events); - }; + channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, 'manual exchange', events)); await pc.setLocalDescription(); await gatherIce(pc); @@ -303,10 +327,7 @@ 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(pc, 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); @@ -332,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(peer, 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); @@ -365,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(pc, channel, events); pc.setLocalDescription() .then(() => gatherIce(pc))