Own each transfer in a session and harden the protocol

Every operation (share, receive, manual offer or answer) now runs as one
session tied to an AbortSignal. Starting another ends it: its connections,
tracker sockets and timers close, and it can no longer touch the shared
security check, progress or incoming file. Finished, failed and cancelled
transfers close their connections, and the sender's tracker sockets close
once the download starts.

- A malformed or never-connecting tracker offer no longer blocks a share
- The receiver validates the file offer and rejects excess bytes and
  data beyond the flow control window; sw.js checks name and size too
- Failures show up in the card instead of disappearing into rejected
  promises: bad manual codes, unreachable trackers, lost connections
- Primary buttons and pink text meet 4.5:1 contrast, the STUN switch
  shows keyboard focus again, the tracker Copy button matches the others
- Split the core into src/core.ts, src/main.ts only mounts the app, which
  removes the main.ts <-> App.vue import cycle
- Bring back the Gitea source link, write the README
- Tests reuse one browser per worker with fresh contexts, fail on page
  errors, check cleanup after transfers, use a local fake STUN server
  and cover empty files, window boundaries, odd names, malformed
  messages, session replacement and the production build

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-24 16:04:14 +02:00
1 parent bacc15baaf
commit 2abd0b504d
7 files changed
+1442 -752

No files matched your search

