// 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 { getEventListeners } from 'node:events'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { answerOffer, CHUNK_SIZE, type Check, CODE_CHARS, CODE_LENGTH, CONNECT_TIMEOUT, codeSalt, createOffer, DEFAULT_STUN_SERVERS, deadline, decode, fingerprints, type Incoming, live, MAX_BUFFERED, MAX_NAME, MAX_TRACKER_MESSAGE, MAX_TRACKER_MESSAGES, MESSAGE_WINDOW, MIN_INTERVAL, newCode, noTracker, own, PBKDF2_ITERATIONS, PROOF_TIMEOUT, parse, prove, type ReceiveEvents, randomCode, receiveFile, receiveViaTracker, SALT_WINDOW, type SendEvents, seal, secrets, securityCheck, sendFile, sendViaTracker, settings, stunChoice, stunHint, TRACKER_NOTES, TRACKER_TIMEOUT, TRACKER_WAIT, trackerSalt, trackerSocket, unseal, WINDOW, } from './core'; import type { Download, DownloadEvents } from './download'; // The receiver saves into memory instead of the service worker, see saveInMemory. vi.mock('./download', () => ({ downloadsReady: async () => {}, startDownload: (file: { name: string; size: number }, events: DownloadEvents) => saveInMemory(file, events), })); // A second into the window from 12:00 to 12:06 UTC, so every code made now has the same salt. const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1); // biome-ignore lint/suspicious/noExplicitAny: messages and handlers of the fakes, the tests read what they need type Any = any; // The browser's on properties: a handler listens in the place where it was first set. class Target extends EventTarget { #handlers = new Map unknown) | null>(); protected on(type: string, handler: ((event: Any) => unknown) | null) { if (!this.#handlers.has(type)) this.addEventListener(type, (event) => this.#handlers.get(type)?.(event)); this.#handlers.set(type, handler); } emit(type: string, props: object = {}) { this.dispatchEvent(Object.assign(new Event(type), props)); } } // A data channel. Connected, what one side sends arrives a moment later at the other, also when this // side closes right after: a channel sends what it buffered first. class FakeChannel extends Target { readyState: RTCDataChannelState = 'connecting'; bufferedAmount = 0; bufferedAmountLowThreshold = 0; binaryType: BinaryType = 'blob'; // Everything this side sent. sent: (string | ArrayBuffer)[] = []; peer?: FakeChannel; // What this side drops instead of sending. drop = (_data: string | ArrayBuffer) => false; constructor(readonly label = 'file') { super(); } set onopen(handler: ((event: Any) => unknown) | null) { this.on('open', handler); } set onmessage(handler: ((event: Any) => unknown) | null) { this.on('message', handler); } send(data: string | ArrayBuffer) { if (this.readyState !== 'open') throw new DOMException('not open', 'InvalidStateError'); if (this.drop(data)) return; this.sent.push(data); const { peer } = this; const copy = typeof data === 'string' ? data : data.slice(0); if (peer) setImmediate(() => peer.readyState === 'open' && peer.emit('message', { data: copy })); } // What the peer sends, arriving right away. An object as JSON. receive(data: object | string | ArrayBuffer) { const message = typeof data === 'string' || data instanceof ArrayBuffer ? data : JSON.stringify(data); this.emit('message', { data: message }); } open() { this.readyState = 'open'; this.emit('open'); } close() { if (this.readyState === 'closed') return; this.readyState = 'closed'; setImmediate(() => this.emit('close')); const { peer } = this; if (peer && peer !== this) setImmediate(() => peer.close()); } // The JSON messages this side sent. json() { return this.sent.filter((data) => typeof data === 'string').map((data) => JSON.parse(data)); } // How many bytes of binary messages this side sent. bytes() { return this.sent.reduce((sum, data) => sum + (typeof data === 'string' ? 0 : data.byteLength), 0); } } const named = (description: RTCSessionDescriptionInit | null) => description?.sdp?.match(/a=fingerprint:\S+ (\S+)/)?.[1]; // A peer connection. Two connect in memory once each has the other's description, unless the test // keeps them apart. Its SDP has a fingerprint of its own, and a public address with a STUN server. class FakePeer extends Target { static all: FakePeer[] = []; static reachable = true; readonly fingerprint = Array.from(randomBytes(32), (byte) => byte.toString(16).padStart(2, '0')) .join(':') .toUpperCase(); localDescription: RTCSessionDescriptionInit | null = null; remoteDescription: RTCSessionDescriptionInit | null = null; signalingState: RTCSignalingState = 'stable'; iceGatheringState: RTCIceGatheringState = 'new'; connectionState: RTCPeerConnectionState = 'new'; channels: FakeChannel[] = []; constructor(readonly config: RTCConfiguration = {}) { super(); FakePeer.all.push(this); } set ondatachannel(handler: ((event: Any) => unknown) | null) { this.on('datachannel', handler); } getConfiguration() { return this.config; } createDataChannel(label: string) { const channel = new FakeChannel(label); this.channels.push(channel); return channel; } async setLocalDescription() { if (this.signalingState === 'closed') throw new DOMException('closed', 'InvalidStateError'); const type = this.signalingState === 'have-remote-offer' ? 'answer' : 'offer'; const srflx = this.config.iceServers?.length ? 'a=candidate:2 1 udp 1 203.0.113.5 50000 typ srflx\r\n' : ''; const host = 'a=candidate:1 1 udp 2 192.168.0.2 50000 typ host\r\n'; this.localDescription = { type, sdp: `v=0\r\na=fingerprint:sha-256 ${this.fingerprint}\r\n${host}${srflx}` }; this.signalingState = type === 'offer' ? 'have-local-offer' : 'stable'; this.iceGatheringState = 'complete'; this.link(); } async setRemoteDescription({ type, sdp }: RTCSessionDescriptionInit) { if (this.signalingState === 'closed') throw new DOMException('closed', 'InvalidStateError'); if (!sdp?.startsWith('v=0\r\n') || !named({ type, sdp })) throw new DOMException('no SDP', 'OperationError'); if (this.signalingState !== (type === 'answer' ? 'have-local-offer' : 'stable')) { throw new DOMException('wrong state', 'InvalidStateError'); } this.remoteDescription = { type, sdp }; this.signalingState = type === 'offer' ? 'have-remote-offer' : 'stable'; this.link(); } close() { if (this.signalingState === 'closed') return; this.signalingState = 'closed'; this.connectionState = 'closed'; // Without events on this side, the other one's channels close. for (const channel of this.channels) { channel.readyState = 'closed'; const { peer } = channel; if (peer) setImmediate(() => peer.close()); } } // The connection's state changed to state. state(state: RTCPeerConnectionState) { this.connectionState = state; this.emit('connectionstatechange'); } private link() { const other = FakePeer.all.find((peer) => peer !== this && peer.fingerprint === named(this.remoteDescription)); if (!other || named(other.remoteDescription) !== this.fingerprint || !FakePeer.reachable) return; if (!this.localDescription || !other.localDescription) return; const [offerer, answerer] = this.localDescription.type === 'offer' ? [this, other] : [other, this]; setImmediate(() => { if (offerer.signalingState === 'closed' || answerer.signalingState === 'closed') return; offerer.state('connected'); answerer.state('connected'); for (const channel of offerer.channels) { const end = new FakeChannel(channel.label); answerer.channels.push(end); channel.peer = end; end.peer = channel; answerer.emit('datachannel', { channel: end }); end.open(); channel.open(); } }); } } const trackers = new Map(); // A tracker socket, to the FakeTracker of its URL. Without one the URL is unreachable. class FakeSocket extends Target { static all: FakeSocket[] = []; readyState = 0; constructor(readonly url: string) { super(); FakeSocket.all.push(this); setImmediate(() => { if (this.readyState) return; const tracker = trackers.get(url); this.readyState = tracker ? 1 : 3; if (!tracker) return this.emit('close'); tracker.sockets.push(this); this.emit('open'); }); } set onopen(handler: ((event: Any) => unknown) | null) { this.on('open', handler); } send(data: string) { if (this.readyState !== 1) throw new DOMException('not open', 'InvalidStateError'); const msg = JSON.parse(data); setImmediate(() => trackers.get(this.url)?.receive(this, msg)); } close() { if (this.readyState >= 2) return; this.readyState = 2; trackers.get(this.url)?.forget(this); setImmediate(() => { this.readyState = 3; this.emit('close'); }); } // What the tracker sends. deliver(msg: object) { if (this.readyState === 1) this.emit('message', { data: JSON.stringify(msg) }); } // The tracker closed it. drop() { if (this.readyState >= 2) return; this.readyState = 3; trackers.get(this.url)?.forget(this); this.emit('close'); } } // A WebTorrent tracker in memory at url: it relays the offers in a swarm and the answers back, and // answers announcements with the swarm's seeders. reply takes over the answer: what it returns goes // back, nothing relayed, undefined is no answer. class FakeTracker { sockets: FakeSocket[] = []; // Everything announced to it. announced: Any[] = []; swarms = new Map>(); constructor( readonly url: string, public reply?: (msg: Any, socket: FakeSocket) => object | undefined, ) { trackers.set(url, this); } receive(socket: FakeSocket, msg: Any) { if (socket.readyState !== 1) return; this.announced.push(msg); if (this.reply) { const reply = this.reply(msg, socket); if (reply) socket.deliver(reply); return; } const { info_hash, peer_id } = msg; const swarm = this.swarms.get(info_hash) ?? new Map(); this.swarms.set(info_hash, swarm); swarm.set(peer_id, { socket, seeder: msg.left === 0 }); if (msg.answer) { const answer = { action: 'announce', info_hash, peer_id, offer_id: msg.offer_id, answer: msg.answer }; return swarm.get(msg.to_peer_id)?.socket.deliver(answer); } const complete = [...swarm.values()].filter((peer) => peer.seeder).length; socket.deliver({ action: 'announce', interval: 120, info_hash, complete, incomplete: swarm.size - complete }); const others = [...swarm].filter(([id]) => id !== peer_id); for (const { offer_id, offer } of msg.offers ?? []) { for (const [, peer] of others) peer.socket.deliver({ action: 'announce', info_hash, peer_id, offer_id, offer }); } } forget(socket: FakeSocket) { for (const swarm of this.swarms.values()) { for (const [id, peer] of swarm) if (peer.socket === socket) swarm.delete(id); } } // Its sockets still open. open() { return this.sockets.filter((socket) => socket.readyState === 1); } } // What the mocked src/download.ts saved, newest last. Unless autoSave is off, the download manager // reads each chunk right away, reports that every MiB like public/sw.js and finishes once ended. // Like startDownload, nothing comes once failed, the tests calling events themselves aside. type Saved = { file: { name: string; size: number }; events: DownloadEvents; chunks: Uint8Array[]; ended: boolean }; const saved: (Saved & { failed?: string })[] = []; let autoSave = true; function saveInMemory(file: { name: string; size: number }, events: DownloadEvents): Download { const download: Saved & { failed?: string } = { file, events, chunks: [], ended: false }; saved.push(download); let read = 0; let reported = 0; return { write: (chunk) => { download.chunks.push(new Uint8Array(chunk)); read += chunk.byteLength; if (!autoSave || read - reported < 2 ** 20) return; reported = read; const bytes = read; setImmediate(() => download.failed === undefined && events.read(bytes)); }, end: () => { download.ended = true; if (autoSave) setImmediate(() => download.failed === undefined && events.finished()); }, fail: (reason) => { download.failed = reason; }, }; } // A digest to compare files by, toEqual on megabytes takes seconds. const digest = (bytes: Uint8Array | ArrayBuffer) => createHash('sha256').update(new Uint8Array(bytes)).digest('hex'); const savedDigest = (download: Saved) => digest(Buffer.concat(download.chunks)); const fileDigest = async (source: File) => digest(await source.arrayBuffer()); // A session's events, kept to check them, and its signal. Every one ends after its test. const sessions: AbortController[] = []; function side() { const controller = new AbortController(); sessions.push(controller); const seen = { signal: controller.signal, stop: () => controller.abort(), logs: [] as string[], statuses: [] as string[], errors: [] as string[], checks: [] as (Check | undefined)[], files: [] as (Incoming | undefined)[], progress: [] as number[], expired: false, logged: (text: string) => seen.logs.some((line) => line.includes(text)), count: (text: string) => seen.logs.filter((line) => line.includes(text)).length, status: () => seen.statuses.at(-1), }; const events: SendEvents & ReceiveEvents = { log: (message) => seen.logs.push(message), status: (phase, text) => seen.statuses.push(`${phase}: ${text}`), error: (message) => seen.errors.push(message), check: (check) => seen.checks.push(check), progress: (read) => seen.progress.push(read), incoming: (file) => seen.files.push(file), expired: () => (seen.expired = true), }; return Object.assign(seen, { events }); } // Lets the fakes and real asynchronous work, Web Crypto above all, go on until check passes. The fake // timers only move when a test says so. async function until(check: () => unknown, ms = 5000) { const end = performance.now() + ms; while (!check()) { if (performance.now() > end) throw new Error(`timed out: ${check}`); await new Promise((resolve) => setImmediate(resolve)); } } // Gives everything that is under way a few turns, enough for nothing more to happen. const settle = async () => { for (let turn = 0; turn < 20; turn++) await new Promise((resolve) => setImmediate(resolve)); }; function deferred() { let resolve!: (value: T) => void; const promise = new Promise((done) => (resolve = done)); return { promise, resolve }; } const file = (size: number, name = 'payload.bin') => new File([randomBytes(size)], name); const openPeers = () => FakePeer.all.filter((pc) => pc.signalingState !== 'closed'); const openSockets = () => FakeSocket.all.filter((ws) => ws.readyState < 2); const asPeer = (pc: FakePeer) => pc as unknown as RTCPeerConnection; const asChannel = (channel: FakeChannel) => channel as unknown as RTCDataChannel; beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'], now: TEST_TIME }); vi.stubGlobal('RTCPeerConnection', FakePeer); vi.stubGlobal('WebSocket', FakeSocket); Object.assign(settings, { stun: false, stunServers: [...DEFAULT_STUN_SERVERS], trackers: [] }); FakePeer.all = []; FakePeer.reachable = true; FakeSocket.all = []; trackers.clear(); saved.length = 0; autoSave = true; }); afterEach(async () => { for (const session of sessions.splice(0)) session.abort(); await settle(); vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); describe('codes and salts', () => { it('makes codes of the 62 characters, each equally likely', () => { const counts = new Map(); for (const char of randomCode(62_000)) counts.set(char, (counts.get(char) ?? 0) + 1); expect([...counts.keys()].sort()).toEqual([...CODE_CHARS].sort()); for (const count of counts.values()) expect(count).toBeGreaterThan(800); }); it("ends a code with its window, a receiver's clock hours off still finds its salt", () => { const { code, salt } = newCode(); expect(code).toMatch(new RegExp(`^[0-9a-zA-Z]{${CODE_LENGTH}}$`)); expect(salt).toBe('2026-01-01T12:00'); for (const hours of [-3, -1, 0, 1, 3]) { vi.setSystemTime(TEST_TIME + hours * 3_600_000); expect(codeSalt(code)).toBe(salt); } // Half the characters' windows away it still does, one more and it takes the next cycle's. vi.setSystemTime(TEST_TIME + (CODE_CHARS.length / 2) * SALT_WINDOW); expect(codeSalt(code)).toBe(salt); vi.setSystemTime(TEST_TIME + (CODE_CHARS.length / 2 + 1) * SALT_WINDOW); expect(codeSalt(code)).not.toBe(salt); }); it('adds an own salt trimmed, refuses a blank one', () => { const at = Math.floor(TEST_TIME / SALT_WINDOW); expect(trackerSalt(at, ' Grüße ')).toBe('2026-01-01T12:00 Grüße'); expect(() => trackerSalt(at, ' ')).toThrow('the own salt is empty'); expect(newCode('own').salt).toBe('2026-01-01T12:00 own'); }); it("refuses what can't be a code", () => { for (const code of ['abcdefghij', 'abcdefghijkl', 'abcdefghij-', 'abcdefghijü']) { expect(() => codeSalt(code)).toThrow('a code has 11 letters and digits, check it'); } }); // The protocol in node:crypto, independent of Web Crypto: changing it splits old and new clients. 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 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)); const sealed = Buffer.from(await seal(sealing, 'offer', 'the sdp'), 'base64'); const decipher = createDecipheriv('aes-256-gcm', expand('signaling', 32), sealed.subarray(0, 12)); decipher.setAAD(Buffer.from('offer')).setAuthTag(sealed.subarray(-16)); expect(Buffer.concat([decipher.update(sealed.subarray(12, -16)), decipher.final()]).toString()).toBe('the sdp'); }); it('opens only what was sealed with the key as that type', async () => { const [{ sealing }, other] = await Promise.all([secrets('abcdefghijk', 'salt'), secrets('abcdefghijl', 'salt')]); const sealed = await seal(sealing, 'offer', 'the sdp'); expect(await unseal(sealing, 'offer', sealed)).toBe('the sdp'); expect(await unseal(sealing, 'answer', sealed)).toBeUndefined(); expect(await unseal(other.sealing, 'offer', sealed)).toBeUndefined(); expect(await unseal(sealing, 'offer', 'not base64!')).toBeUndefined(); const bytes = Buffer.from(sealed, 'base64'); bytes[20]! ^= 1; expect(await unseal(sealing, 'offer', bytes.toString('base64'))).toBeUndefined(); }); }); describe('messages', () => { it('reads only JSON objects', () => { expect(parse('{"ok":true}')).toEqual({ ok: true }); for (const data of ['null', '1', '"text"', '{', undefined, new ArrayBuffer(2)]) expect(parse(data)).toBeUndefined(); }); it('reads manual codes wrapped by a chat, tells a broken one', () => { const code = btoa('v=0\r\nsdp'); expect(decode(`${code.slice(0, 4)}\n ${code.slice(4)} `, 'offer')).toEqual({ type: 'offer', sdp: 'v=0\r\nsdp' }); expect(() => decode('not base64!', 'answer')).toThrow('not a valid answer, copy all of it'); }); it('counts every fingerprint once, at session or media level, also hidden ones', () => { const sdp = 'v=0\r\na=fingerprint:sha-256 AB:CD\r\nm=application\r\na=fingerprint:SHA-256 ab:cd\na=fingerprint:sha-1\t01\r\n' + // Hidden in lines the browser reads otherwise. 'a=candidate:1 1 udp 1 127.0.0.1 9 typ host a=fingerprint:sha-256 01:02\r\n' + 'a=x-decoy:a=fingerprint:sha-256 03:04\r\na=x-decoy:\ra=fingerprint:sha-256 05:06\r\n' + // A bare CR doesn't end the line for the browser. 'a=fingerprint:sha-256\r07:08\r\n'; expect(fingerprints(sdp)).toEqual([ 'sha-1 01', 'sha-256 01:02', 'sha-256 03:04', 'sha-256 05:06', 'sha-256 07:08', 'sha-256 ab:cd', ]); }); it('shows the first 16 bytes of a hash over all fingerprints for the check', async () => { const code = (list: string[]) => createHash('sha256') .update(JSON.stringify(list)) .digest('hex') .slice(0, 32) .toUpperCase() .match(/../g)! .join(' '); const pc = { localDescription: { sdp: 'v=0\r\na=fingerprint:sha-256 aa:bb\r\n' }, remoteDescription: { sdp: 'v=0\r\na=fingerprint:sha-256 0A:0B\r\nm=application\r\na=fingerprint:sha-1 0c\r\n' }, } as RTCPeerConnection; expect(await securityCheck(pc)).toEqual({ local: code(['sha-256 aa:bb']), remote: code(['sha-1 0c', 'sha-256 0a:0b']), }); expect(await securityCheck({ ...pc, remoteDescription: { sdp: 'v=0\r\n' } } as RTCPeerConnection)).toBeUndefined(); expect( await securityCheck({ localDescription: null, remoteDescription: null } as RTCPeerConnection), ).toBeUndefined(); }); it('names the side without a public address', () => { const sdp = (srflx: boolean) => ({ sdp: srflx ? 'a=candidate:2 1 udp 1 203.0.113.5 5 typ srflx\r\n' : '' }); const hint = (local: boolean, remote: boolean) => stunHint({ localDescription: sdp(local), remoteDescription: sdp(remote) } as RTCPeerConnection, 'receiver'); const need = ', between different networks both sides need STUN'; expect(hint(true, true)).toBeUndefined(); expect(hint(true, false)).toBe(`the receiver has no public address${need}`); expect(hint(false, true)).toBe(`this side has no public address${need}`); expect(hint(false, false)).toBe(`neither side has a public address${need}`); }); it('tells why no tracker is left', () => { const rejected = (reason?: string) => ({ rejected: reason }) as Parameters[0][number]; expect(noTracker([rejected(), undefined])).toBe('no tracker reachable, check the list under Servers and try again'); expect(noTracker([rejected('a: no'), rejected(), rejected('b: full')])).toBe( 'no tracker accepted it (a: no; b: full), check the list under Servers and try again', ); }); }); describe('session lifetime', () => { it('closes what a session owns once it ends, lets go of what closed before', () => { const session = new AbortController(); const [kept, closed, late] = [vi.fn(), vi.fn(), vi.fn()]; own(session.signal, { close: kept }); own(session.signal, { close: closed }).close(); expect(closed).toHaveBeenCalledTimes(1); expect(getEventListeners(session.signal, 'abort')).toHaveLength(1); session.abort(); expect(kept).toHaveBeenCalledTimes(1); own(session.signal, { close: late }); expect(late).toHaveBeenCalledTimes(1); }); it('expires once after ms, not after the session ended', () => { const session = new AbortController(); const expire = vi.fn(); deadline(session.signal, expire, 1000); vi.advanceTimersByTime(999); expect(expire).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); expect(expire).toHaveBeenCalledTimes(1); expect(getEventListeners(session.signal, 'abort')).toHaveLength(0); deadline(session.signal, expire, 1000); session.abort(); expect(vi.getTimerCount()).toBe(0); }); it('calls no more events once the session ended', () => { const session = new AbortController(); const log = vi.fn(); const events = live({ log }, session.signal); events.log('before'); session.abort(); events.log('after'); expect(log.mock.calls).toEqual([['before']]); }); }); describe('STUN servers', () => { // A probe each test answers itself, the servers asked in order. function prober() { const asked: { url: string; answer: (ok: boolean) => void; stopped: AbortSignal }[] = []; const probe = (url: string, stopped: AbortSignal) => new Promise((answer) => asked.push({ url, answer, stopped })); return { asked, choice: stunChoice(probe), urls: () => asked.map(({ url }) => url) }; } beforeEach(() => Object.assign(settings, { stun: true, stunServers: ['stun:a', 'stun:b', 'stun:c'] })); it('takes the first server that answers and keeps it, the next one once it gave no address', async () => { const { asked, choice, urls } = prober(); const session = new AbortController(); const first = choice.server(session.signal); await until(() => asked.length === 1); asked[0]!.answer(false); await until(() => asked.length === 2); asked[1]!.answer(true); expect(await first).toBe('stun:b'); expect(await choice.server(session.signal)).toBe('stun:b'); expect(urls()).toEqual(['stun:a', 'stun:b']); await choice.failed('stun:b'); const next = choice.server(session.signal); await until(() => asked.length === 3); expect(asked[2]!.url).toBe('stun:c'); asked[2]!.answer(false); // Around to the start of the list. await until(() => asked.length === 4); expect(asked[3]!.url).toBe('stun:a'); asked[3]!.answer(true); expect(await next).toBe('stun:a'); }); it('starts over when the list changed, uses none without STUN or servers', async () => { const { asked, choice } = prober(); const session = new AbortController(); const first = choice.server(session.signal); await until(() => asked.length === 1); asked[0]!.answer(true); expect(await first).toBe('stun:a'); settings.stunServers = ['stun:x', 'stun:a']; const changed = choice.server(session.signal); await until(() => asked.length === 2); expect(asked[1]!.url).toBe('stun:x'); asked[1]!.answer(true); expect(await changed).toBe('stun:x'); settings.stun = false; expect(await choice.server(session.signal)).toBeUndefined(); settings.stun = true; settings.stunServers = []; expect(await choice.server(session.signal)).toBeUndefined(); }); it('stops probing once no session waits, the next probe goes on from there', async () => { const { asked, choice } = prober(); const [one, two] = [new AbortController(), new AbortController()]; void choice.server(one.signal); void choice.server(two.signal); await until(() => asked.length === 1); asked[0]!.answer(false); await until(() => asked.length === 2); one.abort(); expect(asked[1]!.stopped.aborted).toBe(false); two.abort(); expect(asked[1]!.stopped.aborted).toBe(true); asked[1]!.answer(false); await settle(); expect(asked).toHaveLength(2); // At the one it stopped at, that one never got to answer. const three = new AbortController(); const resumed = choice.server(three.signal); await until(() => asked.length === 3); expect(asked[2]!.url).toBe('stun:b'); asked[2]!.answer(true); expect(await resumed).toBe('stun:b'); }); it('contacts no further server once STUN was turned off', async () => { const { asked, choice } = prober(); const session = new AbortController(); const server = choice.server(session.signal); await until(() => asked.length === 1); settings.stun = false; asked[0]!.answer(false); expect(await server).toBeUndefined(); expect(asked).toHaveLength(1); }); }); describe('tracker socket', () => { // A socket to url on the session, with what it reported. function socket(url = 'wss://one.test') { const session = side(); const got: Any[] = []; const lost = vi.fn(); const again = vi.fn(); const tracker = trackerSocket(url, session.signal, session.events, (msg) => void got.push(msg), lost, again); return { session, tracker, got, lost, again }; } it('reports an unreachable tracker once', async () => { const { session, lost } = socket(); await until(() => lost.mock.calls.length); await settle(); expect(lost).toHaveBeenCalledTimes(1); expect(session.logs).toEqual(['wss://one.test unreachable']); }); it('gives up on a tracker that never answers', async () => { new FakeTracker('wss://one.test', () => undefined); const { session, tracker, lost } = socket(); await until(() => tracker.ws.readyState === 1); tracker.ws.send('{}'); vi.advanceTimersByTime(TRACKER_TIMEOUT); expect(session.logs).toEqual(['wss://one.test did not answer']); expect(lost).toHaveBeenCalledTimes(1); expect(tracker.ws.readyState).toBeGreaterThanOrEqual(2); }); it('takes a failure before anything else for a rejection, after that only notes it', async () => { new FakeTracker('wss://one.test', () => ({ 'failure reason': 'not here' })); const rejected = socket(); await until(() => rejected.tracker.ws.readyState === 1); rejected.tracker.ws.send('{}'); await until(() => rejected.lost.mock.calls.length); expect(rejected.tracker.rejected).toBe('wss://one.test: not here'); expect(rejected.session.logs).toEqual(['rejected by wss://one.test: not here']); expect(rejected.tracker.alive()).toBe(false); new FakeTracker('wss://two.test', () => ({ action: 'announce' })); const accepted = socket('wss://two.test'); await until(() => accepted.tracker.ws.readyState === 1); accepted.tracker.ws.send('{}'); await until(() => accepted.got.length); const ws = accepted.tracker.ws as unknown as FakeSocket; ws.deliver({ 'failure reason': 'x'.repeat(1000) }); ws.deliver({ 'failure reason': 'slow down' }); ws.deliver({ 'not json': undefined }); ws.deliver({ 'failure reason': 'slow down' }); ws.deliver({ 'failure reason': 'shutting down' }); expect(accepted.session.logs).toEqual([ `wss://two.test: ${'x'.repeat(200)}`, 'wss://two.test: slow down', 'wss://two.test: shutting down', ]); expect(accepted.tracker.alive()).toBe(true); expect(accepted.lost).not.toHaveBeenCalled(); }); it('takes a message over MAX_TRACKER_MESSAGE first for a rejection, after that only notes and drops it', async () => { new FakeTracker('wss://one.test', () => undefined); // msg padded to length characters of JSON. const sized = (length: number, msg: object) => { const json = JSON.stringify({ ...msg, pad: '' }); return { ...msg, pad: ' '.repeat(length - json.length) }; }; const rejected = socket(); await until(() => rejected.tracker.ws.readyState === 1); (rejected.tracker.ws as unknown as FakeSocket).deliver( sized(MAX_TRACKER_MESSAGE + 1, { 'failure reason': 'not here' }), ); expect(rejected.tracker.rejected).toBe('wss://one.test: message over 64 KiB'); expect(rejected.session.logs).toEqual(['rejected by wss://one.test: message over 64 KiB']); expect(rejected.lost).toHaveBeenCalledTimes(1); const { session, tracker, got, lost } = socket(); await until(() => tracker.ws.readyState === 1); const ws = tracker.ws as unknown as FakeSocket; ws.deliver(sized(MAX_TRACKER_MESSAGE, { action: 'announce' })); ws.deliver(sized(MAX_TRACKER_MESSAGE + 1, { action: 'announce' })); ws.deliver(sized(MAX_TRACKER_MESSAGE + 1, { action: 'announce' })); expect(got).toHaveLength(1); expect(session.logs).toEqual(['wss://one.test: message over 64 KiB']); expect(lost).not.toHaveBeenCalled(); }); it('drops messages beyond MAX_TRACKER_MESSAGES per MESSAGE_WINDOW', async () => { new FakeTracker('wss://one.test', () => undefined); const { session, tracker, got } = socket(); await until(() => tracker.ws.readyState === 1); const ws = tracker.ws as unknown as FakeSocket; for (let i = 0; i < MAX_TRACKER_MESSAGES + 5; i++) ws.deliver({ action: 'announce', i }); expect(got.map((msg) => msg.i)).toEqual([...Array(MAX_TRACKER_MESSAGES).keys()]); expect(session.logs).toEqual(['wss://one.test sends too much, dropping some of it']); vi.setSystemTime(Date.now() + MESSAGE_WINDOW); ws.deliver({ action: 'announce', i: 'later' }); expect(got.at(-1).i).toBe('later'); expect(session.logs).toHaveLength(1); }); it('notes at most TRACKER_NOTES lines', async () => { new FakeTracker('wss://one.test', () => undefined); const { session, tracker } = socket(); await until(() => tracker.ws.readyState === 1); const ws = tracker.ws as unknown as FakeSocket; ws.deliver({ action: 'announce' }); for (let i = 0; i < TRACKER_NOTES + 5; i++) ws.deliver({ 'failure reason': `reason ${i}` }); expect(session.logs).toEqual([ ...[...Array(TRACKER_NOTES).keys()].map((i) => `wss://one.test: reason ${i}`), 'wss://one.test: more of it, no longer logged', ]); }); it('announces again on the interval it names, at least MIN_INTERVAL, at most TRACKER_WAIT', async () => { for (const [interval, every] of [ [0, MIN_INTERVAL], [120, 120_000], ['1e999', TRACKER_WAIT], ] as const) { const url = `wss://${interval}.test`; new FakeTracker(url); const { tracker, again } = socket(url); await until(() => tracker.ws.readyState === 1); (tracker.ws as unknown as FakeSocket).emit('message', { data: `{"interval":${interval}}` }); vi.advanceTimersByTime(every - 1); expect(again).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); expect(again).toHaveBeenCalledTimes(1); tracker.close(); } expect(vi.getTimerCount()).toBe(0); }); it('closes without reporting it lost, and with the session', async () => { new FakeTracker('wss://one.test'); const closed = socket(); closed.tracker.close(); await settle(); expect(closed.lost).not.toHaveBeenCalled(); expect(closed.session.logs).toEqual([]); const ended = socket(); await until(() => ended.tracker.ws.readyState === 1); ended.session.stop(); await settle(); expect(ended.tracker.alive()).toBe(false); expect(ended.lost).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); }); }); describe('proof of the code', () => { const key = () => crypto.subtle.importKey('raw', randomBytes(32), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']); const sdp = (fingerprint: string) => `v=0\r\na=fingerprint:sha-256 ${fingerprint}\r\n`; // One side of a connection as it sees it: its own SDP of type and the peer's. const view = (type: 'offer' | 'answer', local: string, remote: string) => ({ localDescription: { type, sdp: sdp(local) }, remoteDescription: { type: type === 'offer' ? 'answer' : 'offer', sdp: sdp(remote) }, }) as RTCPeerConnection; function pair() { const [a, b] = [new FakeChannel(), new FakeChannel()]; a.peer = b; b.peer = a; a.readyState = b.readyState = 'open'; return [a, b] as const; } it('passes on both sides with the same key and the same certificates', async () => { const shared = await key(); const [a, b] = pair(); const end = vi.fn(); // Sent once the channel opens. a.readyState = 'connecting'; const proven = Promise.all([ prove(view('offer', 'AA', 'BB'), asChannel(a), shared, end), prove(view('answer', 'BB', 'AA'), asChannel(b), shared, end), ]); a.open(); await proven; expect(end).not.toHaveBeenCalled(); }); it('fails with another key, other certificates or a proof sent back', async () => { const shared = await key(); for (const [views, keys] of [ [ [view('offer', 'AA', 'BB'), view('answer', 'BB', 'AA')], [shared, await key()], ], // A man in the middle with its own certificate towards each side. [ [view('offer', 'AA', 'M1'), view('answer', 'BB', 'M2')], [shared, shared], ], ] as const) { const [a, b] = pair(); const ends = [vi.fn(), vi.fn()]; void prove(views[0], asChannel(a), keys[0], ends[0]!); void prove(views[1], asChannel(b), keys[1], ends[1]!); await until(() => ends.every((end) => end.mock.calls.length)); for (const end of ends) expect(end).toHaveBeenCalledWith('security check failed, the peer does not know the code'); } const reflecting = new FakeChannel(); reflecting.peer = reflecting; reflecting.readyState = 'open'; const end = vi.fn(); void prove(view('offer', 'AA', 'BB'), asChannel(reflecting), shared, end); await until(() => end.mock.calls.length); expect(end).toHaveBeenCalledWith('security check failed, the peer does not know the code'); }); it('gives up on a peer that proves nothing within PROOF_TIMEOUT', async () => { const [a] = pair(); const end = vi.fn(); void prove(view('offer', 'AA', 'BB'), asChannel(a), await key(), end); vi.advanceTimersByTime(PROOF_TIMEOUT - 1); expect(end).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); expect(end).toHaveBeenCalledWith('the peer proved no code'); }); // The transfer listens after it and would take the proof for an offer. it('keeps the proof from the listeners after it', async () => { const shared = await key(); const [a, b] = pair(); const later = vi.fn(); const proven = prove(view('answer', 'BB', 'AA'), asChannel(b), shared, vi.fn()); b.addEventListener('message', later); void prove(view('offer', 'AA', 'BB'), asChannel(a), shared, vi.fn()); await proven; expect(later).not.toHaveBeenCalled(); }); }); describe('sending', () => { // A transfer of file on a connection whose handshake passes once check is called. function sending(source: File) { const pc = new FakePeer(); const channel = new FakeChannel(); channel.readyState = 'open'; const checked = deferred(); const handshake = { checked: checked.promise, start: vi.fn(), end: vi.fn() }; const session = side(); const done = sendFile(asPeer(pc), asChannel(channel), source, session.events, handshake, session.signal); return { pc, channel, session, handshake, done, check: checked.resolve }; } it("offers once checked and confirmed by the receiver, sends once asked, waits for the receiver's save", async () => { const source = file(100_000); const { pc, channel, session, handshake, check } = sending(source); // Too early, the receiver has to ask after the offer. channel.receive({ ok: true }); channel.receive({ start: true }); await settle(); expect(channel.sent).toEqual([]); check(); await until(() => channel.sent.length); expect(channel.json()).toEqual([{ name: 'payload.bin', size: 100_000 }]); await settle(); expect(channel.sent).toHaveLength(1); expect(handshake.start).not.toHaveBeenCalled(); channel.receive({ start: true }); await until(() => session.logged('sent')); expect(handshake.start).toHaveBeenCalled(); expect(channel.bytes()).toBe(100_000); const chunks = channel.sent.slice(1).map((chunk) => new Uint8Array(chunk as ArrayBuffer)); expect(digest(Buffer.concat(chunks))).toBe(await fileDigest(source)); expect(session.status()).toBe('transfer: Sent, waiting for the receiver to save the rest'); expect(pc.signalingState).not.toBe('closed'); channel.receive({ done: true }); expect(session.status()).toBe('done: Delivered'); expect(session.progress.at(-1)).toBe(100_000); expect(pc.signalingState).toBe('closed'); expect(session.errors).toEqual([]); }); // The receiver's download manager reports what it read, the rest is held in its RAM. it('keeps at most WINDOW unread, ignores reads that make no sense', async () => { const size = 3 * WINDOW; const { channel, session, check } = sending(file(size)); check(); channel.receive({ ok: true }); await until(() => channel.sent.length); channel.receive({ start: true }); await until(() => channel.bytes() === WINDOW); await settle(); expect(channel.bytes()).toBe(WINDOW); for (const read of [size + 1, -1, 1.5, '1000', 0]) channel.receive({ read }); await settle(); expect(channel.bytes()).toBe(WINDOW); expect(session.progress).toEqual([0]); channel.receive({ read: CHUNK_SIZE }); await until(() => channel.bytes() === WINDOW + CHUNK_SIZE); // Not back. channel.receive({ read: 1 }); channel.receive({ read: WINDOW }); await until(() => channel.bytes() === 2 * WINDOW); channel.receive({ read: 2 * WINDOW }); await until(() => session.logged('sent')); expect(channel.bytes()).toBe(size); expect(session.progress).toEqual([0, CHUNK_SIZE, WINDOW, 2 * WINDOW]); }); it("waits while the channel's buffer is full", async () => { const { channel, check } = sending(file(4 * CHUNK_SIZE)); check(); channel.receive({ ok: true }); await until(() => channel.sent.length); channel.bufferedAmount = MAX_BUFFERED + 1; channel.receive({ start: true }); await settle(); expect(channel.bytes()).toBe(0); channel.bufferedAmount = 0; channel.emit('bufferedamountlow'); await until(() => channel.bytes() === 4 * CHUNK_SIZE); }); it("reports the receiver's error, a lost connection and a file it can't read anymore", async () => { const stopped = sending(file(WINDOW + 1)); stopped.check(); stopped.channel.receive({ ok: true }); await until(() => stopped.channel.sent.length); stopped.channel.receive({ start: true }); stopped.channel.receive({ error: `cancelled ${'x'.repeat(300)}` }); expect(stopped.session.errors).toEqual([`receiver stopped: cancelled ${'x'.repeat(190)}`]); expect(stopped.pc.signalingState).toBe('closed'); const lost = sending(file(WINDOW + 1)); lost.check(); lost.channel.receive({ ok: true }); await until(() => lost.channel.sent.length); lost.channel.receive({ start: true }); await until(() => lost.channel.bytes() === WINDOW); lost.pc.state('failed'); expect(lost.session.errors).toEqual(['connection lost']); await lost.done; const gone = { name: 'gone.bin', size: 10, slice: () => ({ arrayBuffer: () => Promise.reject(new Error()) }) }; const unreadable = sending(gone as unknown as File); unreadable.check(); unreadable.channel.receive({ ok: true }); await until(() => unreadable.channel.sent.length); unreadable.channel.receive({ start: true }); await unreadable.done; expect(unreadable.session.errors).toEqual(['could not read gone.bin anymore']); }); it('stops quietly when the connection closes before the transfer or the session ends', async () => { const closed = sending(file(1000)); closed.channel.close(); closed.check(); await closed.done; expect(closed.channel.sent).toEqual([]); expect(closed.session.errors).toEqual([]); const ended = sending(file(WINDOW + 1)); ended.check(); ended.channel.receive({ ok: true }); await until(() => ended.channel.sent.length); ended.channel.receive({ start: true }); await until(() => ended.channel.bytes() === WINDOW); ended.session.stop(); await ended.done; expect(ended.pc.signalingState).toBe('closed'); expect(ended.session.errors).toEqual([]); }); }); describe('receiving', () => { // A transfer into the mocked download, on a connection whose handshake passes once check is called. function receiving() { autoSave = false; const pc = new FakePeer(); const channel = new FakeChannel(); channel.readyState = 'open'; const checked = deferred(); const handshake = { checked: checked.promise, start: vi.fn(), end: vi.fn() }; const session = side(); receiveFile(asPeer(pc), asChannel(channel), session.events, handshake, session.signal); return { pc, channel, session, handshake, check: checked.resolve }; } // Offered and confirmed, with the download started. async function downloading(size: number) { const receiver = receiving(); receiver.check(); await until(() => receiver.channel.sent.length); receiver.channel.receive({ name: 'payload.bin', size }); receiver.session.files[0]!.download(); return { ...receiver, download: saved.at(-1)! }; } it('accepts nothing before the check, offers the file to the user once', async () => { const { channel, session, check } = receiving(); channel.receive({ name: 'early.bin', size: 1 }); await settle(); expect(session.files).toEqual([]); expect(channel.sent).toEqual([]); check(); await until(() => channel.sent.length); expect(channel.json()).toEqual([{ ok: true }]); channel.receive(new ArrayBuffer(4)); channel.receive({ name: 'payload.bin', size: 4 }); channel.receive({ name: 'second.bin', size: 1 }); expect(session.files).toMatchObject([{ name: 'payload.bin', size: 4 }]); expect(session.status()).toBe('wait: Click Download to save the file'); expect(saved).toEqual([]); }); it("ends the connection on an offer that isn't a file", async () => { for (const offer of [ { name: 1, size: 2 }, { name: 'x'.repeat(MAX_NAME + 1), size: 2 }, { name: 'a', size: -1 }, { name: 'a', size: 1.5 }, { name: 'a', size: 2 ** 53 }, 'not json', ]) { const { channel, session, handshake, check } = receiving(); check(); await until(() => channel.sent.length); channel.receive(offer); expect(handshake.end).toHaveBeenCalledWith('the sender offered no valid file'); expect(session.files).toEqual([]); } }); it('strips controls, line separators and bidi controls from the offered name', async () => { const { channel, session, check } = receiving(); check(); await until(() => channel.sent.length); channel.receive({ name: 'invoice\u202Efdp.exe\n\u2028done\u0000\u009B\u2066', size: 1 }); expect(session.files).toMatchObject([{ name: 'invoicefdp.exedone' }]); expect(session.logs.at(-1)).toBe('offered invoicefdp.exedone (1 bytes)'); session.files[0]!.download(); expect(saved.at(-1)!.file.name).toBe('invoicefdp.exedone'); }); it("saves the chunks in order, reports the download manager's reads and when it finished", async () => { const { channel, session, handshake, download } = await downloading(3 * CHUNK_SIZE); expect(handshake.start).toHaveBeenCalled(); expect(download.file).toEqual({ name: 'payload.bin', size: 3 * CHUNK_SIZE }); expect(channel.json().at(-1)).toEqual({ start: true }); const chunks = [0, 1, 2].map(() => randomBytes(CHUNK_SIZE)); for (const chunk of chunks) channel.receive(new Uint8Array(chunk).buffer); expect(savedDigest(download)).toBe(digest(Buffer.concat(chunks))); expect(download.ended).toBe(true); // Once all arrived, nothing more counts. channel.receive(new ArrayBuffer(1)); expect(session.errors).toEqual([]); download.events.read(CHUNK_SIZE); expect(channel.json().at(-1)).toEqual({ read: CHUNK_SIZE }); download.events.finished(); expect(channel.json().at(-1)).toEqual({ done: true }); expect(session.status()).toBe('done: Download complete'); expect(session.progress).toEqual([0, CHUNK_SIZE, 3 * CHUNK_SIZE]); expect(channel.readyState).toBe('closed'); }); it('ends an empty file right away', async () => { const { download } = await downloading(0); expect(download.ended).toBe(true); }); it('fails the download on more bytes than offered or beyond the window', async () => { for (const [size, chunks, reason] of [ [10, [6, 5], 'the sender sent more than it offered'], [4 * WINDOW, [WINDOW, CHUNK_SIZE, 1], 'the sender ignored the flow control'], ] as const) { const { channel, session, download } = await downloading(size); for (const bytes of chunks) channel.receive(new ArrayBuffer(bytes)); expect(download.failed).toBe(reason); expect(session.errors).toEqual([`download failed: ${reason}`]); expect(channel.json().at(-1)).toEqual({ error: reason }); expect(channel.readyState).toBe('closed'); } }); it('tells the sender when the user cancelled, the user when the download failed', async () => { const cancelled = await downloading(10); cancelled.download.events.cancelled(); expect(cancelled.channel.json().at(-1)).toEqual({ error: 'download cancelled' }); expect(cancelled.session.status()).toBe('stopped: Download cancelled'); expect(cancelled.session.errors).toEqual([]); const failed = await downloading(10); failed.download.events.failed('service worker stopped'); expect(failed.session.errors).toEqual(['download failed: service worker stopped']); expect(failed.channel.json().at(-1)).toEqual({ error: 'service worker stopped' }); }); it('withdraws the offer when the sender leaves before the download, fails it after', async () => { const before = receiving(); before.check(); await until(() => before.channel.sent.length); before.channel.receive({ name: 'payload.bin', size: 10 }); before.pc.state('failed'); expect(before.session.files).toMatchObject([{ name: 'payload.bin' }, undefined]); const after = await downloading(10); after.channel.close(); await until(() => after.session.errors.length); expect(after.session.errors).toEqual(['download failed: connection lost']); }); it('fails the download once the session ended', async () => { const { session, download } = await downloading(10); session.stop(); expect(download.failed).toBe('stopped'); }); }); describe('manual exchange', () => { // Sender and receiver connected by the manual codes, both shown the check. async function exchange(source: File) { const [sender, receiver] = [side(), side()]; const { offer, accept } = await createOffer(source, sender.events, sender.signal); const answer = await answerOffer(offer, receiver.events, receiver.signal); await accept(answer); await until(() => sender.checks[0] && receiver.checks[0]); return { sender, receiver, accept, answer }; } it('sends a file once both compared the same codes', async () => { const source = file(WINDOW + 100_000); const { sender, receiver } = await exchange(source); const [own, peer] = [sender.checks[0]!, receiver.checks[0]!]; expect([own.local, own.remote]).toEqual([peer.remote, peer.local]); expect(sender.status()).toBe('wait: Compare the security codes above with the receiver'); own.confirm(); await until(() => sender.logged("waiting for the receiver's security check")); expect(receiver.files).toEqual([]); peer.confirm(); await until(() => receiver.files[0]); receiver.files[0]!.download(); await until(() => sender.logged('delivered') && receiver.logged('download complete')); expect(savedDigest(saved[0]!)).toBe(await fileDigest(source)); expect(openPeers()).toEqual([]); expect([...sender.errors, ...receiver.errors]).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); it('ends both sides when one says the codes differ', async () => { const { sender, receiver } = await exchange(file(10)); receiver.checks[0]!.reject(); await until(() => sender.errors.length); expect(receiver.errors).toEqual(['security check failed']); expect(sender.errors).toEqual(['the receiver left before the transfer']); expect(sender.checks.at(-1)).toBeUndefined(); expect(openPeers()).toEqual([]); }); it('shows other codes for a peer that named a second certificate', async () => { const [sender, receiver] = [side(), side()]; const { offer, accept } = await createOffer(file(10), sender.events, sender.signal); // The real one first, the fake one connects too. FakePeer only knows the first. const tampered = btoa(`${atob(offer)}m=application\r\na=fingerprint:sha-256 AA:BB\r\n`); await accept(await answerOffer(tampered, receiver.events, receiver.signal)); await until(() => sender.checks[0] && receiver.checks[0]); const [own, peer] = [sender.checks[0]!, receiver.checks[0]!]; expect(peer.remote).not.toBe(own.local); expect(peer.local).toBe(own.remote); expect(receiver.status()).toBe('wait: Compare the security codes above with the sender'); }); it('reports a broken offer and answer, the offer stays good for the right answer', async () => { const receiver = side(); await expect(answerOffer(btoa('v=0 but nothing else'), receiver.events, receiver.signal)).rejects.toThrow( 'not a valid offer, copy all of it', ); expect(openPeers()).toEqual([]); await expect(answerOffer('not base64!', receiver.events, receiver.signal)).rejects.toThrow( 'not a valid offer, copy all of it', ); const sender = side(); const { offer, accept } = await createOffer(file(10), sender.events, sender.signal); await expect(accept(btoa('v=0\r\nnothing'))).rejects.toThrow('not a valid answer to this offer, copy all of it'); await accept(await answerOffer(offer, receiver.events, receiver.signal)); await until(() => sender.checks[0]); }); it('tells why it could not connect, on each side once its time is up', async () => { FakePeer.reachable = false; const [sender, receiver] = [side(), side()]; const { offer, accept } = await createOffer(file(10), sender.events, sender.signal); await accept(await answerOffer(offer, receiver.events, receiver.signal)); const neither = 'could not connect: neither side has a public address, between different networks both sides need STUN'; vi.advanceTimersByTime(CONNECT_TIMEOUT); expect(sender.errors).toEqual([neither]); expect(receiver.errors).toEqual([]); vi.advanceTimersByTime(TRACKER_WAIT - CONNECT_TIMEOUT); expect(receiver.errors).toEqual([neither]); expect(openPeers()).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); }); describe('tracker signaling', () => { const URLS = ['wss://one.test', 'wss://two.test', 'wss://three.test']; // An announcement as a tracker relays it from another peer. const relayed = (msg: object) => ({ action: 'announce', peer_id: randomBytes(20).toString('latin1'), ...msg }); const offerId = () => randomBytes(20).toString('latin1'); it('sends a file proven by the code, the share is used up after', async () => { new FakeTracker(URLS[0]!); settings.trackers = [URLS[0]!]; const [sender, receiver] = [side(), side()]; const source = file(2 * WINDOW); const { code } = await sendViaTracker(source, sender.events, sender.signal); await receiveViaTracker(code, receiver.events, receiver.signal); await until(() => receiver.files[0]); expect([...sender.checks, ...receiver.checks]).toEqual([]); expect(sender.logged('security check passed') && receiver.logged('security check passed')).toBe(true); receiver.files[0]!.download(); await until(() => sender.logged('delivered') && receiver.logged('download complete')); expect(savedDigest(saved[0]!)).toBe(await fileDigest(source)); expect(openPeers()).toEqual([]); expect(openSockets()).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); it('shares on after a peer that proves no code, with the next receiver', async () => { new FakeTracker(URLS[0]!); settings.trackers = [URLS[0]!]; const [sender, silent, receiver] = [side(), side(), side()]; const { code } = await sendViaTracker(file(10), sender.events, sender.signal); await receiveViaTracker(code, silent.events, silent.signal); // Its offer's channel, the first one made. 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')); // The sender's proof still reaches it. await until(() => silent.logged('security check passed')); vi.advanceTimersByTime(PROOF_TIMEOUT); await until(() => sender.logged('waiting for the next receiver')); expect(sender.logged('the peer proved no code')).toBe(true); expect(sender.logged('offered')).toBe(false); // Left without the sender, it looks again. await until(() => silent.logged('looking again')); silent.stop(); await receiveViaTracker(code, receiver.events, receiver.signal); await until(() => receiver.files[0]); expect(sender.errors).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]!); new FakeTracker(URLS[2]!); settings.trackers = URLS; const sender = side(); await sendViaTracker(file(10), sender.events, sender.signal); await until(() => sender.logged(`waiting on ${URLS[1]}`)); await settle(); expect(FakeSocket.all.map((ws) => ws.url)).toEqual(URLS.slice(0, 2)); expect(sender.logged(`rejected by ${URLS[0]}: not here`)).toBe(true); second.sockets[0]!.drop(); await until(() => sender.logged(`waiting on ${URLS[2]}`)); expect(sender.errors).toEqual([]); trackers.get(URLS[2]!)!.sockets[0]!.drop(); await until(() => sender.errors.length); expect(sender.errors).toEqual([ `no tracker accepted it (${URLS[0]}: not here), check the list under Servers and try again`, ]); expect(vi.getTimerCount()).toBe(0); }); it('reports trackers that reject on both sides, unreachable ones as such', async () => { for (const url of URLS) new FakeTracker(url, () => ({ 'failure reason': 'not here' })); settings.trackers = URLS; const [sender, receiver] = [side(), side()]; const { code } = await sendViaTracker(file(10), sender.events, sender.signal); await receiveViaTracker(code, receiver.events, receiver.signal); const rejected = `no tracker accepted it (${URLS.map((url) => `${url}: not here`).join('; ')}), check the list under Servers and try again`; await until(() => sender.errors.length && receiver.errors.length); expect(sender.errors).toEqual([rejected]); expect(receiver.errors).toEqual([rejected]); // Neither keeps a timer, not even its expiry. expect(vi.getTimerCount()).toBe(0); trackers.clear(); const lonely = side(); await sendViaTracker(file(10), lonely.events, lonely.signal); await until(() => lonely.errors.length); expect(lonely.errors).toEqual(['no tracker reachable, check the list under Servers and try again']); expect(openPeers()).toEqual([]); expect(openSockets()).toEqual([]); }); it('walks the trackers until one has a seeder, keeps its offer on those it passed', async () => { let seeders = [0, 1, 0]; for (const [i, url] of URLS.entries()) { new FakeTracker(url, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash, complete: seeders[i] })); } settings.trackers = URLS; const receiver = side(); await receiveViaTracker('somecode123', receiver.events, receiver.signal); await until(() => receiver.logged(`looking on ${URLS[1]}`)); await settle(); expect(openSockets().map((ws) => ws.url)).toEqual(URLS.slice(0, 2)); // The sender lost the second one. seeders = [0, 0, 0]; 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(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 }); expect(receiver.status()).toBe('wait: Found the share on three.test, waiting for the sender to answer'); expect(receiver.errors).toEqual([]); }); // A tracker sees all signaling, without the code it can read none of it nor get anything answered: // not an SDP of its own, not the receiver's sealed offer passed off as an answer. it('seals the offers, ignores answers without the code', async () => { const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); settings.trackers = [URLS[0]!]; const receiver = side(); await receiveViaTracker('somecode123', receiver.events, receiver.signal); await until(() => tracker.announced.length); const [{ offer_id, offer }] = tracker.announced[0].offers; expect(offer.sdp).not.toContain('a=fingerprint'); expect(offer.sdp).not.toContain('candidate'); for (const sdp of ['v=0\r\na=fingerprint:sha-256 AA\r\n', offer.sdp]) { tracker.sockets[0]!.deliver(relayed({ offer_id, answer: { type: 'answer', sdp } })); } await until(() => receiver.count('answer without the code')); await settle(); expect(receiver.count('answer without the code')).toBe(1); expect(receiver.logged('answer via')).toBe(false); expect(FakePeer.all.map((pc) => pc.remoteDescription)).toEqual([null]); }); // Trimmed and NFC, an ü typed on one system can be other bytes than on the next. it('takes the own salt into the swarm, the share is found only with it', async () => { const tracker = 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, ' Gru\u0308ße '); await until(() => tracker.announced.length); expect(tracker.announced[0].info_hash).toBe((await secrets(code, codeSalt(code, 'Grüße'))).hash); 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', ); await receiveViaTracker(code, receiver.events, receiver.signal, 'Grüße'); await until(() => receiver.files[0]); }); // Anyone with the code can send offers no browser can parse, as many as they like. it('lets go of every unusable offer and keeps the tracker, ignores offers without the code', async () => { const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); settings.trackers = [URLS[0]!]; const sender = side(); const { code } = await sendViaTracker(file(10), sender.events, sender.signal); const { sealing } = await secrets(code, codeSalt(code)); await until(() => tracker.open().length); const ws = tracker.sockets[0]!; for (let offers = 1; offers <= 25; offers++) { ws.deliver( relayed({ offer_id: offerId(), offer: { type: 'offer', sdp: await seal(sealing, 'offer', 'garbage') } }), ); await until(() => sender.count('unusable offer') === offers); if (offers === 1) ws.deliver({ 'failure reason': 'slow down' }); // Fewer than MAX_TRACKER_MESSAGES per MESSAGE_WINDOW, none of them is dropped. if (offers % 10 === 0) vi.setSystemTime(Date.now() + MESSAGE_WINDOW); } for (let offers = 0; offers < 5; offers++) ws.deliver(relayed({ offer_id: offerId(), offer: { sdp: 'garbage' } })); await until(() => sender.count('offer without the code')); await settle(); expect(sender.count('offer without the code')).toBe(1); expect(sender.logged(`${URLS[0]}: slow down`)).toBe(true); expect(sender.logged('rejected by')).toBe(false); expect(sender.errors).toEqual([]); expect(FakePeer.all).toHaveLength(25); expect(openPeers()).toEqual([]); // The tracker socket's and the expiry's, none for the closed connections. expect(getEventListeners(sender.signal, 'abort')).toHaveLength(2); }); it('gives an offer still being opened no turn after the expiry', async () => { const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); settings.trackers = [URLS[0]!]; const sender = side(); const { code } = await sendViaTracker(file(10), sender.events, sender.signal); const { sealing } = await secrets(code, codeSalt(code)); const sealed = await seal(sealing, 'offer', 'v=0\r\na=fingerprint:sha-256 AA\r\n'); await until(() => tracker.open().length); const decrypt = vi.spyOn(crypto.subtle, 'decrypt'); tracker.sockets[0]!.deliver(relayed({ offer_id: offerId(), offer: { type: 'offer', sdp: sealed } })); expect(decrypt).toHaveBeenCalledTimes(1); vi.advanceTimersByTime(TRACKER_WAIT); expect(sender.errors).toHaveLength(1); expect(sender.errors[0]).toMatch(/^nobody received the file until .+, share it again$/); await decrypt.mock.results[0]!.value; await settle(); expect(sender.logged('offer via')).toBe(false); expect(FakePeer.all).toEqual([]); }); // Trackers drop a peer that doesn't announce again on their interval. it('announces again on both sides until they give up after TRACKER_WAIT', async () => { const tracker = new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 0, info_hash })); settings.trackers = [URLS[0]!]; const [sender, receiver] = [side(), side()]; const { code } = await sendViaTracker(file(10), sender.events, sender.signal); await receiveViaTracker(code, receiver.events, receiver.signal); await until(() => tracker.announced.length === 2); const [shared, offered] = tracker.announced; vi.advanceTimersByTime(MIN_INTERVAL - 1); await settle(); expect(tracker.announced).toHaveLength(2); vi.advanceTimersByTime(1); await until(() => tracker.announced.length === 4); const again = tracker.announced.slice(2); expect(again.map((msg) => [msg.info_hash, msg.left, msg.event])).toEqual([ [shared.info_hash, 0, undefined], [shared.info_hash, 1, undefined], ]); // The same offer, a busy sender may have dropped it. expect(again[1].offers).toEqual(offered.offers); 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$/); await settle(); expect(openSockets()).toEqual([]); expect(openPeers()).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); it('lets a receiver connected before the expiry download after it', async () => { new FakeTracker(URLS[0]!); settings.trackers = [URLS[0]!]; 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]); vi.advanceTimersByTime(TRACKER_WAIT); expect(sender.expired).toBe(true); await settle(); expect(openSockets()).toEqual([]); receiver.files[0]!.download(); await until(() => sender.logged('delivered')); expect([...sender.errors, ...receiver.errors]).toEqual([]); }); it('keeps nothing of sessions that ended', async () => { new FakeTracker(URLS[0]!, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash })); settings.trackers = [URLS[0]!]; for (let session = 0; session < 5; session++) { const [sender, receiver] = [side(), side()]; await sendViaTracker(file(10), sender.events, sender.signal); await receiveViaTracker(`nobodyhere${session}`, receiver.events, receiver.signal); await until(() => receiver.logged('looking on')); sender.stop(); receiver.stop(); } await settle(); expect(openSockets()).toEqual([]); expect(openPeers()).toEqual([]); expect(vi.getTimerCount()).toBe(0); }); it('tells why the peers could not connect, until the time is up', async () => { FakePeer.reachable = false; new FakeTracker(URLS[0]!); settings.trackers = [URLS[0]!]; 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.logged('answer via')); const neither = 'neither side has a public address, between different networks both sides need STUN'; vi.advanceTimersByTime(CONNECT_TIMEOUT); expect(sender.logs).toContain(`receiver did not connect: ${neither}`); expect(receiver.logs).toContain(`sender via ${URLS[0]} did not connect: ${neither}`); expect(sender.status()).toBe( `retry: could not connect to the receiver: ${neither}. Waiting for the receiver to try again`, ); vi.advanceTimersByTime(TRACKER_WAIT); await settle(); expect(sender.errors).toHaveLength(1); expect(sender.errors[0]).toMatch(new RegExp(`^no receiver connected until .+: ${neither}$`)); expect(receiver.errors[0]).toMatch(new RegExp(`^no sender connected until .+: ${neither}$`)); }); it("tells a code that can't be one right away", async () => { const receiver = side(); await expect(receiveViaTracker('abcdefghij', receiver.events, receiver.signal)).rejects.toThrow( 'a code has 11 letters and digits, check it', ); expect(FakeSocket.all).toEqual([]); }); });