From 08b9f659c21e5e23c4e24ffce4196ef5e488b5a0 Mon Sep 17 00:00:00 2001 From: Schluffe Date: Fri, 23 Oct 2026 01:01:45 +0200 Subject: [PATCH] Lengthen codes and keep going after a failed security check The security check compares 8 instead of 5 fingerprint bytes, too many to brute force matching certificates. The tracker code has 8 digits, making collisions between concurrent senders 100x less likely. A "Codes don't match" button, or a peer leaving before the transfer starts, ends that connection without ending the share: the tracker sender answers the next (or a queued) offer, the receiver replaces its used up offers. Both codes are aligned below each other. Co-Authored-By: Claude Opus 5.5 --- e2e.spec.ts | 59 +++++++++++++++++- src/App.vue | 27 +++++--- src/main.ts | 166 +++++++++++++++++++++++++++++++++++++------------- src/style.css | 30 ++++++++- 4 files changed, 228 insertions(+), 54 deletions(-) diff --git a/e2e.spec.ts b/e2e.spec.ts index d31890d..fbe1fbe 100644 --- a/e2e.spec.ts +++ b/e2e.spec.ts @@ -46,7 +46,7 @@ const MODES: Record Promise> = { }, async tracker(sender, receiver) { await sender.click('#share'); - await expect(sender.locator('#send-code')).toHaveText(/^\d{6}$/); + await expect(sender.locator('#send-code')).toHaveText(/^\d{8}$/); await expect(sender.locator('#log')).toContainText('waiting on'); await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!); await receiver.click('#receive'); @@ -190,7 +190,7 @@ async function connect(mode: string, sender: Page, receiver: Page, source: strin await MODES[mode]!(sender, receiver); const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent(); - await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){4}[0-9A-F]{2}$/, { + await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){7}[0-9A-F]{2}$/, { timeout: 45_000, }); await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!); @@ -357,6 +357,61 @@ for (const name of Object.keys(BROWSERS)) { }); }); + // A peer that guessed the code, or got the same one by chance, takes the sender's turn first. + test(`check: ${name} sender shares on after a mismatch`, async () => { + const [sender, intruder, receiver] = await Promise.all([open(name, []), open(name, []), open(name, [])]); + const source = test.info().outputPath('payload.bin'); + await writeFile(source, randomBytes(SIZE)); + + await withLogs(sender!, receiver!, async () => { + await connect('tracker', sender!, intruder!, source); + await receiver!.fill('#receive-code', (await sender!.locator('#send-code').textContent())!); + await receiver!.click('#receive'); + await expect(receiver!.locator('#log')).toContainText('looking on'); + await sender!.click('#reject'); + await intruder!.context().close(); + await expect(sender!.locator('#log')).toContainText('waiting for the next receiver'); + + await expect(receiver!.locator('#check-local')).toBeVisible({ timeout: 45_000 }); + await expect(sender!.locator('#check-local')).toHaveText((await receiver!.locator('#check-remote').textContent())!); + await expect(sender!.locator('#check-remote')).toHaveText((await receiver!.locator('#check-local').textContent())!); + const started = downloadStarts(receiver!); + await sender!.click('#confirm'); + await receiver!.click('#confirm'); + const { download } = await started; + expect(await hash(await download.path())).toBe(await hash(source)); + await expect(sender!.locator('#log')).toContainText('delivered'); + }); + }); + + test(`check: ${name} both sides go on after the receiver rejected`, async () => { + const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]); + const source = test.info().outputPath('payload.bin'); + await writeFile(source, randomBytes(SIZE)); + + await withLogs(sender!, receiver!, async () => { + await connect('tracker', sender!, receiver!, source); + const first = await receiver!.locator('#check-local').textContent(); + // Retrying still has to work for a side that already confirmed. + await sender!.click('#confirm'); + await receiver!.click('#reject'); + await expect(receiver!.locator('#log')).toContainText('looking again'); + // The sender notices the receiver left, Chromium only once the connection counts as failed. + await expect(sender!.locator('#log')).toContainText('waiting for the next receiver', { timeout: 30_000 }); + + await expect(receiver!.locator('#check-local')).toHaveText(new RegExp(`^(?!${first}$)([0-9A-F]{2} ){7}[0-9A-F]{2}$`), { + timeout: 45_000, + }); + await expect(sender!.locator('#check-remote')).toHaveText((await receiver!.locator('#check-local').textContent())!); + const started = downloadStarts(receiver!); + await sender!.click('#confirm'); + await receiver!.click('#confirm'); + const { download } = await started; + expect(await hash(await download.path())).toBe(await hash(source)); + await expect(sender!.locator('#log')).toContainText('delivered'); + }); + }); + 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/src/App.vue b/src/App.vue index fc0d2de..41f3c80 100644 --- a/src/App.vue +++ b/src/App.vue @@ -23,20 +23,20 @@ const answer = ref(''); const receiveCode = ref(''); const check = ref(); -const confirmCheck = ref<() => void>(); +const confirmed = ref(false); const log = ref([]); const events: Events = { log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`), - check: (result, confirm) => { + check: (result) => { check.value = result; - confirmCheck.value = confirm; + confirmed.value = false; }, }; function onConfirm() { - confirmCheck.value?.(); - confirmCheck.value = undefined; + confirmed.value = true; + check.value?.confirm(); } let acceptAnswer: ((answer: string) => Promise) | undefined; @@ -98,10 +98,19 @@ function onReceive() {
@@ -153,7 +162,7 @@ function onReceive() {
-

Tracker optional

+

Tracker

diff --git a/src/main.ts b/src/main.ts index 8f21bae..0a196dc 100644 --- a/src/main.ts +++ b/src/main.ts @@ -25,12 +25,18 @@ const KEEPALIVE = 10_000; const ICE_GRACE = 300; const ICE_TIMEOUT = 5000; -export type Check = { local: string; remote: string }; +export type Check = { + local: string; + remote: string; + // Once the user compared the codes: confirm if they match, else reject. + confirm: () => void; + reject: () => void; +}; export type Events = { log: (message: string) => void; - // Called on both sides, confirm once the user compared the codes and they match. - check: (check: Check, confirm: () => void) => void; + // Called on both sides once connected, and without a check when it ended undecided. + check: (check?: Check) => void; }; function createPeerConnection() { @@ -42,7 +48,7 @@ function randomBinary(length: number) { } function randomCode() { - return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, '0'); + return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 100_000_000).padStart(8, '0'); } // The tracker swarm is identified by a 20 byte info_hash, derived from the shared code. @@ -85,20 +91,50 @@ async function gatherIce(pc: RTCPeerConnection) { }); } -// Anti-MITM check: the first 5 bytes of both DTLS certificate fingerprints. My local code must -// equal the peer's remote code and vice versa, otherwise someone interposed on the signaling. -function securityCheck(pc: RTCPeerConnection): Check { +// Anti-MITM check: the first 8 bytes of both DTLS certificate fingerprints, fewer an interposer can +// brute force with matching certificates. My local code must equal the peer's remote code and vice +// versa, otherwise someone interposed on the signaling. +function securityCheck(pc: RTCPeerConnection) { const short = (sdp = '') => - sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 5).join(' ') ?? '?'; + sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 8).join(' ') ?? '?'; return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) }; } -// 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) { +// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing +// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which +// needs both confirmations, a rejected check or a peer that left closes the connection and calls next: +// tracker signaling goes on with another peer. From start on, sendFile and receiveFile handle a loss. +type Handshake = { checked: Promise; start: () => void }; + +function connected( + pc: RTCPeerConnection, + channel: RTCDataChannel, + via: string, + events: Events, + next = () => {}, +): Handshake { events.log(`connected via ${via}`); events.log('waiting for the security check'); - return new Promise((resolve) => events.check(securityCheck(pc), resolve)); + let done = false; + const end = (reason: string) => { + if (done) return; + done = true; + events.log(reason); + events.check(); + pc.close(); + next(); + }; + // A vanished peer only closes the channel in Firefox, Chromium just fails the connection. + channel.addEventListener('close', () => end('peer left before the transfer')); + pc.addEventListener('connectionstatechange', () => { + if (pc.connectionState === 'failed') end('peer left before the transfer'); + }); + return { + checked: new Promise((resolve) => + events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }), + ), + start: () => (done = true), + }; } // Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers @@ -109,7 +145,7 @@ async function sendFile( channel: RTCDataChannel, file: File, events: Events, - checked: Promise, + handshake: Handshake, ) { if (channel.readyState !== 'open') { await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true })); @@ -120,10 +156,10 @@ async function sendFile( let stopped = false; // Every event the send loop can wait for calls this. let wake = () => {}; - const stop = (message: string) => { + const stop = (message?: string) => { if (stopped) return; stopped = true; - events.log(message); + if (message) events.log(message); wake(); }; channel.onmessage = ({ data }) => { @@ -140,17 +176,20 @@ async function sendFile( 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')); + // A vanished peer only closes the channel in Firefox, Chromium just fails the connection. Before + // sending, connected reports it. + const lost = () => stop(sending ? 'connection lost' : undefined); + channel.addEventListener('close', lost); + pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost()); channel.addEventListener('bufferedamountlow', () => wake()); - await checked; + await handshake.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; + handshake.start(); events.log(`sending ${file.name} (${file.size} bytes)`); channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2; channel.send(JSON.stringify({ name: file.name, size: file.size })); @@ -208,7 +247,7 @@ async function holdWorker() { } // Accepts nothing until checked resolved, then tells the sender with { ok }. -function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, checked: Promise) { +function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, handshake: Handshake) { const id = crypto.randomUUID(); const frames: HTMLIFrameElement[] = []; let meta: { name: string; size: number } | undefined; @@ -278,7 +317,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve }, (error) => fail(String(error))); } - checked.then(() => { + handshake.checked.then(() => { confirmed = true; reply({ ok: true }); events.log('waiting for the sender'); @@ -289,6 +328,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve if (ended || !confirmed) return; if (typeof data === 'string') { meta = JSON.parse(data); + handshake.start(); events.log(`receiving ${meta!.name} (${meta!.size} bytes)`); startDownload(); } else { @@ -314,7 +354,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 = () => sendFile(pc, channel, file, events, connected(pc, 'manual exchange', events)); + channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events)); await pc.setLocalDescription(); await gatherIce(pc); @@ -327,7 +367,8 @@ 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 }) => receiveFile(pc, channel, events, connected(pc, 'manual exchange', events)); + pc.ondatachannel = ({ channel }) => + receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events)); await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) }); await pc.setLocalDescription(); await gatherIce(pc); @@ -335,12 +376,49 @@ export async function answerOffer(offer: string, events: Events) { return btoa(pc.localDescription!.sdp); } -// Tracker signaling (optional): sender joins the swarm on every tracker and answers the first offer. +// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a +// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed +// the code, or got the same one by chance, doesn't end the share. export async function sendViaTracker(file: File, events: Events) { const code = randomCode(); const hash = await infoHash(code); const peerId = randomBinary(20); - let pc: RTCPeerConnection | undefined; + let busy = false; + // The latest offer that came while busy, answered once that peer is out. + let waiting: (() => void) | undefined; + + async function answer(ws: WebSocket, url: string, msg: { offer: RTCSessionDescriptionInit; peer_id: string; offer_id: string }) { + busy = true; + events.log(`offer via ${url}`); + const pc = createPeerConnection(); + const next = () => { + busy = false; + events.log('waiting for the next receiver'); + const offer = waiting; + waiting = undefined; + offer?.(); + }; + let checking = false; + pc.ondatachannel = ({ channel }) => { + checking = true; + sendFile(pc, channel, file, events, connected(pc, channel, url, events, next)); + }; + // An offer whose receiver is gone never gets to the check. + pc.addEventListener('connectionstatechange', () => { + if (pc.connectionState !== 'failed' || checking) return; + pc.close(); + next(); + }); + await pc.setRemoteDescription(msg.offer); + await pc.setLocalDescription(); + await gatherIce(pc); + announce(ws, hash, peerId, { + left: 0, + to_peer_id: msg.peer_id, + offer_id: msg.offer_id, + answer: pc.localDescription, + }); + } for (const url of TRACKERS) { const ws = new WebSocket(url); @@ -348,42 +426,42 @@ export async function sendViaTracker(file: File, events: Events) { announce(ws, hash, peerId, { left: 0, event: 'started' }); events.log(`waiting on ${url}`); }; - ws.onmessage = async (event) => { + ws.onmessage = (event) => { const msg = JSON.parse(event.data); - if (!msg.offer || pc) return; - events.log(`offer via ${url}`); - const peer = (pc = createPeerConnection()); - peer.ondatachannel = ({ channel }) => sendFile(peer, channel, file, events, connected(peer, url, events)); - await peer.setRemoteDescription(msg.offer); - await peer.setLocalDescription(); - await gatherIce(peer); - announce(ws, hash, peerId, { - left: 0, - to_peer_id: msg.peer_id, - offer_id: msg.offer_id, - answer: peer.localDescription, - }); + if (!msg.offer) return; + if (busy) waiting = () => answer(ws, url, msg); + else answer(ws, url, msg); }; } return code; } -// Receiver sends one offer per tracker; the first data channel that opens wins. +// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails +// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have +// queued one of them. export async function receiveViaTracker(code: string, events: Events) { await downloadsReady(events); const hash = await infoHash(code); const peerId = randomBinary(20); + const offers = new Map(); let isConnected = false; - for (const url of TRACKERS) { + const next = () => { + isConnected = false; + events.log('looking again'); + for (const [url, pc] of offers) if (pc.signalingState === 'closed') offer(url); + }; + + function offer(url: string) { const pc = createPeerConnection(); + offers.set(url, pc); const channel = pc.createDataChannel('file'); const offerId = randomBinary(20); channel.onopen = () => { if (isConnected) return pc.close(); isConnected = true; - receiveFile(pc, channel, events, connected(pc, url, events)); + receiveFile(pc, channel, events, connected(pc, channel, url, events, next)); }; pc.setLocalDescription() @@ -404,10 +482,14 @@ export async function receiveViaTracker(code: string, events: Events) { if (msg.answer && msg.offer_id === offerId) { events.log(`answer via ${url}`); pc.setRemoteDescription(msg.answer); + // Only one answer per offer, a replacement opens its own connection. + ws.close(); } }; }); } + + for (const url of TRACKERS) offer(url); } // Mounted last: App.vue imports the core from this module. diff --git a/src/style.css b/src/style.css index f513a4b..d18f27d 100644 --- a/src/style.css +++ b/src/style.css @@ -331,7 +331,35 @@ label:has([role='switch']) { } [role='alert'] p { - flex: 1 1 20rem; + flex: 1 1 100%; +} + +/* Monospaced in a grid, so both codes line up byte by byte */ +[role='alert'] dl { + flex: 1 1 auto; + display: grid; + grid-template-columns: auto auto; + justify-content: start; + column-gap: var(--space-3); +} + +[role='alert'] dt { + color: var(--color-text-muted); +} + +[role='alert'] div { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +[role='alert'] button + button { + background: transparent; + border-color: var(--color-border); +} + +[role='alert'] button + button:hover { + background: var(--color-border); } output {