Salt the tracker swarm with the clock or an own salt
The code used to be derived with a fixed salt, so a tracker could compute a table from swarm to code ahead of time, once for every share. Now the salt is the UTC 6 minute window the share was made in, and the code's new 11th character names that window, so the receiver finds it even with a clock hours off. Use own salt adds a salt both sides agree on, which nobody can guess ahead for; Generate makes a random one. The salt is locked while a tracker share or search runs, and a receiver that finds no sender is told to check the salt too. Settings are no longer kept in localStorage: a remembered list or salt that differs from the other side's would silently break shares. The core now reports when a share expires and until when it lasts, and the session owns a tracker's timers, so a socket still closing after an abort announces nothing more. Header options line up with the cards, disabled switches look disabled, and sizes, percents and times don't wrap. postcss 8.5.32. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e3a2b348d6
commit
2e47b55901
7 files changed
+462
-142
No files matched your search
+114
-45
@@ -82,6 +82,12 @@ export type Events = {
|
||||
progress: (read: number, size: number) => void;
|
||||
};
|
||||
|
||||
export type SendEvents = Events & {
|
||||
// Once a tracker share's TRACKER_WAIT passed: no further receiver finds it with the code. One
|
||||
// connected by then still gets its turn.
|
||||
expired: () => 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 };
|
||||
|
||||
@@ -257,30 +263,78 @@ function randomBinary(length: number) {
|
||||
}
|
||||
|
||||
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
// The largest multiple of the alphabet's length a byte holds. The bytes above would make the first
|
||||
// characters likelier, they are dropped.
|
||||
const CODE_LIMIT = 256 - (256 % CODE_CHARS.length);
|
||||
|
||||
// 10 of 62 characters. Bytes from 248 on are dropped, so every character is equally likely.
|
||||
function randomCode() {
|
||||
// length of the 62 characters, each equally likely.
|
||||
export function randomCode(length: number) {
|
||||
let code = '';
|
||||
while (code.length < 10)
|
||||
for (const byte of crypto.getRandomValues(new Uint8Array(10)))
|
||||
if (byte < 248 && code.length < 10) code += CODE_CHARS[byte % 62];
|
||||
while (code.length < length)
|
||||
for (const byte of crypto.getRandomValues(new Uint8Array(length)))
|
||||
if (byte < CODE_LIMIT && code.length < length) code += CODE_CHARS[byte % CODE_CHARS.length];
|
||||
return code;
|
||||
}
|
||||
|
||||
// The code is all both sides share. It gives the tracker swarm, identified by a 20 byte info_hash,
|
||||
// and the key that proves the connection, see prove. Whoever sees the swarms, a tracker or anyone
|
||||
// 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). The salt is fixed, both sides only know the code, so the guesses
|
||||
// can also be made ahead of time, once for every share: a table from info_hash to code would let a
|
||||
// tracker take over any share as it happens. Only the code's length prices that: for 62¹⁰ codes
|
||||
// it's over a million GPU years. Any length derives the same way, an older client takes a longer
|
||||
// code. HKDF splits the result, the public info_hash tells nothing about the keys: one seals the
|
||||
// signaling, see seal, one proves the connection.
|
||||
async function secrets(code: string) {
|
||||
// Hours and minutes, the way the user's browser writes them. The time and an AM or PM keep together.
|
||||
export const formatTime = (time: number) =>
|
||||
new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0');
|
||||
|
||||
// Tracker signaling salts with the clock: its windows of SALT_WINDOW, counted in UTC from 1970. The
|
||||
// last of a code's CODE_LENGTH characters is the window it was made in, mod the number of characters,
|
||||
// so the same one comes back every ~6 hours. The receiver takes the window with that character nearest
|
||||
// its own clock's: both sides agree on the window even with clocks hours apart, and a code lasts
|
||||
// TRACKER_WAIT from the click whenever in its window that was.
|
||||
// Its own constant, not TRACKER_WAIT: changing it splits old and new clients into separate swarms.
|
||||
const SALT_WINDOW = 6 * 60_000;
|
||||
const CODE_LENGTH = 11;
|
||||
const clockWindow = (time: number) => Math.floor(time / SALT_WINDOW);
|
||||
|
||||
// The window's start in UTC, then the own salt if there is one. Spaces around that would be a typo,
|
||||
// not a different salt. A blank one is a mistake, not the clock's: nobody with it would find the share.
|
||||
function trackerSalt(at: number, own?: string) {
|
||||
const salt = new Date(at * SALT_WINDOW).toISOString().slice(0, 16);
|
||||
if (own === undefined) return salt;
|
||||
if (!own.trim()) throw new Error('the own salt is empty');
|
||||
return `${salt} ${own.trim()}`;
|
||||
}
|
||||
|
||||
// A sender's new code and its salt.
|
||||
function newCode(own?: string) {
|
||||
const at = clockWindow(Date.now());
|
||||
return { code: randomCode(CODE_LENGTH - 1) + CODE_CHARS[at % CODE_CHARS.length], salt: trackerSalt(at, own) };
|
||||
}
|
||||
|
||||
// The salt of the code a receiver got, its window from half the characters before the clock's to half
|
||||
// after. Anything else can't be a code, a typo gets told right away instead of searched for.
|
||||
function codeSalt(code: string, own?: string) {
|
||||
if (code.length !== CODE_LENGTH || [...code].some((char) => !CODE_CHARS.includes(char)))
|
||||
throw new Error(`a code has ${CODE_LENGTH} letters and digits, check it`);
|
||||
const now = clockWindow(Date.now());
|
||||
const cycle = CODE_CHARS.length;
|
||||
const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle;
|
||||
return trackerSalt(now + (ahead < cycle / 2 ? ahead : ahead - cycle), own);
|
||||
}
|
||||
|
||||
// The code and the salt are all both sides share. They give the tracker swarm, identified by a 20
|
||||
// byte info_hash, and the key that proves the connection, see prove. Whoever sees the swarms, a
|
||||
// tracker or anyone 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). A salt known ahead lets the guesses be made ahead
|
||||
// too: a table from info_hash to code would let a tracker take over any share as it happens. The
|
||||
// clock's salt limits a table to the shares of one window, for 62¹⁰ codes it takes over a million GPU
|
||||
// years. An own salt nobody can predict leaves guessing while the share lasts. NFC, an ü typed on one
|
||||
// system can be other bytes than on the next. HKDF splits the result, the public info_hash tells
|
||||
// nothing about the keys: one seals the signaling, see seal, one proves the connection.
|
||||
async function secrets(code: string, salt: string) {
|
||||
const text = new TextEncoder();
|
||||
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits(
|
||||
{ name: 'PBKDF2', hash: 'SHA-256', salt: text.encode('hellcon'), iterations: PBKDF2_ITERATIONS },
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
hash: 'SHA-256',
|
||||
salt: text.encode(`hellcon ${salt.normalize('NFC')}`),
|
||||
iterations: PBKDF2_ITERATIONS,
|
||||
},
|
||||
password,
|
||||
256,
|
||||
);
|
||||
@@ -892,23 +946,21 @@ function trackerSocket(
|
||||
lost: () => void,
|
||||
again: () => void,
|
||||
) {
|
||||
const ws = own(signal, new WebSocket(url));
|
||||
const ws = new WebSocket(url);
|
||||
let opened = false;
|
||||
let accepted = false;
|
||||
let closed = false;
|
||||
let reannounce: ReturnType<typeof setInterval> | undefined;
|
||||
const end = (reason: string) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearTimeout(timeout);
|
||||
clearInterval(reannounce);
|
||||
// Already closed unless rejected or silent, this only lets go of it.
|
||||
ws.close();
|
||||
tracker.close();
|
||||
events.log(reason);
|
||||
lost();
|
||||
};
|
||||
const timeout = setTimeout(() => end(opened ? `${url} did not answer` : `${url} unreachable`), TRACKER_TIMEOUT);
|
||||
const tracker = {
|
||||
// The session owns the timers too: a socket still closing after the abort gets no announce.
|
||||
const tracker = own(signal, {
|
||||
ws,
|
||||
// What the tracker answered, if it rejected the announcement.
|
||||
rejected: undefined as string | undefined,
|
||||
@@ -920,7 +972,7 @@ function trackerSocket(
|
||||
clearInterval(reannounce);
|
||||
ws.close();
|
||||
},
|
||||
};
|
||||
});
|
||||
ws.addEventListener('open', () => (opened = true));
|
||||
ws.addEventListener('message', ({ data }) => {
|
||||
const msg = parse(data);
|
||||
@@ -958,12 +1010,13 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
||||
// 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 tracker goes. After TRACKER_WAIT it goes as well, a
|
||||
// receiver connected by then still gets its turn.
|
||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||
// receiver connected by then still gets its turn. Resolves with the code and when it ends.
|
||||
export async function sendViaTracker(file: File, events: SendEvents, signal: AbortSignal, ownSalt?: string) {
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Creating the code');
|
||||
const code = randomCode();
|
||||
const { hash, key, sealing } = await secrets(code);
|
||||
const until = Date.now() + TRACKER_WAIT;
|
||||
const { code, salt } = newCode(ownSalt);
|
||||
const { hash, key, sealing } = await secrets(code, salt);
|
||||
const peerId = randomBinary(20);
|
||||
const urls = [...settings.trackers];
|
||||
// Every one tried so far, only the last can be alive.
|
||||
@@ -989,13 +1042,18 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
||||
const nobody = () =>
|
||||
hint
|
||||
? `no receiver connected within ${TRACKER_WAIT / 60_000} minutes: ${hint}`
|
||||
: `nobody received the file within ${TRACKER_WAIT / 60_000} minutes, share it again`;
|
||||
const expiry = deadline(signal, () => {
|
||||
expired = true;
|
||||
for (const tracker of trackers) tracker.close();
|
||||
if (stranded()) events.error(nobody());
|
||||
});
|
||||
? `no receiver connected until ${formatTime(until)}: ${hint}`
|
||||
: `nobody received the file until ${formatTime(until)}, share it again`;
|
||||
const expiry = deadline(
|
||||
signal,
|
||||
() => {
|
||||
expired = true;
|
||||
events.expired();
|
||||
for (const tracker of trackers) tracker.close();
|
||||
if (stranded()) events.error(nobody());
|
||||
},
|
||||
until - Date.now(),
|
||||
);
|
||||
// Once stranded the share is over.
|
||||
const end = (reason: string) => {
|
||||
expiry.close();
|
||||
@@ -1117,7 +1175,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
}
|
||||
|
||||
join(0);
|
||||
return code;
|
||||
return { code, until };
|
||||
}
|
||||
|
||||
// Receiver walks the trackers in order with one offer each, until one has a seeder: the sender, which
|
||||
@@ -1128,11 +1186,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
// 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) {
|
||||
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal, ownSalt?: string) {
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Looking for the sender');
|
||||
// From the click, getting ready may take a moment.
|
||||
const salt = codeSalt(code.trim(), ownSalt);
|
||||
const until = Date.now() + TRACKER_WAIT;
|
||||
await downloadsReady();
|
||||
const { hash, key, sealing } = await secrets(code.trim());
|
||||
const { hash, key, sealing } = await secrets(code.trim(), salt);
|
||||
if (signal.aborted) return;
|
||||
const peerId = randomBinary(20);
|
||||
const urls = [...settings.trackers];
|
||||
@@ -1158,10 +1219,11 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
else events.status('start', text);
|
||||
};
|
||||
|
||||
// No sender with this code can come after the end, a new code can.
|
||||
const nobody = () =>
|
||||
hint
|
||||
? `no sender connected within ${TRACKER_WAIT / 60_000} minutes: ${hint}`
|
||||
: `no sender answered within ${TRACKER_WAIT / 60_000} minutes, check the code and try again`;
|
||||
? `no sender connected until ${formatTime(until)}: ${hint}`
|
||||
: `no sender answered until ${formatTime(until)}, ${ownSalt === undefined ? '' : 'check that both of you use the same salt or '}ask the sender for a new code`;
|
||||
// Without a sender connected the search is over, every offer goes.
|
||||
const end = (reason: string) => {
|
||||
expiry.close();
|
||||
@@ -1172,11 +1234,15 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
events.error(reason);
|
||||
};
|
||||
// A connected sender keeps its connection, the other offers wait for next or start.
|
||||
const expiry = deadline(signal, () => {
|
||||
expired = true;
|
||||
if (!isConnected) return end(nobody());
|
||||
for (const { tracker } of offers.values()) tracker?.close();
|
||||
});
|
||||
const expiry = deadline(
|
||||
signal,
|
||||
() => {
|
||||
expired = true;
|
||||
if (!isConnected) return end(nobody());
|
||||
for (const { tracker } of offers.values()) tracker?.close();
|
||||
},
|
||||
until - Date.now(),
|
||||
);
|
||||
|
||||
const next = (reason: string) => {
|
||||
isConnected = false;
|
||||
@@ -1269,7 +1335,10 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
const none = offers.size === urls.length && everywhere;
|
||||
if (none !== noSender && !isConnected && !started) {
|
||||
if (none)
|
||||
events.status('retry', 'No sender with this code on any tracker. Check the code, still looking');
|
||||
events.status(
|
||||
'retry',
|
||||
`No sender with this code on any tracker. Check the code${ownSalt === undefined ? '' : ' and the salt'}, still looking`,
|
||||
);
|
||||
else if (failure) events.status('retry', `${failure}. Looking again`);
|
||||
else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user