-551
View File
@@ -2,555 +2,4 @@ import { createApp } from 'vue';
import App from './App.vue';
import './style.css';
export const DEFAULT_TRACKERS = ['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',
];
// 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],
};
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;
// Once the user compared the codes: confirm if they match, else reject.
confirm: () => void;
reject: () => void;
};
export type Events = {
log: (message: string) => void;
// Called on both sides once connected, and without a check when it ended undecided.
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;
};
// 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;
};
function createPeerConnection() {
// An empty urls list is a syntax error.
const stun = settings.stun && settings.stunServers.length;
return new RTCPeerConnection({ iceServers: stun ? [{ urls: settings.stunServers }] : [] });
}
function randomBinary(length: number) {
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
}
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// 8 of 62 characters. Bytes from 248 on are dropped, so every character is equally likely.
function randomCode() {
let code = '';
while (code.length < 8)
for (const byte of crypto.getRandomValues(new Uint8Array(8)))
if (byte < 248 && code.length < 8) code += CODE_CHARS[byte % 62];
return code;
}
// 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<void>((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 8 bytes of both DTLS certificate fingerprints, fewer an interposer can
// brute force with matching certificates. My local code must equal the peer's remote code and vice
// versa, otherwise someone interposed on the signaling.
function securityCheck(pc: RTCPeerConnection) {
const short = (sdp = '') =>
sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 8).join(' ') ?? '?';
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
}
// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing
// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which
// needs both confirmations, a rejected check or a peer that left closes the connection and calls next:
// tracker signaling goes on with another peer. From start on, sendFile and receiveFile handle a loss.
type Handshake = { checked: Promise<void>; start: () => void };
function connected(
pc: RTCPeerConnection,
channel: RTCDataChannel,
via: string,
events: Events,
next = () => {},
): Handshake {
events.log(`connected via ${via}`);
events.log('waiting for the security check');
let done = false;
const end = (reason: string) => {
if (done) return;
done = true;
events.log(reason);
events.check();
pc.close();
next();
};
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
channel.addEventListener('close', () => end('peer left before the transfer'));
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed') end('peer left before the transfer');
});
return {
checked: new Promise((resolve) =>
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
),
start: () => (done = true),
};
}
// 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.
async function sendFile(
pc: RTCPeerConnection,
channel: RTCDataChannel,
file: File,
events: Events,
handshake: Handshake,
) {
if (channel.readyState !== 'open') {
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
}
let read = 0;
let accepted = false;
let started = 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;
if (message) events.log(message);
wake();
};
channel.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.ok) accepted = true;
else if (message.start) started = true;
// Before that, nothing else can come from a receiver that passed its check.
else if (!sending) return;
if (message.read) {
read = message.read;
events.progress(read, file.size);
}
if (message.done) {
events.log('delivered');
events.progress(file.size, file.size);
// 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. Before
// sending, connected reports it.
const lost = () => stop(sending ? 'connection lost' : undefined);
channel.addEventListener('close', lost);
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
channel.addEventListener('bufferedamountlow', () => wake());
await handshake.checked;
if (!accepted && !stopped) events.log("waiting for the receiver's security check");
while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
events.log(`offered ${file.name} (${file.size} bytes)`);
if (!started) events.log('waiting for the receiver to download');
while (!stopped && !started) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
sending = true;
handshake.start();
events.log(`sending ${file.name}`);
events.progress(0, file.size);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
await new Promise<void>((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 }. Its file is offered to
// the user, chunks are accepted only once they started the download.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: ReceiveEvents, handshake: Handshake) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
let received = 0;
let confirmed = false;
let downloading = false;
let ended = false;
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
let worker: Promise<ServiceWorker | void> = 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<typeof setInterval> | 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') {
events.progress(data, meta!.size);
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');
events.progress(meta!.size, meta!.size);
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)));
}
handshake.checked.then(() => {
confirmed = true;
reply({ ok: true });
events.log('waiting for the sender');
});
function complete() {
post({ done: true });
events.log('received');
}
function download() {
if (downloading || ended) return;
downloading = true;
handshake.start();
events.log(`receiving ${meta!.name}`);
events.progress(0, meta!.size);
startDownload();
reply({ start: true });
if (!meta!.size) complete();
}
channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => {
if (ended || !confirmed) return;
if (typeof data === 'string') {
if (meta) return;
meta = JSON.parse(data);
events.log(`offered ${meta!.name} (${meta!.size} bytes)`);
events.incoming({ ...meta!, download });
} else if (downloading) {
received += data.byteLength;
post({ chunk: data }, [data]);
if (received === meta!.size) complete();
}
};
// 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) return;
if (!downloading) events.incoming();
else if (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, channel, '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: ReceiveEvents) {
await downloadsReady(events);
const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) =>
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events));
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
await pc.setLocalDescription();
await gatherIce(pc);
return btoa(pc.localDescription!.sdp);
}
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed
// the code, or got the same one by chance, doesn't end the share.
export async function sendViaTracker(file: File, events: Events) {
const code = randomCode();
const hash = await infoHash(code);
const peerId = randomBinary(20);
let busy = false;
// The latest offer that came while busy, answered once that peer is out.
let waiting: (() => void) | undefined;
async function answer(ws: WebSocket, url: string, msg: { offer: RTCSessionDescriptionInit; peer_id: string; offer_id: string }) {
busy = true;
events.log(`offer via ${url}`);
const pc = createPeerConnection();
const next = () => {
busy = false;
events.log('waiting for the next receiver');
const offer = waiting;
waiting = undefined;
offer?.();
};
let checking = false;
pc.ondatachannel = ({ channel }) => {
checking = true;
sendFile(pc, channel, file, events, connected(pc, channel, url, events, next));
};
// An offer whose receiver is gone never gets to the check.
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState !== 'failed' || checking) return;
pc.close();
next();
});
await pc.setRemoteDescription(msg.offer);
await pc.setLocalDescription();
await gatherIce(pc);
announce(ws, hash, peerId, {
left: 0,
to_peer_id: msg.peer_id,
offer_id: msg.offer_id,
answer: pc.localDescription,
});
}
for (const url of settings.trackers) {
const ws = new WebSocket(url);
ws.onopen = () => {
announce(ws, hash, peerId, { left: 0, event: 'started' });
events.log(`waiting on ${url}`);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (!msg.offer) return;
if (busy) waiting = () => answer(ws, url, msg);
else answer(ws, url, msg);
};
}
return code;
}
// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails
// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have
// queued one of them.
export async function receiveViaTracker(code: string, events: ReceiveEvents) {
await downloadsReady(events);
const hash = await infoHash(code);
const peerId = randomBinary(20);
const offers = new Map<string, RTCPeerConnection>();
let isConnected = false;
const next = () => {
isConnected = false;
events.log('looking again');
for (const [url, pc] of offers) if (pc.signalingState === 'closed') offer(url);
};
function offer(url: string) {
const pc = createPeerConnection();
offers.set(url, pc);
const channel = pc.createDataChannel('file');
const offerId = randomBinary(20);
channel.onopen = () => {
if (isConnected) return pc.close();
isConnected = true;
receiveFile(pc, channel, events, connected(pc, channel, url, events, next));
};
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);
// Only one answer per offer, a replacement opens its own connection.
ws.close();
}
};
});
}
for (const url of settings.trackers) offer(url);
}
// Mounted last: App.vue imports the core from this module.
createApp(App).mount('#app');