import { type Download, downloadsReady, startDownload } from './download'; export const DEFAULT_TRACKERS = [ 'wss://tracker.pagequit.net', 'wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com', ]; export const DEFAULT_STUN_SERVERS = [ 'stun:stun.pagequit.net:3478', 'stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302', '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: // a new one goes on its list there. // Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody. // Read whenever a connection or tracker socket is created, so changes apply to the next one. export const settings = { stun: true, stunServers: [...DEFAULT_STUN_SERVERS], trackers: [...DEFAULT_TRACKERS], }; 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. export const WINDOW = 8 * 1024 * 1024; const ICE_GRACE = 300; const ICE_TIMEOUT = 5000; // A STUN server that reports no public address by then gets passed over, see stunChoice. const PROBE_TIMEOUT = 2000; // A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn. export const TRACKER_TIMEOUT = 10_000; // A tracker peer that got an answer but never opens the data channel gives up its turn after this, // e.g. one whose SDP has no usable candidates: Chromium never even fails its connection. The manual // sender gives up on the answer after it as well. export const CONNECT_TIMEOUT = 30_000; // A share, or a receiver looking for one, gives up after this without a download: nobody announces // all day for a code nobody uses. Until then both announce again on the interval the tracker names, // else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names. // 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. export const PBKDF2_ITERATIONS = 600_000; // 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; // Far beyond what a file system stores, but keeps an absurd name out of the page and the worker. export const MAX_NAME = 1024; export type Check = { local: string; remote: string; // Once the user compared the codes: confirm if they match, else reject. confirm: () => void; reject: () => void; }; // What a session is doing, see Events.status. export type Phase = 'start' | 'wait' | 'retry' | 'transfer' | 'done' | 'stopped'; export type Events = { log: (message: string) => void; // What the session is doing, a sentence for the user. start: it sets something up or connects, // wait: someone has to act, retry: an attempt failed and it tries again, the text says why. Then // transfer, and once it's over done or stopped. An error replaces it. status: (phase: Phase, text: string) => void; // Something the user has to act on, the session can't go on by itself. Not logged separately. error: (message: string) => void; // Called on both sides once connected by the manual exchange, and without a check when it ended // undecided. Tracker signaling has the code to prove the connection, nobody has to compare anything. check: (check?: Check) => void; // Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when // the transfer starts. progress: (read: number, size: number) => void; }; export type SendEvents = Events & { // Once a tracker share's TRACKER_WAIT passed: no further receiver finds it with the code. One // connected by then still gets its turn. expired: () => void; }; // The sender's file, offered once both sides confirmed the check. download() starts saving it. export type Incoming = { name: string; size: number; download: () => void }; export type ReceiveEvents = Events & { // Without a file when the sender left before the download started. incoming: (file?: Incoming) => void; }; // Every export runs one session until its signal aborts: then it closes the connections and tracker // sockets it opened, starts nothing new and calls no more events. A new session doesn't touch an old one. // Closes it once the session ends, right away if it already did. Closing it earlier lets go of it, else // the session would keep every connection a rejected or failed peer left behind until it ends. export function own void }>(signal: AbortSignal, resource: T) { const closeResource = resource.close.bind(resource); // Without the abort event, WebSocket.close() would take it for a close code and throw. const close = () => closeResource(); if (signal.aborted) close(); else signal.addEventListener('abort', close, { once: true }); resource.close = () => { signal.removeEventListener('abort', close); close(); }; return resource; } // Closing everything fires events of its own, none of them reaches the caller after the abort. export function live void>>(events: T, signal: AbortSignal) { return Object.fromEntries( Object.entries(events).map(([name, handler]) => [name, (...args: never[]) => signal.aborted || handler(...args)]), ) as T; } // Runs expire after ms unless closed before, cleared with the session. export function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) { const timer = setTimeout(() => { owned.close(); expire(); }, ms); const owned = own(signal, { close: () => clearTimeout(timer) }); return owned; } // Whether url reports a public address to a throwaway connection within PROBE_TIMEOUT. Not once stop // aborted, the connection closes right away then. async function probe(url: string, stop: AbortSignal) { const pc = new RTCPeerConnection({ iceServers: [{ urls: url }] }); let timeout: ReturnType | undefined; let abort = () => {}; try { // Without anything to negotiate nothing is gathered. pc.createDataChannel('probe'); const answered = new Promise((resolve) => { timeout = setTimeout(() => resolve(false), PROBE_TIMEOUT); abort = () => resolve(false); stop.addEventListener('abort', abort, { once: true }); pc.addEventListener('icecandidate', ({ candidate }) => candidate?.type === 'srflx' && resolve(true)); pc.addEventListener('icegatheringstatechange', () => pc.iceGatheringState === 'complete' && resolve(false)); }); await pc.setLocalDescription(); return await answered; } catch { return false; } finally { clearTimeout(timeout); stop.removeEventListener('abort', abort); pc.close(); } } // Each connection uses one STUN server, so only that one learns the address: the first in the list // that reports one. It stays for the page's lifetime, unless a connection gets no address from it, // then the next connection probes on from the server after it. A changed list starts over. None, or // none reporting an address, means connections without STUN. A device with a public address of its // own gets none reported (browsers drop it as redundant) and probes them all for every connection. // The page has one, see stun, a test makes its own with a probe of its own. export function stunChoice(answers = probe) { let current: ReturnType | undefined; // Where the next probe of the list with key starts, if not at its first server. let resume: { key: string; at: number } | undefined; // Probes list in order from start on, the ones before start last. function probeFrom(list: string[], start: number) { const key = list.join('\n'); const stop = new AbortController(); let at = start; let settled = false; let waiting = 0; const server = (async () => { for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) { // No further server is contacted once nobody waits, STUN was turned off or the list changed. if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return; if (await answers(list[at]!, stop.signal)) return list[at]; } })().finally(() => (settled = true)); const choice = { list, key, server, // Before it found one, the next probe goes on where this one stopped. stopped: false, // The server for a session's connection. Once no session waits for it any more, the probe stops. async wait(signal: AbortSignal) { if (signal.aborted) return; waiting++; const leave = () => { if (--waiting || settled) return; choice.stopped = true; resume = { key, at }; stop.abort(); }; signal.addEventListener('abort', leave, { once: true }); try { return await server; } finally { signal.removeEventListener('abort', leave); if (!signal.aborted) waiting--; } }, }; // E.g. offline, the next connection probes again. void server.then((url) => { if (!url && current === choice) current = undefined; }); return choice; } return { // The server for a connection of the session with signal, if any. server(signal: AbortSignal) { if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined); const key = settings.stunServers.join('\n'); if (current?.key !== key || current.stopped) { current = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0); resume = undefined; } return current.wait(signal); }, // A connection got no public address from url. async failed(url: string) { const choice = current; if (!choice || (await choice.server) !== url || current !== choice) return; resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length }; current = undefined; }, }; } const stun = stunChoice(); async function createPeerConnection(signal: AbortSignal) { const server = await stun.server(signal); return own(signal, new RTCPeerConnection({ iceServers: server ? [{ urls: server }] : [] })); } // Peers and trackers send JSON objects. Anything else, malformed or not an object, counts as nothing. // Whatever is read from one has to be checked, the any only saves the casts for that. // biome-ignore lint/suspicious/noExplicitAny: checked field by field, see above type Message = Record; export function parse(data: unknown): Message | undefined { if (typeof data !== 'string') return; try { const message = JSON.parse(data); return message && typeof message === 'object' ? message : undefined; } catch {} } // The manual codes are base64 SDP. Chats may wrap them, so whitespace is ignored. export function decode(code: string, type: 'offer' | 'answer') { try { return { type, sdp: atob(code.replace(/\s/g, '')) }; } catch { throw new Error(`not a valid ${type}, copy all of it`); } } function randomBinary(length: number) { return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length))); } export const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // The largest multiple of the alphabet's length a byte holds. The bytes above would make the first // characters likelier, they are dropped. const CODE_LIMIT = 256 - (256 % CODE_CHARS.length); // length of the 62 characters, each equally likely. export function randomCode(length: number) { let code = ''; while (code.length < length) for (const byte of crypto.getRandomValues(new Uint8Array(length))) if (byte < CODE_LIMIT && code.length < length) code += CODE_CHARS[byte % CODE_CHARS.length]; return code; } // Hours and minutes, the way the user's browser writes them. The time and an AM or PM keep together. export const formatTime = (time: number) => new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0'); // Tracker signaling salts with the clock: its windows of SALT_WINDOW, counted in UTC from 1970. The // last of a code's CODE_LENGTH characters is the window it was made in, mod the number of characters, // 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. export const SALT_WINDOW = 6 * 60_000; export const CODE_LENGTH = 11; const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW); // The window's start in UTC, then the own salt if there is one. Spaces around that would be a typo, // not a different salt. A blank one is a mistake, not the clock's: nobody with it would find the share. export function trackerSalt(at: number, own?: string) { const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16); if (own === undefined) return salt; if (!own.trim()) throw new Error('the own salt is empty'); return `${salt} ${own.trim()}`; } // A sender's new code and its salt. export function newCode(own?: string) { const at = clockWindow(Date.now()); return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) }; } // The salt of the code a receiver got, its window from half the characters before the clock's to half // after. Anything else can't be a code, a typo gets told right away instead of searched for. export function codeSalt(code: string, own?: string) { if (code.length !== CODE_LENGTH || [...code].some((char) => !CODE_CHARS.includes(char))) throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`); const now = clockWindow(Date.now()); const cycle = CODE_CHARS.length; const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle; return trackerSalt(now + (ahead < cycle / 2 ? ahead : ahead - cycle), own); } // The code and the salt are all both sides share. They give the tracker swarm, identified by a 20 // byte info_hash, and the key that proves the connection, see prove. Whoever sees the swarms, a // tracker or anyone scraping one, can test a guessed code against all of them at once. PBKDF2 makes // every guess cost what a share pays once (~50 ms). A salt known ahead lets the guesses be made ahead // too: a table from info_hash to code would let a tracker take over any share as it happens. The // 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. 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']); const bits = await crypto.subtle.deriveBits( { name: 'PBKDF2', hash: 'SHA-256', salt: text.encode(`hellcon ${salt.normalize('NFC')}`), iterations: PBKDF2_ITERATIONS, }, password, 256, ); const master = await crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits', 'deriveKey']); const expand = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: text.encode(info) }); const hash = await crypto.subtle.deriveBits(expand('swarm'), master, 160); const key = await crypto.subtle.deriveKey(expand('proof'), master, { name: 'HMAC', hash: 'SHA-256' }, false, [ 'sign', 'verify', ]); const sealing = await crypto.subtle.deriveKey(expand('signaling'), master, { name: 'AES-GCM', length: 256 }, false, [ 'encrypt', 'decrypt', ]); return { hash: String.fromCharCode(...new Uint8Array(hash)), key, sealing }; } // Tracker signaling carries the SDP sealed with the code: neither the trackers nor a peer that found // the swarm without the code learn the addresses in it, and nobody answers what they can't open. The // type is sealed along, an offer doesn't pass for an answer. Base64 of IV and ciphertext, in the // sdp field, so trackers relay it like any other. export async function seal(key: CryptoKey, type: 'offer' | 'answer', sdp: string) { const text = new TextEncoder(); const iv = crypto.getRandomValues(new Uint8Array(12)); const params = { name: 'AES-GCM', iv, additionalData: text.encode(type) }; const sealed = await crypto.subtle.encrypt(params, key, text.encode(sdp)); return btoa(String.fromCharCode(...iv, ...new Uint8Array(sealed))); } // The SDP, unless it wasn't sealed with the code as that type. export async function unseal(key: CryptoKey, type: 'offer' | 'answer', sealed: string) { // atob throws on what isn't base64, decrypt on anything else. try { const bytes = Uint8Array.from(atob(sealed), (char) => char.charCodeAt(0)); const params = { name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: new TextEncoder().encode(type) }; return new TextDecoder().decode(await crypto.subtle.decrypt(params, key, bytes.subarray(12))); } catch {} } function announce(ws: WebSocket, hash: string, peerId: string, params: object) { ws.send( JSON.stringify({ action: 'announce', info_hash: hash, peer_id: peerId, numwant: 0, uploaded: 0, downloaded: 0, ...params, }), ); } // The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after // the STUN server answered or timed out (40 s in Chromium for a silent one): its first address plus a // short grace for the other IP family is enough. Without one the STUN server stopped answering, the // next connection gets another one. async function gatherIce(pc: RTCPeerConnection) { if (pc.iceGatheringState === 'complete') return; let reported = false; await new Promise((resolve) => { const timeout = setTimeout(resolve, ICE_TIMEOUT); const done = () => { clearTimeout(timeout); resolve(); }; pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') done(); }); pc.addEventListener('icecandidate', ({ candidate }) => { if (candidate?.type !== 'srflx') return; reported = true; setTimeout(done, ICE_GRACE); }); }); const [server] = pc.getConfiguration().iceServers ?? []; if (server && !reported && pc.signalingState !== 'closed') void stun.failed([server.urls].flat()[0]!); } // Why pc didn't connect, if a missing public address explains it: a side without one from STUN offers // only local addresses, enough on the same network or VPN. peer names the other side. A device with // a public address of its own offers none either, see stunChoice, so it's a hint, not a diagnosis. export function stunHint(pc: RTCPeerConnection, peer: string) { const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? ''); const local = offersPublic(pc.localDescription); const remote = offersPublic(pc.remoteDescription); if (local && remote) return; const missing = local ? `the ${peer} has no public address` : remote ? 'this side has no public address' : 'neither side has a public address'; return `${missing}, between different networks both sides need STUN`; } // Why a tracker peer didn't connect when stunHint has no explanation: both sides offered a public // address, so something in between doesn't let them reach each other. A guess, but the usual one. const BLOCKED = 'a network in between, e.g. a VPN or firewall, may block direct connections'; const host = (url: string) => URL.parse(url)?.host || url; // 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. export function securityCheck(pc: RTCPeerConnection) { const short = (sdp = '') => 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) }; } // Every fingerprint the SDP names, in full: one added beside the real one changes the result too. // Browsers may move them between session and media level, so each counts once. export const fingerprints = (sdp: string) => [...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort(); // The security check of tracker signaling, resolves once the peer proved the code. Each side signs its // role, its SDP type, and the fingerprints of both certificates as it sees them. The peer checks that // against its own view. An interposer has its own certificate towards each side and can't sign for it // without the code, neither can a peer that found the swarm some other way. One that sends no proof // within PROOF_TIMEOUT or a wrong one ends the connection. export function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) { const local = pc.localDescription!; const remote = pc.remoteDescription!; const statement = (type: string, own: string, peer: string) => new TextEncoder().encode(JSON.stringify([type, fingerprints(own), fingerprints(peer)])); const send = async () => { const proof = await crypto.subtle.sign('HMAC', key, statement(local.type, local.sdp, remote.sdp)); if (channel.readyState !== 'open') return; channel.send(JSON.stringify({ proof: btoa(String.fromCharCode(...new Uint8Array(proof))) })); }; if (channel.readyState === 'open') void send(); else channel.addEventListener('open', () => void send(), { once: true }); return new Promise((resolve) => { const timeout = setTimeout(() => end('the peer proved no code'), PROOF_TIMEOUT); const check = async (event: MessageEvent) => { const proof = parse(event.data)?.proof; if (typeof proof !== 'string') return; // Registered before sendFile and receiveFile, which must not see it: Chromium can verify before // the next listener runs, the receiver would take the proof for the sender's offer then. event.stopImmediatePropagation(); channel.removeEventListener('message', check); clearTimeout(timeout); // atob throws on what isn't base64. let valid = false; try { const signature = Uint8Array.from(atob(proof), (char) => char.charCodeAt(0)); valid = await crypto.subtle.verify('HMAC', key, signature, statement(remote.type, remote.sdp, local.sdp)); } catch {} if (valid) resolve(); else end('security check failed, the peer does not know the code'); }; channel.addEventListener('message', check); }); } // checked resolves once the security check passed: by the user confirming the codes, or with a key // once the peer proved the code. 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 sides to // pass, a failed check, a peer that left or end closes the connection and calls next: tracker // signaling goes on with another peer. Without next, as in the manual exchange, the session is over // and the reason is an error. From start on, sendFile and receiveFile handle a loss. export type Handshake = { checked: Promise; start: () => void; end: (reason: string) => void }; function connected( pc: RTCPeerConnection, channel: RTCDataChannel, via: string, peer: string, events: Events, next?: (reason: string) => void, key?: CryptoKey, ): Handshake { events.log(`connected via ${via}`); events.log('waiting for the security check'); if (key) events.status('start', 'Connected, checking the code'); else events.status('wait', `Compare the security codes above with the ${peer}`); let done = false; const end = (reason: string) => { if (done) return; done = true; events.check(); pc.close(); if (!next) return events.error(reason); events.log(reason); next(reason); }; // A vanished peer only closes the channel in Firefox, Chromium just fails the connection. channel.addEventListener('close', () => end(`the ${peer} left before the transfer`)); pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'failed') end(`the ${peer} left before the transfer`); }); return { checked: key ? prove(pc, channel, key, end).then(() => events.log('security check passed')) : new Promise((resolve) => events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }), ), start: () => (done = true), end, }; } // Offers the file once checked resolved and the receiver confirmed its own check with { ok }, sends // it once the receiver started the download with { start }. Then it answers with { read } progress, // { done } once the download manager read the last byte, or { error } when its download was // cancelled or failed. Any other message, or one out of turn, is ignored. Every way out of the // transfer closes the connection. export async function sendFile( pc: RTCPeerConnection, channel: RTCDataChannel, file: File, events: Events, handshake: Handshake, signal: AbortSignal, ) { let read = 0; let accepted = false; let offered = false; let sending = false; let stopped = false; // Every event the send loop can wait for calls this. let wake = () => {}; const stop = (error?: string) => { if (stopped) return; stopped = true; signal.removeEventListener('abort', abort); if (error) events.error(error); pc.close(); wake(); }; channel.onmessage = ({ data }) => { const message = parse(data); if (!offered) accepted ||= message?.ok === true; else if (!sending) sending = message?.start === true; else if (Number.isSafeInteger(message?.read) && message!.read > read && message!.read <= file.size) { read = message!.read; events.progress(read, file.size); } else if (message?.done === true && !stopped) { events.log('delivered'); events.status('done', 'Delivered'); events.progress(file.size, file.size); stop(); } else if (typeof message?.error === 'string') { stop(`receiver stopped: ${message.error.slice(0, 200)}`); } wake(); }; // 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()); const abort = () => stop(); signal.addEventListener('abort', abort, { once: true }); // Also false once the channel closes, its close event may still be on the way. const open = () => !stopped && channel.readyState === 'open'; if (channel.readyState === 'connecting') { await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true })); } await handshake.checked; if (!accepted && open()) { events.log("waiting for the receiver's security check"); events.status('wait', "Waiting for the receiver's security check"); } while (open() && !accepted) await new Promise((resolve) => (wake = resolve)); if (!open()) return; channel.send(JSON.stringify({ name: file.name, size: file.size })); offered = true; events.log(`offered ${file.name} (${file.size} bytes)`); events.log('waiting for the receiver to download'); events.status('wait', 'Waiting for the receiver to download'); while (open() && !sending) await new Promise((resolve) => (wake = resolve)); if (!open()) return; handshake.start(); events.log(`sending ${file.name}`); events.status('transfer', 'Sending'); events.progress(0, file.size); channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2; for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) { while (open() && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) { await new Promise((resolve) => (wake = resolve)); } // E.g. the file was changed or deleted since it was picked. const chunk = await file .slice(offset, offset + CHUNK_SIZE) .arrayBuffer() .catch(() => undefined); if (!chunk) return stop(`could not read ${file.name} anymore`); if (!open()) return; channel.send(chunk); } events.log('sent'); if (open()) events.status('transfer', 'Sent, waiting for the receiver to save the rest'); } // Accepts nothing until checked resolved, then tells the sender with { ok }. Its file is offered to // the user, chunks are accepted only once they started the download. Nothing the sender sends is // trusted: a malformed offer ends the connection, more bytes than offered or beyond the window fail // the download. Once it ended, the connection closes. startDownload saves it, see src/download.ts. export function receiveFile( pc: RTCPeerConnection, channel: RTCDataChannel, events: ReceiveEvents, handshake: Handshake, signal: AbortSignal, ) { let meta: { name: string; size: number } | undefined; let saving: Download | undefined; let received = 0; // By the download manager. The rest of received is held in this page and the worker. let read = 0; let confirmed = false; let downloading = false; let complete = false; let ended = false; // To the sender, see sendFile. const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message)); // A data channel closes only after sending what it buffered, so the last reply still arrives. channel.addEventListener('close', () => pc.close()); function fail(reason: string) { if (ended) return; saving?.fail(reason); failed(reason); } // Also when the download failed on its own, no telling it then. function failed(reason: string) { if (ended) return; ended = true; reply({ error: reason }); channel.close(); events.error(`download failed: ${reason}`); } function startSaving(file: { name: string; size: number }) { saving = startDownload(file, { read: (bytes) => { read = bytes; events.progress(read, file.size); reply({ read }); }, finished: () => { events.log('download complete'); events.status('done', 'Download complete'); events.progress(file.size, file.size); reply({ done: true }); ended = true; channel.close(); }, cancelled: () => { events.log('download cancelled'); events.status('stopped', 'Download cancelled'); reply({ error: 'download cancelled' }); ended = true; channel.close(); }, failed, }); } void handshake.checked.then(() => { confirmed = true; reply({ ok: true }); events.log('waiting for the sender'); events.status('wait', 'Waiting for the sender'); }); function receivedAll() { complete = true; saving!.end(); events.log('received'); } function download() { if (downloading || ended || signal.aborted) return; downloading = true; // Until then closing the connection is all there is to stop, the session does that. Only one // download per session, so this never piles up. signal.addEventListener('abort', () => fail('stopped'), { once: true }); handshake.start(); events.log(`receiving ${meta!.name}`); events.status('transfer', 'Receiving'); events.progress(0, meta!.size); startSaving(meta!); reply({ start: true }); if (!meta!.size) receivedAll(); } channel.binaryType = 'arraybuffer'; channel.onmessage = ({ data }) => { if (ended || !confirmed) return; if (typeof data === 'string') { if (meta) return; const { name, size } = parse(data) ?? {}; if (typeof name !== 'string' || name.length > MAX_NAME || !Number.isSafeInteger(size) || size < 0) { return handshake.end('the sender offered no valid file'); } meta = { name, size }; events.log(`offered ${name} (${size} bytes)`); events.status('wait', 'Click Download to save the file'); events.incoming({ name, size, download }); } else if (downloading && !complete) { received += data.byteLength; if (received > meta!.size) return fail('the sender sent more than it offered'); // sendFile never has more than WINDOW unread plus the chunk it just sent. if (received - read > WINDOW + CHUNK_SIZE) return fail('the sender ignored the flow control'); saving!.write(data); if (received === meta!.size) receivedAll(); } }; // Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished // peer only closes the channel in Firefox, Chromium just fails the connection. Before the download // started, connected reports it and only the offer goes. function lost() { if (!meta || ended) return; if (!downloading) events.incoming(); else if (!complete) fail('connection lost'); } channel.addEventListener('close', lost); pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost()); } // The manual exchange has nobody else to try: a connection that fails before the data channel opened, // e.g. after a wrong answer or between networks without STUN, ends the session. Chromium never fails // one without usable addresses, so the returned wait also ends it once ms passed without connecting, // counted from when the peer can connect. peer names the other side. function failUnconnected( pc: RTCPeerConnection, opened: () => boolean, events: Events, signal: AbortSignal, peer: string, ) { let expiry: { close: () => void } | undefined; const fail = () => { expiry?.close(); if (opened() || pc.signalingState === 'closed') return; const hint = stunHint(pc, peer); pc.close(); events.error(hint ? `could not connect: ${hint}` : 'could not connect, check the codes'); }; pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'connected') expiry?.close(); if (pc.connectionState === 'failed') fail(); }); return (ms: number) => { expiry = deadline(signal, fail, ms); }; } // Manual signaling: the SDP itself is the code, exchanged over any channel the users trust. // The sender offers, the receiver answers, no tracker involved. export async function createOffer(file: File, events: Events, signal: AbortSignal) { events = live(events, signal); events.status('start', 'Creating the offer'); const pc = await createPeerConnection(signal); const channel = pc.createDataChannel('file'); 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'); await pc.setLocalDescription(); await gatherIce(pc); events.status('wait', 'Send the offer to the receiver and paste their answer below'); return { offer: btoa(pc.localDescription!.sdp), // Rejects with a message for the user. After a wrong answer the offer is still good for the right one. accept: async (answer: string) => { const description = decode(answer, 'answer'); if (pc.signalingState === 'closed') throw new Error('this offer is used up, create a new one'); // Already connecting with an earlier answer. if (pc.signalingState !== 'have-local-offer') return; await pc.setRemoteDescription(description).catch(() => { throw new Error('not a valid answer to this offer, copy all of it'); }); events.status('start', 'Connecting to the receiver'); wait(CONNECT_TIMEOUT); }, }; } export async function answerOffer(offer: string, events: ReceiveEvents, signal: AbortSignal) { events = live(events, signal); const description = decode(offer, 'offer'); events.status('start', 'Creating the answer'); await downloadsReady(); const pc = await createPeerConnection(signal); let opened = false; pc.ondatachannel = ({ channel }) => { // The sender's file channel, anything more is none of ours. if (opened) return; opened = true; receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', 'sender', events), signal); }; const wait = failUnconnected(pc, () => opened, events, signal, 'sender'); await pc.setRemoteDescription(description).catch(() => { pc.close(); throw new Error('not a valid offer, copy all of it'); }); await pc.setLocalDescription(); await gatherIce(pc); wait(TRACKER_WAIT); events.status('wait', 'Send the answer back to the sender, it connects once it has it'); return btoa(pc.localDescription!.sdp); } // A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason // before anything else rejects the announcement, the tracker is no use then and its socket closes, a // later one only concerns that message and is logged. message may be async, the next message doesn't // wait for it. lost runs once it closed without close() being called: unreachable, lost, rejected or // without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names. export function trackerSocket( url: string, signal: AbortSignal, events: Events, message: (msg: Message) => void | Promise, lost: () => void, again: () => void, ) { const ws = new WebSocket(url); let opened = false; let accepted = false; let closed = false; let reannounce: ReturnType | undefined; const end = (reason: string) => { if (closed) return; // Already closed unless rejected or silent, this only lets go of it. tracker.close(); events.log(reason); lost(); }; const timeout = setTimeout(() => end(opened ? `${url} did not answer` : `${url} unreachable`), TRACKER_TIMEOUT); // The session owns the timers too: a socket still closing after the abort gets no announce. const tracker = own(signal, { ws, // What the tracker answered, if it rejected the announcement. rejected: undefined as string | undefined, alive: () => !closed, close: () => { if (closed) return; closed = true; clearTimeout(timeout); clearInterval(reannounce); ws.close(); }, }); ws.addEventListener('open', () => (opened = true)); ws.addEventListener('message', ({ data }) => { const msg = parse(data); const failure = msg?.['failure reason']; if (typeof failure !== 'string') { if (!msg) return; accepted = true; clearTimeout(timeout); // Seconds, JSON may give Infinity for a huge one. Beyond TRACKER_WAIT it would never come. if (!reannounce && !closed && typeof msg.interval === 'number') { reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000))); } return void message(msg); } if (accepted) return events.log(`${url}: ${failure}`); tracker.rejected = `${url}: ${failure.slice(0, 200)}`; end(`rejected by ${tracker.rejected}`); }); ws.addEventListener('close', () => end(opened ? `lost ${url}` : `${url} unreachable`)); return tracker; } type Tracker = ReturnType; // Once none of the trackers is left: what the user can do about it, and why if any rejected. export function noTracker(trackers: (Tracker | undefined)[]) { const rejected = trackers.flatMap((tracker) => tracker?.rejected ?? []); const reason = rejected.length ? `no tracker accepted it (${rejected.join('; ')})` : 'no tracker reachable'; return `${reason}, check the list under Servers and try again`; } // Tracker signaling (optional): sender joins the swarm on the first tracker that accepts it, so only // that one learns about the share, and moves on to the next only once it lost that one. It answers one // offer at a time. An offer not sealed with the code gets no turn, a peer that found the swarm without // it doesn't even learn the sender's address. Until a receiver proved the code, the next one gets its // turn: an offer that can't be answered, never connects or proves nothing doesn't end the share. Once // the download started the share is used up, the tracker goes. After TRACKER_WAIT it goes as well, a // receiver connected by then still gets its turn. Resolves with the code and when it ends. export async function sendViaTracker(file: File, events: SendEvents, signal: AbortSignal, ownSalt?: string) { events = live(events, signal); events.status('start', 'Creating the code'); const until = Date.now() + TRACKER_WAIT; const { code, salt } = newCode(ownSalt); const { hash, key, sealing } = await secrets(code, salt); const peerId = randomBinary(20); const urls = [...settings.trackers]; // Every one tried so far, only the last can be alive. const trackers: Tracker[] = []; let busy = false; let shared = false; let expired = false; // The latest offer that came while busy, answered once that peer is out. let waiting: (() => Promise) | undefined; // Why the last receiver that answered didn't connect. let hint: string | undefined; // Why the last receiver's turn ended without a transfer, shown until the next one connects. let failure: string | undefined; // Receivers answered, a failed one usually tries again right away. let attempts = 0; const waitForReceiver = () => failure ? events.status('retry', `${failure}. Waiting for the receiver to try again`) : events.status('wait', 'Waiting for the receiver'); // Without a tracker no further receiver can find the share. const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive()); const nobody = () => hint ? `no receiver connected until ${formatTime(until)}: ${hint}` : `nobody received the file until ${formatTime(until)}, share it again`; const expiry = deadline( signal, () => { expired = true; events.expired(); for (const tracker of trackers) tracker.close(); if (stranded()) events.error(nobody()); }, until - Date.now(), ); // Once stranded the share is over. const end = (reason: string) => { expiry.close(); events.error(reason); }; // reason: why the receiver's turn ended, unless it was no receiver to speak of. function next(reason?: string) { busy = false; if (reason) failure = reason; if (signal.aborted) return; if (stranded()) return end(expired ? nobody() : noTracker(trackers)); events.log('waiting for the next receiver'); waitForReceiver(); const offer = waiting; waiting = undefined; void offer?.(); } async function answer( ws: WebSocket, url: string, msg: { offer: { sdp: string }; peer_id: string; offer_id: string }, ) { busy = true; attempts++; events.log(`offer via ${url}`); if (failure) events.status('retry', `${failure}. Trying again, attempt ${attempts}`); else events.status('start', 'Receiver found, connecting'); const pc = await createPeerConnection(signal); // Until the data channel opens this ends the turn, from then on connected does. let settled = false; // Shown until the next receiver connects, an unusable offer doesn't concern the user. let problem: string | undefined; const giveUp = (reason: string) => { if (settled) return; settled = true; clearTimeout(timeout); events.log(reason); pc.close(); next(problem); }; const unconnected = () => { if (settled) return; hint = stunHint(pc, 'receiver') ?? BLOCKED; problem = `could not connect to the receiver: ${hint}`; giveUp(`receiver did not connect: ${hint}`); }; const timeout = setTimeout(unconnected, CONNECT_TIMEOUT); pc.ondatachannel = ({ channel }) => { if (settled) return; settled = true; clearTimeout(timeout); const handshake = connected(pc, channel, url, 'receiver', events, next, key); const start = () => { handshake.start(); shared = true; waiting = undefined; expiry.close(); for (const tracker of trackers) tracker.close(); }; void sendFile(pc, channel, file, events, { ...handshake, start }, signal); }; pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'failed') unconnected(); }); let sdp: string; try { await pc.setRemoteDescription({ type: 'offer', sdp: msg.offer.sdp }); await pc.setLocalDescription(); await gatherIce(pc); sdp = await seal(sealing, 'answer', pc.localDescription!.sdp); } catch (error) { return giveUp(`unusable offer via ${url}: ${error}`); } if (settled) return; announce(ws, hash, peerId, { left: 0, to_peer_id: msg.peer_id, offer_id: msg.offer_id, answer: { type: 'answer', sdp }, }); } // The tracker at urls[i]. Receivers that come later walk on to the next one too, see receiveViaTracker. function join(i: number) { const url = urls[i]!; // A receiver's turn goes on without the tracker. if (!busy) events.status('start', `Connecting to ${host(url)}`); const tracker = trackerSocket( url, signal, events, async (msg) => { // What a tracker relays from a receiver, anything else is ignored. if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return; if (typeof msg.offer_id !== 'string') return; const sdp = await unseal(sealing, 'offer', msg.offer.sdp); // Meanwhile the share may have been used up, expired or ended, its tracker closed then. if (signal.aborted || !tracker.alive()) return; if (sdp === undefined) return events.log(`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); else void answer(tracker.ws, url, offer); }, () => { if (signal.aborted) return; if (i + 1 < urls.length) join(i + 1); else if (stranded()) end(noTracker(trackers)); }, () => announce(tracker.ws, hash, peerId, { left: 0 }), ); tracker.ws.onopen = () => { announce(tracker.ws, hash, peerId, { left: 0, event: 'started' }); events.log(`waiting on ${url}`); if (!busy) waitForReceiver(); }; trackers.push(tracker); } join(0); return { code, until }; } // Receiver walks the trackers in order with one offer each, until one has a seeder: the sender, which // announced before anyone had the code. It moves on from a tracker without one, unreachable or lost, // and stays where the sender is. A wrong code still walks them all. 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, or come to a tracker it passed. An answer not sealed with // the code is ignored, the offer waits for the real one. One that can't be used or never connects is // replaced right away. Once the download started, every other offer and tracker socket goes. After // TRACKER_WAIT no offer is made or kept any more, a sender connected by then still gets its turn. export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal, ownSalt?: string) { events = live(events, signal); events.status('start', 'Looking for the sender'); // From the click, getting ready may take a moment. const salt = codeSalt(code.trim(), ownSalt); const until = Date.now() + TRACKER_WAIT; await downloadsReady(); const { hash, key, sealing } = await secrets(code.trim(), salt); if (signal.aborted) return; const peerId = randomBinary(20); const urls = [...settings.trackers]; // The current offer per tracker by its place in urls, its connection once made, its socket only // until the answer came. lost: the socket closed before that. empty: its tracker has no seeder. type Offer = { pc?: RTCPeerConnection; tracker?: Tracker; lost: boolean; empty?: boolean }; const offers = new Map(); let isConnected = false; let started = false; let expired = false; // Why the last sender that answered didn't connect. let hint: string | undefined; // Why the last connection to the sender failed, shown until the next one connects. let failure: string | undefined; // Answers from the sender, after a failure it answers the replacement right away. let attempts = 0; // Every tracker reported no sender, the status says so until one has it again. let noSender = false; const looking = (text: string) => { if (isConnected || started) return; if (failure) events.status('retry', `${failure}. Looking again`); else events.status('start', text); }; // No sender with this code can come after the end, a new code can. 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`; // Without a sender connected the search is over, every offer goes. const end = (reason: string) => { expiry.close(); for (const { pc, tracker } of offers.values()) { tracker?.close(); pc?.close(); } events.error(reason); }; // A connected sender keeps its connection, the other offers wait for next or start. const expiry = deadline( signal, () => { expired = true; if (!isConnected) return end(nobody()); for (const { tracker } of offers.values()) tracker?.close(); }, until - Date.now(), ); const next = (reason: string) => { isConnected = false; failure = reason; if (signal.aborted) return; if (expired) return end(nobody()); events.log('looking again'); looking('Looking for the sender'); for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i); }; // The tracker after urls[i], unless it has an offer already. const walk = (i: number) => { if (signal.aborted || started || expired || i + 1 >= urls.length || offers.has(i + 1)) return; void offer(i + 1); }; async function offer(i: number) { const url = urls[i]!; const entry: Offer = { lost: false }; offers.set(i, entry); const pc = await createPeerConnection(signal); 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 offerId = randomBinary(20); let timeout: ReturnType | undefined; // Unless another offer is connected, next replaces this one then. const retry = (reason: string) => { clearTimeout(timeout); if (pc.signalingState === 'closed') return; events.log(reason); pc.close(); if (!isConnected && !started && !signal.aborted && !expired) void offer(i); }; const unconnected = () => { if (pc.signalingState === 'closed') return; hint = stunHint(pc, 'sender') ?? BLOCKED; failure = `could not connect to the sender: ${hint}`; retry(`sender via ${url} did not connect: ${hint}`); looking('Looking for the sender'); }; channel.onopen = () => { clearTimeout(timeout); if (isConnected || started) return pc.close(); isConnected = true; const handshake = connected(pc, channel, url, 'sender', events, next, key); const start = () => { handshake.start(); started = true; expiry.close(); for (const other of offers.values()) { other.tracker?.close(); if (other.pc !== pc) other.pc?.close(); } }; receiveFile(pc, channel, events, { ...handshake, start }, signal); }; pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'failed' && channel.readyState === 'connecting') unconnected(); }); pc.setLocalDescription() .then(() => gatherIce(pc)) .then(() => seal(sealing, 'offer', pc.localDescription!.sdp)) .then((sdp) => { if (pc.signalingState === 'closed' || expired) return; // Again with the same offer on the interval, a busy sender may have dropped it meanwhile. const hello = (event?: string) => announce(tracker.ws, hash, peerId, { left: 1, numwant: 1, event, offers: [{ offer_id: offerId, offer: { type: 'offer', sdp } }], }); const tracker = trackerSocket( url, signal, events, async (msg) => { // The tracker's reply to an announcement, complete counts the seeders. Without one the // sender isn't here, or no longer. if (msg.answer === undefined && msg.offer === undefined) { entry.empty = !(msg.complete > 0); if (entry.empty) walk(i); // Every tracker asked and none has it: a wrong code, or the share is over. A sender that // shows up later may be busy with another receiver, its answer can take a while. const everywhere = [...offers.values()].every((other) => other.lost || other.empty); const none = offers.size === urls.length && everywhere; if (none !== noSender && !isConnected && !started) { if (none) events.status( 'retry', `No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'}, still looking`, ); else if (failure) events.status('retry', `${failure}. Looking again`); else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`); } noSender = none; return; } if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return; const answer = await unseal(sealing, 'answer', msg.answer.sdp); // Only one answer per offer, a replacement opens its own socket. Meanwhile it may have // come, or the search ended, its socket closed then. if (pc.signalingState === 'closed' || !tracker.alive()) return; if (answer === undefined) return events.log(`answer without the code via ${url}`); events.log(`answer via ${url}`); attempts++; noSender = false; if (!isConnected && !started) { if (failure) events.status('retry', `${failure}. Trying again, attempt ${attempts}`); else events.status('start', 'Sender found, connecting'); } tracker.close(); timeout = setTimeout(unconnected, CONNECT_TIMEOUT); pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`)); }, () => { entry.lost = true; walk(i); if (!isConnected && !started && [...offers.values()].every((other) => other.lost)) { end(noTracker([...offers.values()].map((other) => other.tracker))); } }, () => hello(), ); entry.tracker = tracker; tracker.ws.onopen = () => { hello('started'); events.log(`looking on ${url}`); looking(`Looking for the sender on ${host(url)}`); }; }) // Closed in the meantime, nothing to report then. .catch((error) => pc.signalingState === 'closed' || events.error(String(error))); } void offer(0); }