Seal tracker signaling with the code
The SDP relayed by the trackers is now encrypted with AES-GCM under a key derived from the code, next to the swarm ID and the proof key. Trackers and peers that found the swarm without the code no longer learn either side's addresses, and an offer or answer that doesn't decrypt is dropped before any peer connection exists, so it can't take the sender's turn. The proof stays as a second layer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
338d4d2532
commit
bb69569b51
3 files changed
+240
-72
No files matched your search
+63
-25
@@ -152,7 +152,7 @@ function randomCode() {
|
||||
// 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), so a GPU gets through a vanishing part of the 62⁸ codes within
|
||||
// TRACKER_WAIT. The salt is fixed, both sides only know the code. HKDF splits the result, the public
|
||||
// info_hash tells nothing about the key.
|
||||
// info_hash tells nothing about the keys: one seals the signaling, see seal, one proves the connection.
|
||||
async function secrets(code: string) {
|
||||
const text = new TextEncoder();
|
||||
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||
@@ -168,7 +168,33 @@ async function secrets(code: string) {
|
||||
'sign',
|
||||
'verify',
|
||||
]);
|
||||
return { hash: String.fromCharCode(...new Uint8Array(hash)), key };
|
||||
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.
|
||||
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.
|
||||
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) {
|
||||
@@ -659,13 +685,14 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
||||
|
||||
// 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. lost runs once it closed without close() being
|
||||
// called: unreachable, lost or rejected. again announces once more, on the first interval it names.
|
||||
// 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 or rejected.
|
||||
// again announces once more, on the first interval it names.
|
||||
function trackerSocket(
|
||||
url: string,
|
||||
signal: AbortSignal,
|
||||
events: Events,
|
||||
message: (msg: Message) => void,
|
||||
message: (msg: Message) => void | Promise<void>,
|
||||
lost: () => void,
|
||||
again: () => void,
|
||||
) {
|
||||
@@ -706,7 +733,7 @@ function trackerSocket(
|
||||
if (!reannounce && !closed && typeof msg.interval === 'number') {
|
||||
reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000)));
|
||||
}
|
||||
return message(msg);
|
||||
return void message(msg);
|
||||
}
|
||||
if (accepted) return events.log(`${url}: ${failure}`);
|
||||
tracker.rejected = `${url}: ${failure.slice(0, 200)}`;
|
||||
@@ -726,14 +753,15 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
||||
}
|
||||
|
||||
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
|
||||
// time. Until a receiver proved the code, the next one gets its turn: a peer that found the swarm
|
||||
// without it doesn't end the share. Neither does an offer that can't be answered, never connects or
|
||||
// proves nothing. Once the download started the share is used up, the trackers go. After
|
||||
// TRACKER_WAIT they go as well, a receiver connected by then still gets its turn.
|
||||
// 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 trackers go. After TRACKER_WAIT they go as well, a
|
||||
// receiver connected by then still gets its turn.
|
||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
const code = randomCode();
|
||||
const { hash, key } = await secrets(code);
|
||||
const { hash, key, sealing } = await secrets(code);
|
||||
const peerId = randomBinary(20);
|
||||
const trackers: Tracker[] = [];
|
||||
let busy = false;
|
||||
@@ -802,10 +830,12 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
|
||||
});
|
||||
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}`);
|
||||
}
|
||||
@@ -814,7 +844,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
left: 0,
|
||||
to_peer_id: msg.peer_id,
|
||||
offer_id: msg.offer_id,
|
||||
answer: pc.localDescription,
|
||||
answer: { type: 'answer', sdp },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -823,11 +853,15 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
url,
|
||||
signal,
|
||||
events,
|
||||
(msg) => {
|
||||
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 offer = { offer: { sdp: msg.offer.sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
||||
const sdp = await unseal(sealing, 'offer', msg.offer.sdp);
|
||||
// Meanwhile the share may have been used up, expired or ended, its trackers 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);
|
||||
},
|
||||
@@ -846,13 +880,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
|
||||
// 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. An answer 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.
|
||||
// queued one of them. 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) {
|
||||
events = live(events, signal);
|
||||
await downloadsReady();
|
||||
const { hash, key } = await secrets(code.trim());
|
||||
const { hash, key, sealing } = await secrets(code.trim());
|
||||
if (signal.aborted) return;
|
||||
const peerId = randomBinary(20);
|
||||
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
|
||||
@@ -925,7 +960,8 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
|
||||
pc.setLocalDescription()
|
||||
.then(() => gatherIce(pc))
|
||||
.then(() => {
|
||||
.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) =>
|
||||
@@ -933,21 +969,23 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
left: 1,
|
||||
numwant: 1,
|
||||
event,
|
||||
offers: [{ offer_id: offerId, offer: pc.localDescription }],
|
||||
offers: [{ offer_id: offerId, offer: { type: 'offer', sdp } }],
|
||||
});
|
||||
const tracker = trackerSocket(
|
||||
url,
|
||||
signal,
|
||||
events,
|
||||
(msg) => {
|
||||
async (msg) => {
|
||||
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}`);
|
||||
// Only one answer per offer, a replacement opens its own socket.
|
||||
tracker.close();
|
||||
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
|
||||
pc.setRemoteDescription({ type: 'answer', sdp: msg.answer.sdp }).catch(() =>
|
||||
retry(`unusable answer via ${url}`),
|
||||
);
|
||||
pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`));
|
||||
},
|
||||
() => {
|
||||
entry.lost = true;
|
||||
|
||||
Reference in new issue
Block a user