import { createApp } from 'vue'; import App from './App.vue'; import './style.css'; export const TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com']; export const STUN_SERVERS = [ 'stun:stun.pagequit.net:3478', 'stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302', 'stun:stun.nextcloud.com:443', ]; // Without STUN only local addresses are offered: works on the same network or VPN, contacts nobody. export const settings = { stun: true }; const CHUNK_SIZE = 16 * 1024; 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. const WINDOW = 8 * 1024 * 1024; // Firefox stops a service worker after 30 s without events, also in the middle of a download, and // then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings. const KEEPALIVE = 10_000; const ICE_GRACE = 300; const ICE_TIMEOUT = 5000; export type Check = { local: string; remote: string }; export type Events = { log: (message: string) => void; // Called on both sides, confirm once the user compared the codes and they match. check: (check: Check, confirm: () => void) => void; }; function createPeerConnection() { return new RTCPeerConnection({ iceServers: settings.stun ? [{ urls: STUN_SERVERS }] : [] }); } function randomBinary(length: number) { return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length))); } function randomCode() { return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, '0'); } // The tracker swarm is identified by a 20 byte info_hash, derived from the shared code. async function infoHash(code: string) { const digest = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`hellcon:${code}`)); return String.fromCharCode(...new Uint8Array(digest)); } 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 // every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report // the same public address: the first one plus a short grace for the other IP family is enough. async function gatherIce(pc: RTCPeerConnection) { if (pc.iceGatheringState === 'complete') return; 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') setTimeout(done, ICE_GRACE); }); }); } // Anti-MITM check: the first 5 bytes of both DTLS certificate fingerprints. My local code must // equal the peer's remote code and vice versa, otherwise someone interposed on the signaling. function securityCheck(pc: RTCPeerConnection): Check { const short = (sdp = '') => sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 5).join(' ') ?? '?'; return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) }; } // Resolves once the user compared the codes. Both sides wait for it: the sender sends nothing to a man // in the middle, the receiver accepts no file from one. function connected(pc: RTCPeerConnection, via: string, events: Events) { events.log(`connected via ${via}`); events.log('waiting for the security check'); return new Promise((resolve) => events.check(securityCheck(pc), resolve)); } // Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers // with { read } progress, { done } once the download manager read the last byte, or { error } when // its download was cancelled or failed. async function sendFile( pc: RTCPeerConnection, channel: RTCDataChannel, file: File, events: Events, checked: Promise, ) { if (channel.readyState !== 'open') { await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true })); } let read = 0; let accepted = false; let sending = false; let stopped = false; // Every event the send loop can wait for calls this. let wake = () => {}; const stop = (message: string) => { if (stopped) return; stopped = true; events.log(message); wake(); }; channel.onmessage = ({ data }) => { const message = JSON.parse(data); if (message.ok) accepted = true; // Before that, nothing else can come from a receiver that passed its check. else if (!sending) return; if (message.read) read = message.read; if (message.done) { events.log('delivered'); // Finished, a later close is no loss. stopped = true; } if (message.error) stop(`receiver stopped: ${message.error}`); wake(); }; // A vanished peer only closes the channel in Firefox, Chromium just fails the connection. channel.addEventListener('close', () => stop('connection lost')); pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && stop('connection lost')); channel.addEventListener('bufferedamountlow', () => wake()); await checked; if (!accepted && !stopped) events.log("waiting for the receiver's security check"); while (!stopped && !accepted) await new Promise((resolve) => (wake = resolve)); if (stopped) return; sending = true; events.log(`sending ${file.name} (${file.size} bytes)`); channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2; channel.send(JSON.stringify({ name: file.name, size: file.size })); for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) { while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) { await new Promise((resolve) => (wake = resolve)); } const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer(); if (stopped) return; channel.send(chunk); } events.log('sent'); } // Received files are streamed into the browser's download manager by public/sw.js, so a file never // has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests. const downloads = registerDownloads(); // Only the first visit has to wait here, updates are picked up per transfer by holdWorker. async function registerDownloads() { const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' }); const pending = registration.installing ?? registration.waiting; if (!registration.active && pending) { await new Promise((resolve) => pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)), ); } if (!registration.active) throw new Error('service worker did not activate'); } // Awaited before receiving starts, so a browser without service workers fails before connecting. function downloadsReady(events: Events) { return downloads.catch((error) => { events.log(`downloads unavailable: ${error}`); throw error; }); } // A hidden page in the service worker's scope, open for the whole transfer. The worker controlling // it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that // worker in the middle of the download. async function holdWorker() { await downloads; const frame = document.createElement('iframe'); frame.hidden = true; frame.src = 'download/'; document.body.append(frame); await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true })); const worker = frame.contentWindow!.navigator.serviceWorker.controller; if (!worker) { frame.remove(); throw new Error('service worker did not take over'); } return { frame, worker }; } // Accepts nothing until checked resolved, then tells the sender with { ok }. function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, checked: Promise) { const id = crypto.randomUUID(); const frames: HTMLIFrameElement[] = []; let meta: { name: string; size: number } | undefined; let received = 0; let confirmed = false; let ended = false; // Chunks can arrive before the worker is held, chaining every post on this keeps them in order. let worker: Promise = Promise.resolve(); const post = (message: object, transfer: Transferable[] = []) => worker.then((worker) => worker?.postMessage({ id, ...message }, transfer)); // To the sender, see sendFile. const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message)); let keepalive: ReturnType | undefined; // Releases the worker, so a waiting update can take over. function release() { clearInterval(keepalive); for (const frame of frames) frame.remove(); } // The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the // download running instead of failing it. function fail(reason: string) { if (ended) return; ended = true; post({ error: reason }); reply({ error: reason }); events.log(`download failed: ${reason}`); } function startDownload() { worker = holdWorker().then(({ frame, worker }) => { frames.push(frame); keepalive = setInterval(() => post({ ping: true }), KEEPALIVE); // Only if something else than an update stops it, e.g. clearing the site data. It can't answer. worker.addEventListener('statechange', () => { if (worker.state !== 'redundant') return; fail('service worker stopped'); release(); }); const { port1, port2 } = new MessageChannel(); port1.onmessage = ({ data }) => { if (typeof data === 'number') return reply({ read: data }); if (data === 'ready' && !ended) { // A navigation, not fetch(): only navigations hand the response to the download manager. const download = document.createElement('iframe'); download.hidden = true; download.src = `download/${id}`; document.body.append(download); frames.push(download); return; } if (data === 'finished') { events.log('download complete'); reply({ done: true }); } if (data === 'cancelled' && !ended) { events.log('download cancelled'); reply({ error: 'download cancelled' }); } ended = true; release(); }; worker.postMessage({ id, ...meta }, [port2]); return worker; }, (error) => fail(String(error))); } checked.then(() => { confirmed = true; reply({ ok: true }); events.log('waiting for the sender'); }); channel.binaryType = 'arraybuffer'; channel.onmessage = ({ data }) => { if (ended || !confirmed) return; if (typeof data === 'string') { meta = JSON.parse(data); events.log(`receiving ${meta!.name} (${meta!.size} bytes)`); startDownload(); } else { received += data.byteLength; post({ chunk: data }, [data]); } if (meta && received === meta.size) { post({ done: true }); events.log('received'); } }; // 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. function lost() { if (meta && received < meta.size) fail('connection lost'); } channel.addEventListener('close', lost); pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost()); } // 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) { const pc = createPeerConnection(); const channel = pc.createDataChannel('file'); channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, 'manual exchange', events)); await pc.setLocalDescription(); await gatherIce(pc); return { offer: btoa(pc.localDescription!.sdp), accept: (answer: string) => pc.setRemoteDescription({ type: 'answer', sdp: atob(answer.trim()) }), }; } export async function answerOffer(offer: string, events: Events) { await downloadsReady(events); const pc = createPeerConnection(); pc.ondatachannel = ({ channel }) => receiveFile(pc, channel, events, connected(pc, 'manual exchange', events)); await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) }); await pc.setLocalDescription(); await gatherIce(pc); return btoa(pc.localDescription!.sdp); } // Tracker signaling (optional): sender joins the swarm on every tracker and answers the first offer. export async function sendViaTracker(file: File, events: Events) { const code = randomCode(); const hash = await infoHash(code); const peerId = randomBinary(20); let pc: RTCPeerConnection | undefined; for (const url of TRACKERS) { const ws = new WebSocket(url); ws.onopen = () => { announce(ws, hash, peerId, { left: 0, event: 'started' }); events.log(`waiting on ${url}`); }; ws.onmessage = async (event) => { const msg = JSON.parse(event.data); if (!msg.offer || pc) return; events.log(`offer via ${url}`); const peer = (pc = createPeerConnection()); peer.ondatachannel = ({ channel }) => sendFile(peer, channel, file, events, connected(peer, url, events)); await peer.setRemoteDescription(msg.offer); await peer.setLocalDescription(); await gatherIce(peer); announce(ws, hash, peerId, { left: 0, to_peer_id: msg.peer_id, offer_id: msg.offer_id, answer: peer.localDescription, }); }; } return code; } // Receiver sends one offer per tracker; the first data channel that opens wins. export async function receiveViaTracker(code: string, events: Events) { await downloadsReady(events); const hash = await infoHash(code); const peerId = randomBinary(20); let isConnected = false; for (const url of TRACKERS) { const pc = createPeerConnection(); const channel = pc.createDataChannel('file'); const offerId = randomBinary(20); channel.onopen = () => { if (isConnected) return pc.close(); isConnected = true; receiveFile(pc, channel, events, connected(pc, url, events)); }; pc.setLocalDescription() .then(() => gatherIce(pc)) .then(() => { const ws = new WebSocket(url); ws.onopen = () => { announce(ws, hash, peerId, { left: 1, numwant: 1, event: 'started', offers: [{ offer_id: offerId, offer: pc.localDescription }], }); events.log(`looking on ${url}`); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.answer && msg.offer_id === offerId) { events.log(`answer via ${url}`); pc.setRemoteDescription(msg.answer); } }; }); } } // Mounted last: App.vue imports the core from this module. createApp(App).mount('#app');