- Skipped, not a ws: or wss: URL without #: {{ trackers.invalid.join(', ') }} + Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}: + {{ trackers.invalid.join(', ') }}
@@ -589,8 +605,9 @@ document.addEventListener('visibilitychange', holdWakeLock); diff --git a/src/core.test.ts b/src/core.test.ts index 0858868..d1417d3 100644 --- a/src/core.test.ts +++ b/src/core.test.ts @@ -1,7 +1,7 @@ // The core on its own, in Node without browsers: the protocol, the transfer and both kinds of // signaling, on fake connections, tracker sockets and timers in memory. e2e.spec.ts covers what only // browsers can tell: real WebRTC, the service worker and the network. -import { createDecipheriv, createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto'; +import { createDecipheriv, createHash, createHmac, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto'; import { getEventListeners } from 'node:events'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { @@ -30,6 +30,7 @@ import { own, PBKDF2_ITERATIONS, PROOF_TIMEOUT, + PROTOCOL, parse, prove, type ReceiveEvents, @@ -92,7 +93,7 @@ class FakeChannel extends Target { peer?: FakeChannel; // What this side drops instead of sending. drop = (_data: string | ArrayBuffer) => false; - constructor(readonly label = 'file') { + constructor(readonly label = PROTOCOL) { super(); } set onopen(handler: ((event: Any) => unknown) | null) { @@ -476,7 +477,7 @@ describe('codes and salts', () => { it('derives the swarm and the sealing key as the protocol says, the salt in NFC', async () => { const code = 'abcdefghijk'; const salt = '2026-01-01T12:00 Grüße'; - const master = pbkdf2Sync(code, `hellcon ${salt}`, PBKDF2_ITERATIONS, 32, 'sha256'); + const master = pbkdf2Sync(code, `hellcon/1 ${salt}`, PBKDF2_ITERATIONS, 32, 'sha256'); const expand = (info: string, length: number) => Buffer.from(hkdfSync('sha256', master, '', info, length)); const { hash, sealing } = await secrets(code, salt.normalize('NFD')); expect(Buffer.from(hash, 'latin1')).toEqual(expand('swarm', 20)); @@ -725,6 +726,23 @@ describe('tracker socket', () => { expect(session.logs).toEqual(['wss://one.test unreachable']); }); + it('takes a tracker the browser refuses to open for lost, once the caller has it', async () => { + vi.stubGlobal( + 'WebSocket', + class { + constructor() { + throw new DOMException('insecure', 'SecurityError'); + } + }, + ); + const { session, tracker, lost } = socket('ws://one.test'); + expect(lost).not.toHaveBeenCalled(); + await settle(); + expect(lost).toHaveBeenCalledTimes(1); + expect(session.logs).toEqual(['ws://one.test refused: insecure']); + expect(tracker.alive()).toBe(false); + }); + it('gives up on a tracker that never answers', async () => { new FakeTracker('wss://one.test', () => undefined); const { session, tracker, lost } = socket(); @@ -757,10 +775,13 @@ describe('tracker socket', () => { ws.deliver({ 'not json': undefined }); ws.deliver({ 'failure reason': 'slow down' }); ws.deliver({ 'failure reason': 'shutting down' }); + // Controls and bidi controls would fake log lines. + ws.deliver({ 'failure reason': 'bye\nsecurity check passed\u202E' }); expect(accepted.session.logs).toEqual([ `wss://two.test: ${'x'.repeat(200)}`, 'wss://two.test: slow down', 'wss://two.test: shutting down', + 'wss://two.test: byesecurity check passed', ]); expect(accepted.tracker.alive()).toBe(true); expect(accepted.lost).not.toHaveBeenCalled(); @@ -877,6 +898,24 @@ describe('proof of the code', () => { return [a, b] as const; } + // The protocol in node:crypto, like the derivation in codes and salts: changing it splits old and new clients. + it('proves with the key secrets derives, over the fingerprints as the protocol says', async () => { + const master = pbkdf2Sync('abcdefghijk', 'hellcon/1 salt', PBKDF2_ITERATIONS, 32, 'sha256'); + const proofKey = Buffer.from(hkdfSync('sha256', master, '', 'proof', 64)); + const hmac = (statement: unknown) => + createHmac('sha256', proofKey).update(JSON.stringify(statement)).digest('base64'); + const { key } = await secrets('abcdefghijk', 'salt'); + const channel = new FakeChannel(); + channel.readyState = 'open'; + const end = vi.fn(); + const proven = prove(view('offer', 'AA', 'BB'), asChannel(channel), key, end); + await until(() => channel.sent.length); + expect(channel.sent).toEqual([JSON.stringify({ proof: hmac(['offer', ['sha-256 aa'], ['sha-256 bb']]) })]); + channel.emit('message', { data: JSON.stringify({ proof: hmac(['answer', ['sha-256 bb'], ['sha-256 aa']]) }) }); + await proven; + expect(end).not.toHaveBeenCalled(); + }); + it('passes on both sides with the same key and the same certificates', async () => { const shared = await key(); const [a, b] = pair(); @@ -1038,7 +1077,7 @@ describe('sending', () => { stopped.channel.receive({ ok: true }); await until(() => stopped.channel.sent.length); stopped.channel.receive({ start: true }); - stopped.channel.receive({ error: `cancelled ${'x'.repeat(300)}` }); + stopped.channel.receive({ error: `cancelled\n\u202E ${'x'.repeat(300)}` }); expect(stopped.session.errors).toEqual([`receiver stopped: cancelled ${'x'.repeat(190)}`]); expect(stopped.pc.signalingState).toBe('closed'); @@ -1060,6 +1099,17 @@ describe('sending', () => { unreadable.channel.receive({ start: true }); await unreadable.done; expect(unreadable.session.errors).toEqual(['could not read gone.bin anymore']); + + // Read short instead of failing. + const shrunk = { name: 'shrunk.bin', size: 10, slice: () => ({ arrayBuffer: async () => new ArrayBuffer(5) }) }; + const short = sending(shrunk as unknown as File); + short.check(); + short.channel.receive({ ok: true }); + await until(() => short.channel.sent.length); + short.channel.receive({ start: true }); + await short.done; + expect(short.session.errors).toEqual(['could not read shrunk.bin anymore']); + expect(short.channel.bytes()).toBe(0); }); it('stops quietly when the connection closes before the transfer or the session ends', async () => { @@ -1228,6 +1278,14 @@ describe('receiving', () => { }); }); +// Data channels opened from here on carry another protocol's label. +function otherProtocol() { + const create = FakePeer.prototype.createDataChannel; + return vi.spyOn(FakePeer.prototype, 'createDataChannel').mockImplementation(function (this: FakePeer, label: string) { + return create.call(this, label === PROTOCOL ? 'other/1' : label); + }); +} + describe('manual exchange', () => { // Sender and receiver connected by the manual codes, both shown the check. async function exchange(source: File) { @@ -1299,6 +1357,20 @@ describe('manual exchange', () => { await until(() => sender.checks[0]); }); + it('refuses a sender on another protocol', async () => { + const [sender, receiver] = [side(), side()]; + otherProtocol(); + const { offer, accept } = await createOffer(file(10), sender.events, sender.signal); + await accept(await answerOffer(offer, receiver.events, receiver.signal)); + await until(() => sender.errors.length); + expect(receiver.errors).toEqual([`the sender runs another protocol, both pages have to show protocol ${PROTOCOL}`]); + expect(receiver.logged('the sender\'s protocol: "other/1"')).toBe(true); + expect(receiver.checks).toEqual([]); + expect(sender.errors).toEqual(['the receiver left before the transfer']); + expect(sender.checks.at(-1)).toBeUndefined(); + expect(openPeers()).toEqual([]); + }); + it('tells why it could not connect, on each side once its time is up', async () => { FakePeer.reachable = false; const [sender, receiver] = [side(), side()]; @@ -1366,6 +1438,78 @@ describe('tracker signaling', () => { expect(sender.errors).toEqual([]); }); + it('shares on after a receiver on another protocol, with the next receiver', async () => { + new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const [sender, other, receiver] = [side(), side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + const labels = otherProtocol(); + await receiveViaTracker(code, other.events, other.signal); + await until(() => sender.logged(`receiver via ${URLS[0]} runs another protocol`)); + await until(() => sender.logged('waiting for the next receiver')); + expect(sender.logged('connected via')).toBe(false); + other.stop(); + labels.mockRestore(); + + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => receiver.files[0]); + expect(sender.errors).toEqual([]); + }); + + it('walks on past a tracker the browser refuses to open, on both sides', async () => { + new FakeTracker(URLS[0]!); + settings.trackers = ['ws://refused.test', URLS[0]!]; + vi.stubGlobal( + 'WebSocket', + class extends FakeSocket { + constructor(url: string) { + if (url.startsWith('ws:')) throw new DOMException('insecure', 'SecurityError'); + super(url); + } + }, + ); + const [sender, receiver] = [side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, receiver.events, receiver.signal); + await until(() => receiver.files[0]); + for (const peer of [sender, receiver]) expect(peer.logged('ws://refused.test refused: insecure')).toBe(true); + expect([...sender.errors, ...receiver.errors]).toEqual([]); + }); + + it('answers no offer that waited for its turn on a tracker lost meanwhile', async () => { + for (const url of URLS.slice(0, 2)) new FakeTracker(url); + settings.trackers = URLS.slice(0, 2); + const [sender, silent, waiting] = [side(), side(), side()]; + const { code } = await sendViaTracker(file(10), sender.events, sender.signal); + await receiveViaTracker(code, silent.events, silent.signal); + await until(() => FakePeer.all[0]?.channels.length); + FakePeer.all[0]!.channels[0]!.drop = (data) => typeof data === 'string' && data.includes('"proof"'); + await until(() => sender.logged('waiting for the security check')); + await receiveViaTracker(code, waiting.events, waiting.signal); + await until(() => waiting.logged(`looking on ${URLS[0]}`)); + await settle(); + // The sender's socket, the first one made. + FakeSocket.all[0]!.drop(); + await until(() => sender.logged(`waiting on ${URLS[1]}`)); + // Answered, so it doesn't time out below. + await settle(); + vi.advanceTimersByTime(PROOF_TIMEOUT); + await until(() => sender.logged('waiting for the next receiver')); + await settle(); + expect(sender.count('offer via')).toBe(1); + expect(sender.errors).toEqual([]); + }); + + it('opens no tracker for a share that ended while its key was derived', async () => { + new FakeTracker(URLS[0]!); + settings.trackers = [URLS[0]!]; + const sender = side(); + const shared = sendViaTracker(file(10), sender.events, sender.signal); + sender.stop(); + await shared; + expect(FakeSocket.all).toEqual([]); + }); + it('stays on the first tracker that accepts the share, the next only once that one is lost', async () => { new FakeTracker(URLS[0]!, () => ({ 'failure reason': 'not here' })); const second = new FakeTracker(URLS[1]!); @@ -1428,7 +1572,9 @@ describe('tracker signaling', () => { trackers.get(URLS[1]!)!.sockets[0]!.deliver({ action: 'announce', interval: 120, complete: 0 }); await until(() => receiver.logged(`looking on ${URLS[2]}`)); await until(() => receiver.status()?.startsWith('retry: No sender')); - expect(receiver.status()).toBe('retry: No sender with this code on any tracker. Check the code, still looking'); + expect(receiver.status()).toBe( + 'retry: No sender with this code on any tracker. Check the code and that both pages show protocol hellcon/1, still looking', + ); expect(openSockets()).toHaveLength(3); // It showed up again, busy with another receiver maybe. trackers.get(URLS[2]!)!.sockets[0]!.deliver({ action: 'announce', interval: 120, complete: 1 }); @@ -1468,7 +1614,7 @@ describe('tracker signaling', () => { await receiveViaTracker(code, other.events, other.signal, 'Grüße!'); await until(() => other.status()?.startsWith('retry: No sender')); expect(other.status()).toBe( - 'retry: No sender with this code on any tracker. Check the code and the salt, still looking', + 'retry: No sender with this code on any tracker. Check the code and the salt and that both pages show protocol hellcon/1, still looking', ); await receiveViaTracker(code, receiver.events, receiver.signal, 'Grüße'); await until(() => receiver.files[0]); @@ -1550,7 +1696,9 @@ describe('tracker signaling', () => { vi.advanceTimersByTime(TRACKER_WAIT - MIN_INTERVAL); expect(sender.errors[0]).toMatch(/^nobody received the file until .+, share it again$/); expect(sender.expired).toBe(true); - expect(receiver.errors[0]).toMatch(/^no sender answered until .+, ask the sender for a new code$/); + expect(receiver.errors[0]).toMatch( + /^no sender answered until .+, check that both pages show protocol hellcon\/1 or ask the sender for a new code$/, + ); await settle(); expect(openSockets()).toEqual([]); expect(openPeers()).toEqual([]); diff --git a/src/core.ts b/src/core.ts index d5e1317..dbe9cd0 100644 --- a/src/core.ts +++ b/src/core.ts @@ -13,8 +13,8 @@ export const DEFAULT_STUN_SERVERS = [ 'stun:stun.nextcloud.com:443', ]; -// App.vue uses the settings and their defaults, randomCode, formatTime, the types and the sessions -// at the end. src/core.test.ts also tests the other exports on their own, biome.json keeps them to it: +// App.vue uses the settings and their defaults, PROTOCOL, randomCode, formatTime, the types and the +// sessions at the end. src/core.test.ts also tests the other exports on their own, biome.json keeps them to it: // a new one goes on its list there. // Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody. @@ -28,7 +28,8 @@ export const settings = { export const CHUNK_SIZE = 16 * 1024; export 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. +// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM. The +// receiver holds the sender to it and CHUNK_SIZE, raising either takes a new PROTOCOL. export const WINDOW = 8 * 1024 * 1024; const ICE_GRACE = 300; const ICE_TIMEOUT = 5000; @@ -55,8 +56,16 @@ export const CONNECT_TIMEOUT = 30_000; // The manual receiver waits this long for the sender to connect, it has to get the answer first. export const TRACKER_WAIT = 6 * 60_000; export const MIN_INTERVAL = 30_000; -// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms. +// OWASP's recommendation for PBKDF2-SHA-256. Changing it takes a new PROTOCOL. export const PBKDF2_ITERATIONS = 600_000; +// Goes into the key derivation, see secrets: sides on different versions end up in different swarms +// and never meet, the receiver only finds no sender. The manual exchange has no derivation, the data +// channel's label carries it there and the side it reaches checks it. The page shows it, so the two +// can compare. Every change that breaks sharing between versions takes a new one: the code and its +// salt, the derivation, the signaling, the data channel's messages and its flow control. A fork that +// changes any of them takes a name of its own, two forks would otherwise share a version that means +// different things. +export const PROTOCOL = 'hellcon/1'; // A tracker peer that connects but proves no code gives up its turn after this. Signing takes // milliseconds, a peer that knows the code is never near it. export const PROOF_TIMEOUT = 10_000; @@ -304,7 +313,7 @@ export const formatTime = (time: number) => // so the same one comes back every ~6 hours. The receiver takes the window with that character nearest // its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts // TRACKER_WAIT from the click whenever in its window that was. -// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms. +// Its own constant, not TRACKER_WAIT: changing it takes a new PROTOCOL. export const SALT_WINDOW = 6 * 60_000; export const CODE_LENGTH = 11; const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW); @@ -343,7 +352,9 @@ export function codeSalt(code: string, own?: string) { // clock's salt limits a table to the shares of one window, for 62¹⁰ codes it takes over a million GPU // years. An own salt nobody can predict leaves guessing while the share lasts. NFC, an ü typed on one // system can be other bytes than on the next. HKDF splits the result, the public info_hash tells -// nothing about the keys: one seals the signaling, see seal, one proves the connection. +// nothing about the keys: one seals the signaling, see seal, one proves the connection. The PROTOCOL +// goes in front of the salt, each version gets swarms and keys of its own. The proof's HMAC key takes +// the hash's block size without a length given, 64 bytes. export async function secrets(code: string, salt: string) { const text = new TextEncoder(); const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']); @@ -351,7 +362,7 @@ export async function secrets(code: string, salt: string) { { name: 'PBKDF2', hash: 'SHA-256', - salt: text.encode(`hellcon ${salt.normalize('NFC')}`), + salt: text.encode(`${PROTOCOL} ${salt.normalize('NFC')}`), iterations: PBKDF2_ITERATIONS, }, password, @@ -624,7 +635,7 @@ export async function sendFile( events.progress(file.size, file.size); stop(); } else if (typeof message?.error === 'string') { - stop(`receiver stopped: ${message.error.slice(0, 200)}`); + stop(`receiver stopped: ${message.error.replace(HIDDEN, '').slice(0, 200)}`); } wake(); }; @@ -672,7 +683,9 @@ export async function sendFile( .slice(offset, offset + CHUNK_SIZE) .arrayBuffer() .catch(() => undefined); - if (!chunk) return stop(`could not read ${file.name} anymore`); + // A browser may read a file that shrank meanwhile short instead of failing. + if (chunk?.byteLength !== Math.min(CHUNK_SIZE, file.size - offset)) + return stop(`could not read ${file.name} anymore`); if (!open()) return; channel.send(chunk); } @@ -842,7 +855,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna events = live(events, signal); events.status('start', 'Creating the offer'); const pc = await createPeerConnection(signal); - const channel = pc.createDataChannel('file'); + const channel = pc.createDataChannel(PROTOCOL); channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', 'receiver', events), signal); const wait = failUnconnected(pc, () => channel.readyState !== 'connecting', events, signal, 'receiver'); @@ -878,6 +891,11 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal: // The sender's file channel, anything more is none of ours. if (opened) return; opened = true; + if (channel.label !== PROTOCOL) { + events.log(`the sender's protocol: ${JSON.stringify(channel.label.replace(HIDDEN, '').slice(0, 100))}`); + pc.close(); + return events.error(`the sender runs another protocol, both pages have to show protocol ${PROTOCOL}`); + } receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', 'sender', events), signal); }; const wait = failUnconnected(pc, () => opened, events, signal, 'sender'); @@ -908,7 +926,15 @@ export function trackerSocket( lost: () => void, again: () => void, ) { - const ws = new WebSocket(url); + let ws: WebSocket; + try { + ws = new WebSocket(url); + } catch (error) { + // Chromium refuses e.g. ws: on an https page right away, Firefox only closes the socket. Lost all + // the same, once the caller has it. + ws = Object.assign(new EventTarget(), { close: () => {} }) as unknown as WebSocket; + queueMicrotask(() => end(`${url} refused: ${error instanceof Error ? error.message : error}`)); + } let opened = false; let accepted = false; let closed = false; @@ -968,7 +994,7 @@ export function trackerSocket( } return void message(msg); } - reject(`${url}: ${failure.slice(0, 200)}`); + reject(`${url}: ${failure.replace(HIDDEN, '').slice(0, 200)}`); }); // A problem with the tracker's message: the end before acceptance, after it only that message's. const reject = (reason: string) => { @@ -1090,6 +1116,8 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo const timeout = setTimeout(unconnected, CONNECT_TIMEOUT); pc.ondatachannel = ({ channel }) => { if (settled) return; + // Only a fork that kept the name derives these keys. + if (channel.label !== PROTOCOL) return giveUp(`receiver via ${url} runs another protocol`); settled = true; clearTimeout(timeout); const handshake = connected(pc, channel, url, 'receiver', events, next, key); @@ -1141,7 +1169,11 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo if (signal.aborted || !tracker.alive()) return; if (sdp === undefined) return tracker.note(`offer without the code via ${url}`); const offer = { offer: { sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id }; - if (busy) waiting = () => answer(tracker.ws, url, offer); + // A lost tracker would take no answer, a receiver that came by it looks on the next one. + if (busy) + waiting = async () => { + if (tracker.alive()) await answer(tracker.ws, url, offer); + }; else void answer(tracker.ws, url, offer); }, () => { @@ -1159,7 +1191,8 @@ export async function sendViaTracker(file: File, events: SendEvents, signal: Abo trackers.push(tracker); } - join(0); + // Ended while the key was derived. + if (!signal.aborted) join(0); return { code, until }; } @@ -1208,7 +1241,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig const nobody = () => hint ? `no sender connected until ${formatTime(until)}: ${hint}` - : `no sender answered until ${formatTime(until)}, ${ownSalt === undefined ? '' : 'check that both of you use the same salt or '}ask the sender for a new code`; + : `no sender answered until ${formatTime(until)}, check that both pages show protocol ${PROTOCOL}${ownSalt === undefined ? '' : ' and you use the same salt'} or ask the sender for a new code`; // Without a sender connected the search is over, every offer goes. const end = (reason: string) => { expiry.close(); @@ -1253,7 +1286,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig entry.pc = pc; // Meanwhile the download may have started or the search ended. if (signal.aborted || started || expired) return pc.close(); - const channel = pc.createDataChannel('file'); + const channel = pc.createDataChannel(PROTOCOL); const offerId = randomBinary(20); let timeout: ReturnType