Lengthen codes and keep going after a failed security check

The security check compares 8 instead of 5 fingerprint bytes, too many to
brute force matching certificates. The tracker code has 8 digits, making
collisions between concurrent senders 100x less likely.

A "Codes don't match" button, or a peer leaving before the transfer
starts, ends that connection without ending the share: the tracker sender
answers the next (or a queued) offer, the receiver replaces its used up
offers. Both codes are aligned below each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-23 01:01:45 +02:00
1 parent 9282865a8c
commit 08b9f659c2
4 files changed
+228 -54

No files matched your search

+124 -42
View File
@@ -25,12 +25,18 @@ const KEEPALIVE = 10_000;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
export type Check = { local: string; remote: string };
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, confirm once the user compared the codes and they match.
check: (check: Check, confirm: () => void) => void;
// Called on both sides once connected, and without a check when it ended undecided.
check: (check?: Check) => void;
};
function createPeerConnection() {
@@ -42,7 +48,7 @@ function randomBinary(length: number) {
}
function randomCode() {
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, '0');
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 100_000_000).padStart(8, '0');
}
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
@@ -85,20 +91,50 @@ async function gatherIce(pc: RTCPeerConnection) {
});
}
// 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 {
// 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, 5).join(' ') ?? '?';
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) };
}
// 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) {
// 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');
return new Promise<void>((resolve) => events.check(securityCheck(pc), resolve));
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),
};
}
// Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers
@@ -109,7 +145,7 @@ async function sendFile(
channel: RTCDataChannel,
file: File,
events: Events,
checked: Promise<void>,
handshake: Handshake,
) {
if (channel.readyState !== 'open') {
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
@@ -120,10 +156,10 @@ async function sendFile(
let stopped = false;
// Every event the send loop can wait for calls this.
let wake = () => {};
const stop = (message: string) => {
const stop = (message?: string) => {
if (stopped) return;
stopped = true;
events.log(message);
if (message) events.log(message);
wake();
};
channel.onmessage = ({ data }) => {
@@ -140,17 +176,20 @@ async function sendFile(
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'));
// 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 checked;
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;
sending = true;
handshake.start();
events.log(`sending ${file.name} (${file.size} bytes)`);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
@@ -208,7 +247,7 @@ async function holdWorker() {
}
// Accepts nothing until checked resolved, then tells the sender with { ok }.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, checked: Promise<void>) {
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, handshake: Handshake) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
@@ -278,7 +317,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
}, (error) => fail(String(error)));
}
checked.then(() => {
handshake.checked.then(() => {
confirmed = true;
reply({ ok: true });
events.log('waiting for the sender');
@@ -289,6 +328,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
if (ended || !confirmed) return;
if (typeof data === 'string') {
meta = JSON.parse(data);
handshake.start();
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
startDownload();
} else {
@@ -314,7 +354,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
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));
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events));
await pc.setLocalDescription();
await gatherIce(pc);
@@ -327,7 +367,8 @@ export async function createOffer(file: File, events: Events) {
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));
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);
@@ -335,12 +376,49 @@ export async function answerOffer(offer: string, events: Events) {
return btoa(pc.localDescription!.sdp);
}
// Tracker signaling (optional): sender joins the swarm on every tracker and answers the first offer.
// 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 pc: RTCPeerConnection | undefined;
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 TRACKERS) {
const ws = new WebSocket(url);
@@ -348,42 +426,42 @@ export async function sendViaTracker(file: File, events: Events) {
announce(ws, hash, peerId, { left: 0, event: 'started' });
events.log(`waiting on ${url}`);
};
ws.onmessage = async (event) => {
ws.onmessage = (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,
});
if (!msg.offer) return;
if (busy) waiting = () => answer(ws, url, msg);
else answer(ws, url, msg);
};
}
return code;
}
// Receiver sends one offer per tracker; the first data channel that opens wins.
// 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: Events) {
await downloadsReady(events);
const hash = await infoHash(code);
const peerId = randomBinary(20);
const offers = new Map<string, RTCPeerConnection>();
let isConnected = false;
for (const url of TRACKERS) {
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, url, events));
receiveFile(pc, channel, events, connected(pc, channel, url, events, next));
};
pc.setLocalDescription()
@@ -404,10 +482,14 @@ export async function receiveViaTracker(code: string, events: Events) {
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 TRACKERS) offer(url);
}
// Mounted last: App.vue imports the core from this module.