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:
SchluffeandClaude Opus 5.5 committed 2026-10-28 01:14:27 +01:00
1 parent e3a2b348d6
commit 2e47b55901
7 files changed
+462 -142

No files matched your search

+202 -37
View File
@@ -37,6 +37,14 @@ const PROBE_TIMEOUT = 2000;
const PROOF_TIMEOUT = 10_000;
const CONNECT_TIMEOUT = 30_000;
const DOWNLOAD_GRACE = 1000;
// Every page's clock starts a second into the window from 12:00 to 12:06 UTC unless a test sets
// another time, so the test knows the salt of every code, see saltOf. SALT_WINDOW is the one in
// src/core.ts.
const TEST_TIME = Date.UTC(2026, 0, 1, 12, 0, 1);
const SALT_WINDOW = 6 * 60_000;
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// When a share or search ends, in its error. The browser writes the time its own way.
const UNTIL = String.raw`until \d\d?:\d\d(?:[\u00a0\u202f][AP]M)?`;
// Enough for a transfer whose receiver holds back its reads to pause at the window.
const HELD_SIZE = 3 * WINDOW;
// What the fake STUN server reports as public address, reserved for documentation.
@@ -73,7 +81,7 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
},
async tracker(sender, receiver) {
await sender.click('#share');
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{10}$/);
await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{11}$/);
await sender.click('#copy-send-code');
await expect(sender.locator('#copy-send-code')).toHaveText('Copied');
await expect(sender.locator('#log')).toContainText('waiting on');
@@ -134,13 +142,18 @@ test.afterAll(async () => {
stun.close();
});
// init runs in the page before the app. base is the app's URL, the dev server's by default.
async function open(name: string, { init, base = url }: { init?: () => void; base?: string } = {}) {
// init runs in the page before the app. base is the app's URL, the dev server's by default. time is
// where the page's clock starts.
async function open(
name: string,
{ init, base = url, time = TEST_TIME }: { init?: () => void; base?: string; time?: number } = {},
) {
browsers[name] ??= BROWSERS[name]!.launch();
const browser = await browsers[name];
const context = await browser.newContext({ permissions: PERMISSIONS[name] });
contexts.push(context);
const page = await context.newPage();
await page.clock.install({ time });
const trackers: PageSocket[] = [];
sockets.set(page, trackers);
page.on('websocket', (ws) => ws.url().startsWith(base.replace('http', 'ws')) || trackers.push(ws));
@@ -450,13 +463,28 @@ for (const [from, to] of [
test(`own tracker: ${from} sends to ${to}`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(from), open(to)]);
// With an own salt, the clock's is in the live tests.
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
await page.check('#own-salt');
await page.fill('#salt', 'own tracker');
}
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`);
});
// The code tells its window, the receiver's clock can be hours off. With the clock's salt.
test(`own tracker: ${from} sends to ${to} with the receiver's clock 2 hours behind`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(from), open(to, { time: TEST_TIME - 2 * 3_600_000 })]);
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
}
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`);
});
}
@@ -474,7 +502,7 @@ test('build: chromium sends to firefox from the production build', async () => {
});
for (const name of Object.keys(BROWSERS)) {
test(`servers: ${name} skips invalid lines and keeps the lists over a reload`, async () => {
test(`servers: ${name} skips invalid lines, a reload brings back the defaults`, async () => {
const page = await open(name);
const core = () =>
page.evaluate(
@@ -489,10 +517,16 @@ for (const name of Object.keys(BROWSERS)) {
await expect(page.locator('#servers')).toContainText('without #: tracker.example, wss://tracker.example/#');
expect(await core()).toEqual([[], ['wss://tracker.example']]);
await page.uncheck('#stun');
await page.check('#own-salt');
await page.fill('#salt', 'salt');
await page.reload();
await page.click('#servers summary');
await expect(page.locator('#trackers')).toHaveValue('wss://tracker.example');
expect(await core()).toEqual([[], ['wss://tracker.example']]);
await expect(page.locator('#trackers')).toHaveValue(/^wss:\/\/tracker\.pagequit\.net\n/);
await expect(page.locator('#stun')).toBeChecked();
await expect(page.locator('#own-salt')).not.toBeChecked();
await expect(page.locator('#salt')).toHaveCount(0);
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
await page.fill('#receive-code', 'code');
await page.fill('#trackers', '');
@@ -701,7 +735,6 @@ for (const name of Object.keys(BROWSERS)) {
// DOWNLOAD_GRACE. The frame holding the worker goes right away, it would block an update.
test(`boundary: ${name} keeps a finished download's frame for DOWNLOAD_GRACE`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
await receiver.clock.install();
await withLogs(sender, receiver, async () => {
await connect('offline', sender, receiver, await payload(Buffer.alloc(0), 'empty.bin'));
@@ -762,7 +795,7 @@ for (const name of Object.keys(BROWSERS)) {
const first = await sender.locator('#send-code').textContent();
await sender.click('#share');
await expect(sender.locator('#send-code')).not.toHaveText(first!);
await receiver.fill('#receive-code', 'nobody');
await receiver.fill('#receive-code', 'nobodyhere0');
await receiver.click('#receive');
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
// The log tells the sessions apart.
@@ -1002,7 +1035,6 @@ for (const name of Object.keys(BROWSERS)) {
// The 6 minutes only limit finding each other, a receiver connected by then still gets the file.
test(`live tracker: ${name} a receiver connected before the expiry downloads after it`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
await Promise.all([sender, receiver].map((page) => page.clock.install()));
const source = await payload(randomBytes(SIZE));
await withLogs(sender, receiver, async () => {
@@ -1091,7 +1123,7 @@ for (const name of Object.keys(BROWSERS)) {
await receiver.uncheck('#stun');
await receiver.click('#servers summary');
await receiver.fill('#trackers', urls.join('\n'));
await receiver.fill('#receive-code', 'somecode');
await receiver.fill('#receive-code', 'somecode123');
await receiver.click('#receive');
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[1]}`);
// A third one would come within milliseconds.
@@ -1146,6 +1178,134 @@ for (const name of Object.keys(BROWSERS)) {
});
});
// The info_hash tells which salt a share took: the window its code ends with, or that and the own
// salt, trimmed and NFC. A code made late in a window still lasts 6 minutes. The salt stays as it is
// while a share or search runs.
test(`salt: ${name} a share takes the clock's salt or the own one, which stays while it runs`, async () => {
const sender = await open(name);
const hashes: string[] = [];
await mockTrackers(sender, (msg) => {
if (msg.event === 'started') hashes.push(msg.info_hash as string);
return { action: 'announce', interval: 120, info_hash: msg.info_hash };
});
const label = sender.locator('label[for=send-code]');
const valid = /^\s*Code, give this to the receiver, valid until .+:\s*$/;
// The time as the label writes it, in the page's locale and time zone.
const time = (at: number) =>
sender.evaluate(
(at) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }).replaceAll(' ', '\u00a0'),
at,
);
// The code and info_hash of the share start begins, by default a click on Share.
const share = async (start = () => sender.click('#share')) => {
const count = hashes.length;
await start();
await expect.poll(() => hashes.length).toBe(count + 1);
return { code: (await sender.locator('#send-code').textContent())!, hash: hashes.at(-1) };
};
await withLogs(sender, sender, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
const first = await share();
expect(first.hash).toBe(swarm(first.code));
await expect(label).toHaveText(valid);
// toHaveText takes a no-break space for any space, the text itself has to have it.
expect(await label.textContent()).toMatch(new RegExp(`${UNTIL}:`));
// 12:05:30, half a minute before the window ends. Still valid for 6 minutes, until 12:11.
await sender.clock.fastForward('05:29');
const late = await share();
expect(late.code.at(-1)).toBe(first.code.at(-1));
expect(late.hash).toBe(swarm(late.code));
await expect(label).toHaveText(valid);
expect(await label.textContent()).toContain(`until ${await time(Date.UTC(2026, 0, 1, 12, 11, 30))}:`);
await sender.clock.fastForward('06:00');
await expect(label).toHaveText('Code, no longer valid:');
const next = await share();
expect(next.code.at(-1)).not.toBe(first.code.at(-1));
expect(next.hash).toBe(swarm(next.code));
// The switch, and the salt with Generate while it's on.
const locked = async (disabled: boolean) => {
const ids = (await sender.isChecked('#own-salt')) ? ['#own-salt', '#salt', '#generate-salt'] : ['#own-salt'];
for (const id of ids) await expect(sender.locator(id)).toBeEnabled({ enabled: !disabled });
};
await locked(true);
await sender.clock.fastForward('06:00');
await expect(label).toHaveText('Code, no longer valid:');
await locked(false);
await sender.check('#own-salt');
await expect(sender.locator('#share')).toBeDisabled();
await sender.fill('#salt', ' ');
await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'true');
await expect(sender.locator('#share')).toBeDisabled();
// ü decomposed, u and a combining diaeresis.
await sender.fill('#salt', ' Gru\u0308ße ');
await expect(sender.locator('#salt')).toHaveAttribute('aria-invalid', 'false');
const own = await share();
expect(own.hash).toBe(swarm(own.code, 'Grüße'));
await expect(label).toHaveText(/^\s*Code, give this and your salt to the receiver, valid until .+:\s*$/);
await locked(true);
// 16 of the code's characters.
await sender.clock.fastForward('06:00');
await locked(false);
await sender.click('#generate-salt');
const generated = await sender.inputValue('#salt');
expect(generated).toMatch(/^[0-9a-zA-Z]{16}$/);
const resalted = await share();
expect(resalted.hash).toBe(swarm(resalted.code, generated));
// What can't be a code is told right away, that search is over.
await sender.fill('#receive-code', 'abcdefghij');
await sender.click('#receive');
await expect(sender.locator('#receive-error')).toHaveText('a code has 11 letters and digits, check it');
await locked(false);
await sender.fill('#receive-code', 'abcdefghijk');
await sender.click('#receive');
await expect.poll(() => hashes).toContain(swarm('abcdefghijk', generated));
await locked(true);
});
});
// Until the transfer is over, on both sides.
test(`salt: ${name} stays while the peers are connected`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(name), open(name)]);
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
await page.check('#own-salt');
await page.fill('#salt', 'salt');
}
const locked = (disabled: boolean) =>
Promise.all(
[sender, receiver].flatMap((page) =>
['#own-salt', '#salt', '#generate-salt'].map((id) =>
expect(page.locator(id)).toBeEnabled({ enabled: !disabled }),
),
),
);
await withLogs(sender, receiver, async () => {
await connect('tracker', sender, receiver, await payload(randomBytes(1000)));
await expect(sender.locator('#send-status')).toHaveText('Waiting for the receiver to download');
await expect(receiver.locator('#receive-status')).toHaveText('Click Download to save the file');
await locked(true);
const started = downloadStarts(receiver);
await receiver.click('#download');
await started;
await expect(sender.locator('#send-status')).toHaveText('Delivered');
await expect(receiver.locator('#receive-status')).toHaveText('Download complete');
await locked(false);
});
});
// Trackers drop a peer that doesn't announce again on their interval, the defaults after 2 to 3
// minutes. A code nobody uses still ends after 6 minutes, on both sides.
test(`tracker: ${name} both sides announce again until they give up after 6 minutes`, async () => {
@@ -1156,7 +1316,6 @@ for (const name of Object.keys(BROWSERS)) {
// 0 would announce in a loop, the app waits 30 s at least.
const trackers = await Promise.all(
pages.map(async (page, i) => {
await page.clock.install();
return mockTrackers(page, (msg) => {
announced[i]!.push(msg);
return { action: 'announce', interval: 0, info_hash: msg.info_hash };
@@ -1191,12 +1350,12 @@ for (const name of Object.keys(BROWSERS)) {
await fastForward(330_000);
await expect(sender.locator('#send-error')).toHaveText(
'nobody received the file within 6 minutes, share it again',
new RegExp(`^nobody received the file ${UNTIL}, share it again$`),
);
await expect(sender.locator('label[for=send-code]')).toHaveText('Code, no longer valid:');
await expect(sender.locator('#copy-send-code')).toBeDisabled();
await expect(receiver.locator('#receive-error')).toHaveText(
'no sender answered within 6 minutes, check the code and try again',
new RegExp(`^no sender answered ${UNTIL}, ask the sender for a new code$`),
);
await expect.poll(() => trackers.map(({ open }) => open)).toEqual([0, 0]);
await expectClosed(sender);
@@ -1225,7 +1384,7 @@ for (const name of Object.keys(BROWSERS)) {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
for (let session = 0; session < 5; session++) {
await sender.click('#share');
await receiver.fill('#receive-code', `nobody ${session}`);
await receiver.fill('#receive-code', `nobodyhere${session}`);
await receiver.click('#receive');
}
await expect.poll(deadlines).toEqual([1, 1]);
@@ -1245,7 +1404,6 @@ for (const name of Object.keys(BROWSERS)) {
// gets no turn either.
test(`tracker: ${name} an offer still being opened gets no turn after the expiry`, async () => {
const sender = await open(name, { init: holdDecrypts });
await sender.clock.install();
const trackers = await mockTrackers(sender, ({ info_hash }) => ({ action: 'announce', interval: 120, info_hash }));
const decrypts = () =>
sender.evaluate(() => (window as unknown as { decrypts: { held: number; done: number } }).decrypts);
@@ -1259,7 +1417,7 @@ for (const name of Object.keys(BROWSERS)) {
await expect.poll(decrypts).toEqual({ held: 1, done: 0 });
await sender.clock.fastForward('06:00');
await expect(sender.locator('#send-error')).toHaveText(
'nobody received the file within 6 minutes, share it again',
new RegExp(`^nobody received the file ${UNTIL}, share it again$`),
);
await sender.evaluate(() => (window as unknown as { releaseDecrypts: () => void }).releaseDecrypts());
@@ -1324,10 +1482,10 @@ for (const name of Object.keys(BROWSERS)) {
await fastForward('06:00');
await fastForward(CONNECT_TIMEOUT);
await expect(sender.locator('#send-error')).toHaveText(
`no receiver connected within 6 minutes: the receiver ${NO_PUBLIC}`,
new RegExp(`^no receiver connected ${UNTIL}: the receiver ${NO_PUBLIC}$`),
);
await expect(receiver.locator('#receive-error')).toHaveText(
`no sender connected within 6 minutes: this side ${NO_PUBLIC}`,
new RegExp(`^no sender connected ${UNTIL}: this side ${NO_PUBLIC}$`),
);
await expectClosed(sender);
await expectClosed(receiver);
@@ -1346,7 +1504,7 @@ for (const name of Object.keys(BROWSERS)) {
await expect(sender.locator('#log')).toContainText(`waiting on ${TRACKER}`);
const code = (await sender.locator('#send-code').textContent())!;
await intrude(intruder, swarm(code));
await intruder.fill('#receive-code', 'notthecode');
await intruder.fill('#receive-code', 'notthecode0');
await intruder.click('#receive');
await expect(sender.locator('#log')).toContainText(`offer without the code via ${TRACKER}`, { timeout: 45_000 });
await intruder.context().close();
@@ -1366,7 +1524,6 @@ for (const name of Object.keys(BROWSERS)) {
test(`live check: ${name} sender gives up on a peer that proves nothing`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name, { init: withholdProof })]);
await sender.clock.install();
const source = await payload(randomBytes(SIZE));
await withLogs(sender, receiver, async () => {
@@ -1537,15 +1694,27 @@ async function interpose(middle: Page, code: string, toSender: Announce[], toRec
);
}
// What secrets in src/core.ts derives from the code for info, PBKDF2 once per code.
const masters = new Map<string, Buffer>();
function secret(code: string, info: string, length: number) {
if (!masters.has(code)) masters.set(code, pbkdf2Sync(code, 'hellcon', 600_000, 32, 'sha256'));
return Buffer.from(hkdfSync('sha256', masters.get(code)!, '', info, length));
// The salt src/core.ts derives with for a code made or entered around TEST_TIME: the start of the window
// the code's last character tells, the one nearest TEST_TIME's, then own if given.
function saltOf(code: string, own?: string) {
const now = Math.floor(TEST_TIME / SALT_WINDOW);
const cycle = CODE_CHARS.length;
const ahead = (((CODE_CHARS.indexOf(code.at(-1)!) - now) % cycle) + cycle) % cycle;
const salt = new Date((now + (ahead < cycle / 2 ? ahead : ahead - cycle)) * SALT_WINDOW).toISOString().slice(0, 16);
return own === undefined ? salt : `${salt} ${own}`;
}
// The code's info_hash.
const swarm = (code: string) => secret(code, 'swarm', 20).toString('latin1');
// What secrets in src/core.ts derives from the code and own salt for info, PBKDF2 once per pair.
const masters = new Map<string, Buffer>();
function secret(code: string, info: string, length: number, own?: string) {
const salt = saltOf(code, own);
const pair = JSON.stringify([code, salt]);
if (!masters.has(pair)) masters.set(pair, pbkdf2Sync(code, `hellcon ${salt}`, 600_000, 32, 'sha256'));
return Buffer.from(hkdfSync('sha256', masters.get(pair)!, '', info, length));
}
// The info_hash of the code with the own salt, if any.
const swarm = (code: string, own?: string) => secret(code, 'swarm', 20, own).toString('latin1');
// Seals and opens SDP like seal and unseal in src/core.ts. unseal throws on what wasn't sealed with the code.
function seal(code: string, type: 'offer' | 'answer', sdp: string) {
@@ -1610,14 +1779,11 @@ const garbageOffer = (code?: string) =>
const NO_PUBLIC = 'has no public address, between different networks both sides need STUN';
// A sender and a receiver as if on different networks, with the servers open and the clock installed.
// A sender and a receiver as if on different networks, with the servers open.
// Only the sender has a public address, from the fake STUN server, it answers nobody though.
async function apart(name: string) {
const pages = await Promise.all([open(name, { init: dropHosts }), open(name, { init: dropHosts })]);
for (const page of pages) {
await page.clock.install();
await page.click('#servers summary');
}
for (const page of pages) await page.click('#servers summary');
await pages[0]!.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}`);
await pages[1]!.uncheck('#stun');
return pages as [Page, Page];
@@ -1685,15 +1851,14 @@ function holdDecrypts() {
};
}
// Init script: window.deadlines() counts the core's pending TRACKER_WAIT timers, a session's expiry.
// The app's own one for the code is left out. It runs in the hidden frames too, only the app's own
// window counts.
// Init script: window.deadlines() counts the core's pending expiry timers, see deadline in
// src/core.ts. It runs in the hidden frames too, only the app's own window counts.
function countDeadlines() {
if (window !== window.top) return;
const pending = new Set<number>();
const { setTimeout: set, clearTimeout: clear } = window;
window.setTimeout = ((handler: () => void, ms?: number) => {
if (ms !== 6 * 60_000 || !new Error().stack?.includes('/src/core.ts')) return set(handler, ms);
if (!/\bdeadline\b.*\/src\/core\.ts/.test(new Error().stack ?? '')) return set(handler, ms);
const id = set(() => {
pending.delete(id);
handler();