Add experimental tracker reconnect for paired devices

During a session authenticated by both device identities, one person
proposes a WebTorrent tracker and the other confirms it. Both contribute
a nonce over the data channel; HKDF binds both device keys, the session
fingerprints and the tracker URL into a non-extractable base key stored
with the connection. Forget device, a replaced paired device and Turn
off reconnect clear it.

Reconnect joins a daily swarm derived from that key. Offers, answers and
codeless wakes travel as AES-GCM envelopes bound to the tracker routing
fields. The lower device key offers; the other device wakes it when it
arrives second. Retries are spaced and capped, one attempt per slot runs
under a Web Lock, and fresh device proofs still authenticate the session.

Checked against tracker.openwebtorrent.com and tracker.webtorrent.dev
with the new opt-in browser check (--tracker=<url>). Signaling v5,
midnight rollover, clock skew, CSP and real-network checks remain open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-20 20:51:05 +02:00
1 parent a5935a8324
commit 3659956967
17 files changed
+930 -28

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { derivePairing, discoveryId, openSignal, parsePairing, pairingNonce, sealSignal, signalingKey, signalRole, trackerUrl, CLOCK_TOLERANCE, SIGNAL_LIFETIME, type PairingContext, type SignalRoute } from '../src/lib/reconnect.ts';
import { emptyConnection, updateConnection } from '../src/lib/connections.ts';
const fingerprint = (byte: string) => Array(32).fill(byte).join(' ');
const id = (char: string) => char.repeat(20);
const context: PairingContext = {
proposerNonce: pairingNonce(), acceptorNonce: pairingNonce(),
proposerKey: '04' + 'a'.repeat(128), acceptorKey: '04' + 'b'.repeat(128),
offerFingerprint: fingerprint('AA'), answerFingerprint: fingerprint('BB'),
tracker: 'wss://tracker.example/announce',
};
const route: SignalRoute = { role: 'offer', infoHash: id('h'), offerId: id('o'), from: id('f'), to: '' };
test('both peers derive the same pairing; every input separates it', async () => {
const [first, second] = await Promise.all([derivePairing(context), derivePairing({ ...context })]);
assert.equal(first.extractable, false);
assert.equal(await discoveryId(first, 100), await discoveryId(second, 100));
const sealed = await sealSignal(await signalingKey(first), route, 'HC1.code');
assert.equal(await openSignal(await signalingKey(second), route, sealed), 'HC1.code');
for (const changed of [
{ proposerNonce: pairingNonce() }, { acceptorNonce: pairingNonce() },
{ proposerKey: context.acceptorKey, acceptorKey: context.proposerKey },
{ offerFingerprint: fingerprint('CC') }, { answerFingerprint: fingerprint('CC') },
{ tracker: 'wss://other.example/announce' },
]) {
const other = await derivePairing({ ...context, ...changed });
assert.notEqual(await discoveryId(other, 100), await discoveryId(first, 100));
await assert.rejects(openSignal(await signalingKey(other), route, sealed));
}
await assert.rejects(derivePairing({ ...context, acceptorKey: context.proposerKey }), /two different devices/);
await assert.rejects(derivePairing({ ...context, proposerNonce: 'short' }));
});
test('discovery identifiers are 20 binary bytes and change daily', async () => {
const key = await derivePairing(context);
const today = await discoveryId(key, 20000);
assert.equal(today.length, 20);
assert.ok([...today].every(char => char.charCodeAt(0) < 256));
assert.notEqual(await discoveryId(key, 20001), today);
});
test('envelopes bind role and every routing field, and expire', async () => {
const key = await signalingKey(await derivePairing(context));
const now = 1_000_000_000_000;
const sealed = await sealSignal(key, route, 'HC1.code', now);
assert.equal(signalRole(sealed), 'offer');
assert.equal(await openSignal(key, route, sealed, now), 'HC1.code');
for (const changed of [{ infoHash: id('x') }, { offerId: id('x') }, { from: id('x') }, { to: id('x') }]) {
await assert.rejects(openSignal(key, { ...route, ...changed }, sealed, now));
}
await assert.rejects(openSignal(key, { ...route, role: 'answer' }, sealed, now));
const tampered = sealed.slice(0, -2) + (sealed.endsWith('A') ? 'B' : 'A') + sealed.slice(-1);
await assert.rejects(openSignal(key, route, tampered, now));
await assert.rejects(openSignal(key, route, sealed, now + SIGNAL_LIFETIME + CLOCK_TOLERANCE + 1), /expired/);
await assert.rejects(openSignal(key, route, 'x'.repeat(200_000), now));
const wake = await sealSignal(key, { ...route, role: 'wake' }, '', now);
assert.equal(await openSignal(key, { ...route, role: 'wake' }, wake, now), '');
// A wake never carries a code, and offers always do.
await assert.rejects(openSignal(key, route, await sealSignal(key, route, '', now), now));
});
test('tracker addresses must be secure WebSocket URLs', () => {
assert.equal(trackerUrl(' wss://tracker.example '), 'wss://tracker.example/');
assert.equal(trackerUrl('ws://localhost:8000'), 'ws://localhost:8000/');
for (const bad of ['https://tracker.example', 'ws://tracker.example', 'wss://user:pass@tracker.example', 'wss://tracker.example/#x', 'nonsense', 42]) {
assert.throws(() => trackerUrl(bad));
}
});
test('stored pairings are dropped when the paired device changes', async () => {
const peerKey = context.acceptorKey;
const pairing = { version: 1 as const, trackers: ['wss://tracker.example/'], key: await derivePairing(context), localKey: context.proposerKey, peerKey };
const paired = updateConnection(emptyConnection(), { peerKey });
const reconnecting = updateConnection(paired, { reconnect: pairing });
assert.equal(reconnecting.reconnect?.trackers[0], 'wss://tracker.example/');
assert.equal(updateConnection(reconnecting, { name: 'Laptop' }).reconnect, reconnecting.reconnect);
assert.equal(updateConnection(reconnecting, { peerKey }).reconnect, reconnecting.reconnect);
assert.equal(updateConnection(reconnecting, { peerKey: '' }).reconnect, null);
assert.equal(updateConnection(reconnecting, { peerKey: context.proposerKey }).reconnect, null);
assert.equal(updateConnection(reconnecting, { reconnect: null }).reconnect, null);
assert.throws(() => updateConnection(emptyConnection(), { reconnect: pairing }));
assert.equal(parsePairing(structuredClone(pairing), peerKey)?.key.algorithm.name, 'HKDF');
assert.equal(parsePairing({ ...pairing, trackers: ['http://x'] }, peerKey), null);
assert.equal(parsePairing({ ...pairing, key: 'secret' }, peerKey), null);
});
+118
View File
@@ -0,0 +1,118 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { ReconnectAttempt, TrackerClient, type AttemptHooks } from '../src/lib/tracker.ts';
import { derivePairing, discoveryId, pairingNonce, signalingKey } from '../src/lib/reconnect.ts';
// An in-memory tracker with the routing of webtorrent/bittorrent-tracker:
// counts include the announcing peer, offers go to other registered peers,
// answers go to to_peer_id. Messages are delivered asynchronously.
class FakeTracker {
peers = new Map<string, FakeSocket>();
frames: Record<string, unknown>[] = [];
refuse = '';
connect = (_url: string) => new FakeSocket(this) as unknown as WebSocket;
handle(socket: FakeSocket, data: Record<string, unknown>) {
this.frames.push(data);
const reply = (target: FakeSocket, message: object) => target.deliver({ action: 'announce', info_hash: data.info_hash, ...message });
if (this.refuse) { reply(socket, { 'failure reason': this.refuse }); return; }
const peerId = data.peer_id as string;
if (data.event === 'stopped') { this.peers.delete(peerId); return; }
this.peers.set(peerId, socket);
if (data.answer) {
const target = this.peers.get(data.to_peer_id as string);
if (target) reply(target, { peer_id: peerId, offer_id: data.offer_id, answer: data.answer });
return;
}
reply(socket, { interval: 120, complete: 0, incomplete: this.peers.size });
const others = [...this.peers].filter(([id]) => id !== peerId).map(([, peer]) => peer);
for (const [index, item] of ((data.offers ?? []) as { offer_id: string; offer: unknown }[]).entries()) {
const target = others[index];
if (target) reply(target, { peer_id: peerId, offer_id: item.offer_id, offer: item.offer });
}
}
}
class FakeSocket {
readyState = 0;
onopen: (() => void) | null = null;
onclose: (() => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
tracker: FakeTracker;
constructor(tracker: FakeTracker) { this.tracker = tracker; setTimeout(() => { this.readyState = 1; this.onopen?.(); }); }
send(text: string) { const data = JSON.parse(text); setTimeout(() => this.tracker.handle(this, data)); }
deliver(message: object) { setTimeout(() => { if (this.readyState === 1) this.onmessage?.({ data: JSON.stringify(message) }); }); }
close() { this.readyState = 3; }
}
async function pairing() {
const key = await derivePairing({
proposerNonce: pairingNonce(), acceptorNonce: pairingNonce(), proposerKey: '04' + 'a'.repeat(128), acceptorKey: '04' + 'b'.repeat(128),
offerFingerprint: Array(32).fill('AA').join(' '), answerFingerprint: Array(32).fill('BB').join(' '), tracker: 'wss://tracker.test/',
});
return { infoHash: await discoveryId(key), key: await signalingKey(key) };
}
function peer(tracker: FakeTracker, shared: { infoHash: string; key: CryptoKey }, initiator: boolean) {
const log = { offers: 0, answered: [] as string[], accepted: [] as string[], errors: [] as string[] };
let done: () => void;
const finished = new Promise<void>(resolve => { done = resolve; });
const hooks: AttemptHooks = {
createOffer: async () => `HC1.offer-${++log.offers}`,
createAnswer: async offer => { log.answered.push(offer); return `HC1.answer-to-${offer}`; },
acceptAnswer: async answer => { log.accepted.push(answer); done(); },
onPeers: () => {},
onError: error => { log.errors.push(error.message); done(); },
};
const attempt = new ReconnectAttempt({ url: 'wss://tracker.test/', ...shared, initiator, hooks, connectSocket: tracker.connect });
return { attempt, log, finished };
}
const settle = () => new Promise(resolve => setTimeout(resolve, 20));
for (const initiatorFirst of [true, false]) {
test(`peers connect when the ${initiatorFirst ? 'initiator' : 'responder'} arrives first`, async () => {
const tracker = new FakeTracker(), shared = await pairing();
const initiator = peer(tracker, shared, true), responder = peer(tracker, shared, false);
const [first, second] = initiatorFirst ? [initiator, responder] : [responder, initiator];
await first.attempt.start(); await settle();
await second.attempt.start();
await initiator.finished;
assert.equal(initiator.log.offers, 1, 'One offer without waiting for a retry');
assert.deepEqual(responder.log.answered, ['HC1.offer-1']);
assert.deepEqual(initiator.log.accepted, ['HC1.answer-to-HC1.offer-1']);
// Routing data only: no codes in clear on the tracker.
assert.ok(tracker.frames.every(frame => !JSON.stringify(frame).includes('HC1.')));
initiator.attempt.close(); responder.attempt.close();
await settle();
assert.equal(tracker.peers.size, 0, 'Both peers send stopped on close');
});
}
test('a client with another key in the swarm is ignored', async () => {
const tracker = new FakeTracker(), shared = await pairing(), other = await pairing();
const stranger = peer(tracker, { ...other, infoHash: shared.infoHash }, false);
const initiator = peer(tracker, shared, true);
await stranger.attempt.start(); await settle();
await initiator.attempt.start(); await settle(); await settle();
// The stranger's wake does not open, so it never prompts an offer by itself;
// the count alone does, and the stranger cannot open that offer.
assert.equal(initiator.log.offers, 1);
assert.deepEqual(stranger.log.answered, []);
assert.deepEqual(initiator.log.errors, []);
initiator.attempt.close(); stranger.attempt.close();
});
test('tracker refusals and invalid frames end the attempt', async () => {
const tracker = new FakeTracker(), shared = await pairing();
tracker.refuse = 'swarm limit';
const refused = peer(tracker, shared, true);
await refused.attempt.start();
await refused.finished;
assert.match(refused.log.errors[0]!, /refused the request: swarm limit/);
const errors: string[] = [];
let socket: FakeSocket | undefined;
const client = new TrackerClient('wss://tracker.test/', shared.infoHash, { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: error => errors.push(error.message) },
() => (socket = new FakeSocket(new FakeTracker())) as unknown as WebSocket);
await client.connect();
socket!.onmessage?.({ data: 'not json' });
assert.deepEqual(errors, ['The tracker sent an invalid message.']);
assert.throws(() => new TrackerClient('wss://tracker.test/', 'short', { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: () => {} }));
});