Compare commits

...
2 Commits
Author SHA1 Message Date
SchluffeandClaude Opus 5.5 3c4e706e1f Keep a finished download's frame for a moment
Small downloads, empty or one byte, were sometimes never saved, though the worker reported them
finished and both sides logged success. The browser can read the whole response before it hands
the navigation to its download manager, and the frame was removed right then, which cancels it.
Without a delay an empty file failed 8 of 10 runs, a one byte file 4 of 10.

The download's frame now stays for DOWNLOAD_GRACE (1 s) after finished, the frame that holds the
worker still goes right away. No event tells when the browser took the download, so the 1 s is
empirical. A new test checks the retention on a paused clock, it fails without the delay and with
the worker's frame held too. The browser's timing it can't cover, TODO.md keeps a record of that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:55:45 +01:00
SchluffeandClaude Opus 5.5 bd0154db68 Tell the user when a missing public address explains a failed connection
Without STUN a side offers only local addresses, enough on the same network or VPN. Between
networks the connection never came up, and nothing said why: tracker signaling only logged "did
not connect" and ended after 6 minutes with the generic message, the manual exchange in Chromium
never ended at all, since Chromium doesn't fail a connection without usable addresses.

A connection that doesn't come up now checks both SDPs for a public address (typ srflx) and names
the side without one, in the log and in the error at the end of the session. That covers STUN
turned off, an empty list and servers that don't answer, on either side. A device with a public
address of its own offers none either, so it's a hint. The manual sender gives up 30 s after the
answer, the receiver after 6 minutes, it has to hand the answer over first.

A note above the cards says when STUN is off or no server is listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:55:45 +01:00
5 changed files with 252 additions and 31 deletions

No files matched your search

+8 -4
View File
@@ -23,7 +23,11 @@
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again.
- `boundary: chromium sends an empty file` timed out in the first two full runs after `backend/`'s
tests were added (2026-10-25), with empty logs on both sides. It passed alone 8 times, and in 7
full runs since, one of them with a cold Vite cache. The suite without the new tests passed 4
times. Not reproduced, cause unknown.
- Small downloads (empty, one byte) were sometimes never saved, though the worker reported them
finished and both sides logged success: the browser can read the whole response before it hands
the navigation to its download manager, and removing the frame before that cancels it. Without a
delay `boundary: … sends an empty file` failed 8 of 10 runs, the one byte file 4 of 10. The
workaround `DOWNLOAD_GRACE` keeps the download's frame 1 s after finished. No event tells when the
browser took the download, so the 1 s is empirical: `boundary: … keeps a finished download's frame
for DOWNLOAD_GRACE` covers the retention, not the browser's timing. A small download that goes
missing again means it's too short.
+140 -1
View File
@@ -31,10 +31,12 @@ const SIZE = 5_000_000;
const LARGE_SIZE = 2.5 * 2 ** 30;
// Big enough that the transfer still runs while a test cancels or disconnects.
const RUNNING_SIZE = 100_000_000;
// WINDOW, PROBE_TIMEOUT and PROOF_TIMEOUT in src/core.ts.
// WINDOW, PROBE_TIMEOUT, PROOF_TIMEOUT, CONNECT_TIMEOUT and DOWNLOAD_GRACE in src/core.ts.
const WINDOW = 8 * 2 ** 20;
const PROBE_TIMEOUT = 2000;
const PROOF_TIMEOUT = 10_000;
const CONNECT_TIMEOUT = 30_000;
const DOWNLOAD_GRACE = 1000;
// 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.
@@ -494,6 +496,24 @@ for (const name of Object.keys(BROWSERS)) {
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
});
test(`servers: ${name} notes while no STUN server would be used`, async () => {
const page = await open(name);
await expect(page.locator('#no-stun')).toHaveCount(0);
await page.uncheck('#stun');
await expect(page.locator('#no-stun')).toHaveText(
'STUN is off: only devices on the same network or VPN can connect.',
);
await page.check('#stun');
await page.click('#servers summary');
// A line this browser rejects is no server either.
await page.fill('#stun-servers', 'stun:stun.example:99999');
await expect(page.locator('#no-stun')).toHaveText(
'No STUN server under Servers: only devices on the same network or VPN can connect.',
);
await page.click('#reset-servers');
await expect(page.locator('#no-stun')).toHaveCount(0);
});
// Only the STUN server in use learns the address. 192.0.2.1 is reserved for documentation and never
// answers, a connection with it would wait ICE_TIMEOUT in src/core.ts. The probe passes it over
// once, later connections go straight to the one that answered, until it stops.
@@ -653,7 +673,9 @@ for (const name of Object.keys(BROWSERS)) {
// The edges of the chunking and the window, and a name the Content-Disposition header has to encode.
for (const [what, file, size] of [
// Read whole before the browser takes the download, see DOWNLOAD_GRACE in src/core.ts.
['an empty file', 'empty.bin', 0],
['a one byte file', 'one.bin', 1],
// Firefox would save a % as _.
['a file one byte past the window', "l'été (1) 🚀.bin", WINDOW + 1],
] as const) {
@@ -663,6 +685,34 @@ for (const name of Object.keys(BROWSERS)) {
});
}
// When the browser takes a download is beyond the test, how long the frame stays is not: on the
// paused clock the download's frame stays, so the download has to arrive, and goes after exactly
// 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'));
await sender.click('#confirm');
await receiver.click('#confirm');
await expect(receiver.locator('#incoming')).toContainText('empty.bin');
await receiver.clock.pauseAt(await receiver.evaluate(() => Date.now() + 1));
const started = downloadStarts(receiver);
await receiver.click('#download');
await expect(receiver.locator('#log')).toContainText('download complete');
const frames = receiver.locator('iframe');
await expect(frames).toHaveCount(1);
await expect(frames).toHaveAttribute('src', /^download\/./);
const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(test.info().outputPath('empty.bin')));
await receiver.clock.runFor(DOWNLOAD_GRACE - 1);
await expect(frames).toHaveCount(1);
await receiver.clock.runFor(1);
await expect(frames).toHaveCount(0);
});
});
// Share, Receive and the manual exchange each start a session, a new one ends the one before.
test(`session: ${name} a new operation ends the previous one`, async () => {
const [sender, receiver] = await Promise.all([open(name), open(name)]);
@@ -1170,6 +1220,63 @@ for (const name of Object.keys(BROWSERS)) {
});
});
// Between networks a side without a public address connects nobody. Chromium never fails such a
// connection, the timeouts end it. The sender has one from the fake STUN server, the receiver has
// STUN off.
test(`hint: ${name} manual exchange names the side without a public address`, async () => {
const [sender, receiver] = await apart(name);
await withLogs(sender, receiver, async () => {
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await MODES.manual!(sender, receiver);
// The timeout starts once the answer is set.
await expect
.poll(() =>
sender.evaluate(() =>
(window as unknown as { peers: RTCPeerConnection[] }).peers.some((pc) => pc.signalingState === 'stable'),
),
)
.toBe(true);
await sender.clock.fastForward(CONNECT_TIMEOUT);
await expect(sender.locator('#send-error')).toHaveText(`could not connect: the receiver ${NO_PUBLIC}`);
await receiver.clock.fastForward('06:00');
await expect(receiver.locator('#receive-error')).toHaveText(`could not connect: this side ${NO_PUBLIC}`);
await expectClosed(sender);
await expectClosed(receiver);
});
});
// Each failed connection says why in the log, the expiry repeats the last reason.
test(`hint: ${name} tracker signaling names the side without a public address`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await apart(name);
const fastForward = (time: number | string) =>
Promise.all([sender, receiver].map((page) => page.clock.fastForward(time)));
await withLogs(sender, receiver, async () => {
for (const page of [sender, receiver]) await page.fill('#trackers', tracker);
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
await MODES.tracker!(sender, receiver);
await expect(receiver.locator('#log')).toContainText(`answer via ${tracker}`);
await fastForward(CONNECT_TIMEOUT);
await expect(sender.locator('#log')).toContainText(`receiver did not connect: the receiver ${NO_PUBLIC}`);
await expect(receiver.locator('#log')).toContainText(
`sender via ${tracker} did not connect: this side ${NO_PUBLIC}`,
);
// Then once more for the turn a new offer may have taken meanwhile.
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}`,
);
await expect(receiver.locator('#receive-error')).toHaveText(
`no sender connected within 6 minutes: this side ${NO_PUBLIC}`,
);
await expectClosed(sender);
await expectClosed(receiver);
});
});
// A peer that found the swarm without the code, here one that announces another code on the
// sender's info_hash. Its offer isn't sealed with the code, the sender doesn't even answer it.
test(`live check: ${name} sender shares on after a peer without the code`, async () => {
@@ -1444,6 +1551,38 @@ const garbageOffer = (code?: string) =>
offer: { type: 'offer', sdp: code ? seal(code, 'offer', 'garbage') : 'garbage' },
});
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.
// 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');
}
await pages[0]!.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}`);
await pages[1]!.uncheck('#stun');
return pages as [Page, Page];
}
// Init script: drops the local addresses from every description the peer sends, as if it were on
// another network. It runs in the hidden frames too, only the app's own window counts.
function dropHosts() {
if (window !== window.top) return;
const set = RTCPeerConnection.prototype.setRemoteDescription as (
this: RTCPeerConnection,
description: RTCSessionDescriptionInit,
) => Promise<void>;
RTCPeerConnection.prototype.setRemoteDescription = function (
this: RTCPeerConnection,
description: RTCSessionDescriptionInit,
) {
const lines = description.sdp?.split('\r\n').filter((line) => !/^a=candidate:.* typ host\b/.test(line));
return set.call(this, { ...description, sdp: lines?.join('\r\n') });
};
}
// Init script: window.abortListeners() counts the abort listeners on every signal. A session's signal
// holds one for each thing it still has to close. It runs in the hidden frames too, only the app's
// own window counts.
+6
View File
@@ -263,6 +263,12 @@ function onReceive() {
</header>
<main>
<p v-if="!settings.stun" id="no-stun" role="note">
STUN is off: only devices on the same network or VPN can connect.
</p>
<p v-else-if="!settings.stunServers.length" id="no-stun" role="note">
No STUN server under Servers: only devices on the same network or VPN can connect.
</p>
<aside v-if="check" role="alert">
<p>
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
+91 -26
View File
@@ -27,6 +27,10 @@ const WINDOW = 8 * 1024 * 1024;
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
const KEEPALIVE = 10_000;
// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its
// download manager. Its frame removed before that, the download never shows up, though the worker
// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests.
const DOWNLOAD_GRACE = 1000;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
// A STUN server that reports no public address by then gets passed over, see stunServer.
@@ -34,11 +38,13 @@ const PROBE_TIMEOUT = 2000;
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
const TRACKER_TIMEOUT = 10_000;
// A tracker peer that got an answer but never opens the data channel gives up its turn after this,
// e.g. one whose SDP has no usable candidates: its connection never even fails.
// e.g. one whose SDP has no usable candidates: Chromium never even fails its connection. The manual
// sender gives up on the answer after it as well.
const CONNECT_TIMEOUT = 30_000;
// A share, or a receiver looking for one, gives up after this without a download: nobody announces
// all day for a code nobody uses. Until then both announce again on the interval the tracker names,
// else it drops them after a few minutes, but not more often than MIN_INTERVAL whatever it names.
// The manual receiver waits this long for the sender to connect, it has to get the answer first.
export const TRACKER_WAIT = 6 * 60_000;
const MIN_INTERVAL = 30_000;
// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms.
@@ -102,12 +108,12 @@ function live<T extends Record<string, (...args: never[]) => void>>(events: T, s
) as T;
}
// Runs expire after TRACKER_WAIT unless closed before, cleared with the session.
function deadline(signal: AbortSignal, expire: () => void) {
// Runs expire after ms unless closed before, cleared with the session.
function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) {
const timer = setTimeout(() => {
owned.close();
expire();
}, TRACKER_WAIT);
}, ms);
const owned = own(signal, { close: () => clearTimeout(timer) });
return owned;
}
@@ -344,6 +350,22 @@ async function gatherIce(pc: RTCPeerConnection) {
if (server && !reported && pc.signalingState !== 'closed') void stunFailed([server.urls].flat()[0]!);
}
// Why pc didn't connect, if a missing public address explains it: a side without one from STUN offers
// only local addresses, enough on the same network or VPN. peer names the other side. A device with
// a public address of its own offers none either, see stunServer, so it's a hint, not a diagnosis.
function stunHint(pc: RTCPeerConnection, peer: string) {
const offersPublic = (description: RTCSessionDescription | null) => / typ srflx\b/.test(description?.sdp ?? '');
const local = offersPublic(pc.localDescription);
const remote = offersPublic(pc.remoteDescription);
if (local && remote) return;
const missing = local
? `the ${peer} has no public address`
: remote
? 'this side has no public address'
: 'neither side has a public address';
return `${missing}, between different networks both sides need STUN`;
}
// 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.
@@ -613,10 +635,14 @@ function receiveFile(
let keepalive: ReturnType<typeof setInterval> | undefined;
// Releases the worker, so a waiting update can take over.
function release() {
// Releases the worker, so a waiting update can take over. A finished download keeps its own frame
// for DOWNLOAD_GRACE, that one doesn't hold the worker.
function release(finished = false) {
clearInterval(keepalive);
for (const frame of frames) frame.remove();
const [hold, download] = frames;
hold?.remove();
if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE);
else download?.remove();
}
// The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the
@@ -669,7 +695,7 @@ function receiveFile(
}
ended = true;
channel.close();
release();
release(data === 'finished');
};
worker.postMessage({ id, ...meta }, [port2]);
return worker;
@@ -738,13 +764,31 @@ function receiveFile(
}
// The manual exchange has nobody else to try: a connection that fails before the data channel opened,
// e.g. after a wrong answer or between networks without STUN, ends the session.
function failUnconnected(pc: RTCPeerConnection, opened: () => boolean, events: Events) {
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState !== 'failed' || opened()) return;
// e.g. after a wrong answer or between networks without STUN, ends the session. Chromium never fails
// one without usable addresses, so the returned wait also ends it once ms passed without connecting,
// counted from when the peer can connect. peer names the other side.
function failUnconnected(
pc: RTCPeerConnection,
opened: () => boolean,
events: Events,
signal: AbortSignal,
peer: string,
) {
let expiry: { close: () => void } | undefined;
const fail = () => {
expiry?.close();
if (opened() || pc.signalingState === 'closed') return;
const hint = stunHint(pc, peer);
pc.close();
events.error('could not connect, check the codes. Between different networks both sides need STUN');
events.error(hint ? `could not connect: ${hint}` : 'could not connect, check the codes');
};
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'connected') expiry?.close();
if (pc.connectionState === 'failed') fail();
});
return (ms: number) => {
expiry = deadline(signal, fail, ms);
};
}
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
@@ -754,7 +798,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
const pc = await createPeerConnection(signal);
const channel = pc.createDataChannel('file');
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
failUnconnected(pc, () => channel.readyState !== 'connecting', events);
const wait = failUnconnected(pc, () => channel.readyState !== 'connecting', events, signal, 'receiver');
await pc.setLocalDescription();
await gatherIce(pc);
@@ -769,6 +813,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
await pc.setRemoteDescription(description).catch(() => {
throw new Error('not a valid answer to this offer, copy all of it');
});
wait(CONNECT_TIMEOUT);
},
};
}
@@ -785,13 +830,14 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
opened = true;
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events), signal);
};
failUnconnected(pc, () => opened, events);
const wait = failUnconnected(pc, () => opened, events, signal, 'sender');
await pc.setRemoteDescription(description).catch(() => {
pc.close();
throw new Error('not a valid offer, copy all of it');
});
await pc.setLocalDescription();
await gatherIce(pc);
wait(TRACKER_WAIT);
return btoa(pc.localDescription!.sdp);
}
@@ -889,14 +935,19 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
let expired = false;
// The latest offer that came while busy, answered once that peer is out.
let waiting: (() => Promise<void>) | undefined;
// Why the last receiver that answered didn't connect, if a missing public address explains it.
let hint: string | undefined;
// Without a tracker no further receiver can find the share.
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
const nobody = `nobody received the file within ${TRACKER_WAIT / 60_000} minutes, share it again`;
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);
if (stranded()) events.error(nobody());
});
// Once stranded the share is over.
const end = (reason: string) => {
@@ -907,7 +958,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
function next() {
busy = false;
if (signal.aborted) return;
if (stranded()) return end(expired ? nobody : noTracker(trackers));
if (stranded()) return end(expired ? nobody() : noTracker(trackers));
events.log('waiting for the next receiver');
const offer = waiting;
waiting = undefined;
@@ -932,7 +983,12 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
pc.close();
next();
};
const timeout = setTimeout(() => giveUp('receiver did not connect'), CONNECT_TIMEOUT);
const unconnected = () => {
if (settled) return;
hint = stunHint(pc, 'receiver');
giveUp(hint ? `receiver did not connect: ${hint}` : 'receiver did not connect');
};
const timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
pc.ondatachannel = ({ channel }) => {
if (settled) return;
settled = true;
@@ -948,7 +1004,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
void sendFile(pc, channel, file, events, { ...handshake, start }, signal);
};
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
if (pc.connectionState === 'failed') unconnected();
});
let sdp: string;
try {
@@ -1027,8 +1083,13 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
let isConnected = false;
let started = false;
let expired = false;
// Why the last sender that answered didn't connect, if a missing public address explains it.
let hint: string | undefined;
const nobody = `no sender answered within ${TRACKER_WAIT / 60_000} minutes, check the code and try again`;
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`;
// Without a sender connected the search is over, every offer goes.
const end = (reason: string) => {
expiry.close();
@@ -1041,14 +1102,14 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
// 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);
if (!isConnected) return end(nobody());
for (const { tracker } of offers.values()) tracker?.close();
});
const next = () => {
isConnected = false;
if (signal.aborted) return;
if (expired) return end(nobody);
if (expired) return end(nobody());
events.log('looking again');
for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i);
};
@@ -1078,6 +1139,11 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
pc.close();
if (!isConnected && !started && !signal.aborted && !expired) void offer(i);
};
const unconnected = () => {
if (pc.signalingState === 'closed') return;
hint = stunHint(pc, 'sender');
retry(hint ? `sender via ${url} did not connect: ${hint}` : `sender via ${url} did not connect`);
};
channel.onopen = () => {
clearTimeout(timeout);
if (isConnected || started) return pc.close();
@@ -1095,8 +1161,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
receiveFile(pc, channel, events, { ...handshake, start }, signal);
};
pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed' && channel.readyState === 'connecting')
retry(`sender via ${url} did not connect`);
if (pc.connectionState === 'failed' && channel.readyState === 'connecting') unconnected();
});
pc.setLocalDescription()
@@ -1131,7 +1196,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
if (answer === undefined) return events.log(`answer without the code via ${url}`);
events.log(`answer via ${url}`);
tracker.close();
timeout = setTimeout(() => retry(`sender via ${url} did not connect`), CONNECT_TIMEOUT);
timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`));
},
() => {
+7
View File
@@ -136,11 +136,18 @@ main {
padding-bottom: var(--space-8);
}
main > p,
main > aside,
main > details {
grid-column: 1 / -1;
}
/* Note while no STUN server would be used, quiet above the cards */
#no-stun {
font-size: var(--text-sm);
color: var(--color-text-muted);
}
/* Cards */
article,