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>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-25 19:55:45 +01:00
1 parent 21ea9a7e02
commit bd0154db68
4 files changed
+201 -23

No files matched your search

+109 -1
View File
@@ -31,10 +31,11 @@ const SIZE = 5_000_000;
const LARGE_SIZE = 2.5 * 2 ** 30; const LARGE_SIZE = 2.5 * 2 ** 30;
// Big enough that the transfer still runs while a test cancels or disconnects. // Big enough that the transfer still runs while a test cancels or disconnects.
const RUNNING_SIZE = 100_000_000; const RUNNING_SIZE = 100_000_000;
// WINDOW, PROBE_TIMEOUT and PROOF_TIMEOUT in src/core.ts. // WINDOW, PROBE_TIMEOUT, PROOF_TIMEOUT, and CONNECT_TIMEOUT in src/core.ts.
const WINDOW = 8 * 2 ** 20; const WINDOW = 8 * 2 ** 20;
const PROBE_TIMEOUT = 2000; const PROBE_TIMEOUT = 2000;
const PROOF_TIMEOUT = 10_000; const PROOF_TIMEOUT = 10_000;
const CONNECT_TIMEOUT = 30_000;
// Enough for a transfer whose receiver holds back its reads to pause at the window. // Enough for a transfer whose receiver holds back its reads to pause at the window.
const HELD_SIZE = 3 * WINDOW; const HELD_SIZE = 3 * WINDOW;
// What the fake STUN server reports as public address, reserved for documentation. // What the fake STUN server reports as public address, reserved for documentation.
@@ -494,6 +495,24 @@ for (const name of Object.keys(BROWSERS)) {
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev'); 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 // 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 // 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. // once, later connections go straight to the one that answered, until it stops.
@@ -1170,6 +1189,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 // 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. // 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 () => { test(`live check: ${name} sender shares on after a peer without the code`, async () => {
@@ -1444,6 +1520,38 @@ const garbageOffer = (code?: string) =>
offer: { type: 'offer', sdp: code ? seal(code, 'offer', 'garbage') : 'garbage' }, 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 // 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 // holds one for each thing it still has to close. It runs in the hidden frames too, only the app's
// own window counts. // own window counts.
+6
View File
@@ -263,6 +263,12 @@ function onReceive() {
</header> </header>
<main> <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"> <aside v-if="check" role="alert">
<p> <p>
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
+79 -22
View File
@@ -34,11 +34,13 @@ const PROBE_TIMEOUT = 2000;
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn. // A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
const TRACKER_TIMEOUT = 10_000; const TRACKER_TIMEOUT = 10_000;
// A tracker peer that got an answer but never opens the data channel gives up its turn after this, // 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; const CONNECT_TIMEOUT = 30_000;
// A share, or a receiver looking for one, gives up after this without a download: nobody announces // 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, // 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. // 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; export const TRACKER_WAIT = 6 * 60_000;
const MIN_INTERVAL = 30_000; const MIN_INTERVAL = 30_000;
// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms. // OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms.
@@ -102,12 +104,12 @@ function live<T extends Record<string, (...args: never[]) => void>>(events: T, s
) as T; ) as T;
} }
// Runs expire after TRACKER_WAIT unless closed before, cleared with the session. // Runs expire after ms unless closed before, cleared with the session.
function deadline(signal: AbortSignal, expire: () => void) { function deadline(signal: AbortSignal, expire: () => void, ms = TRACKER_WAIT) {
const timer = setTimeout(() => { const timer = setTimeout(() => {
owned.close(); owned.close();
expire(); expire();
}, TRACKER_WAIT); }, ms);
const owned = own(signal, { close: () => clearTimeout(timer) }); const owned = own(signal, { close: () => clearTimeout(timer) });
return owned; return owned;
} }
@@ -344,6 +346,22 @@ async function gatherIce(pc: RTCPeerConnection) {
if (server && !reported && pc.signalingState !== 'closed') void stunFailed([server.urls].flat()[0]!); 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 // 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 // brute force with matching certificates. My local code must equal the peer's remote code and vice
// versa, otherwise someone interposed on the signaling. // versa, otherwise someone interposed on the signaling.
@@ -738,13 +756,31 @@ function receiveFile(
} }
// The manual exchange has nobody else to try: a connection that fails before the data channel opened, // 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. // e.g. after a wrong answer or between networks without STUN, ends the session. Chromium never fails
function failUnconnected(pc: RTCPeerConnection, opened: () => boolean, events: Events) { // one without usable addresses, so the returned wait also ends it once ms passed without connecting,
pc.addEventListener('connectionstatechange', () => { // counted from when the peer can connect. peer names the other side.
if (pc.connectionState !== 'failed' || opened()) return; 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(); 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. // Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
@@ -754,7 +790,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
const pc = await createPeerConnection(signal); const pc = await createPeerConnection(signal);
const channel = pc.createDataChannel('file'); const channel = pc.createDataChannel('file');
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal); 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 pc.setLocalDescription();
await gatherIce(pc); await gatherIce(pc);
@@ -769,6 +805,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
await pc.setRemoteDescription(description).catch(() => { await pc.setRemoteDescription(description).catch(() => {
throw new Error('not a valid answer to this offer, copy all of it'); throw new Error('not a valid answer to this offer, copy all of it');
}); });
wait(CONNECT_TIMEOUT);
}, },
}; };
} }
@@ -785,13 +822,14 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
opened = true; opened = true;
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events), signal); 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(() => { await pc.setRemoteDescription(description).catch(() => {
pc.close(); pc.close();
throw new Error('not a valid offer, copy all of it'); throw new Error('not a valid offer, copy all of it');
}); });
await pc.setLocalDescription(); await pc.setLocalDescription();
await gatherIce(pc); await gatherIce(pc);
wait(TRACKER_WAIT);
return btoa(pc.localDescription!.sdp); return btoa(pc.localDescription!.sdp);
} }
@@ -889,14 +927,19 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
let expired = false; let expired = false;
// The latest offer that came while busy, answered once that peer is out. // The latest offer that came while busy, answered once that peer is out.
let waiting: (() => Promise<void>) | undefined; 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. // Without a tracker no further receiver can find the share.
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive()); 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, () => { const expiry = deadline(signal, () => {
expired = true; expired = true;
for (const tracker of trackers) tracker.close(); for (const tracker of trackers) tracker.close();
if (stranded()) events.error(nobody); if (stranded()) events.error(nobody());
}); });
// Once stranded the share is over. // Once stranded the share is over.
const end = (reason: string) => { const end = (reason: string) => {
@@ -907,7 +950,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
function next() { function next() {
busy = false; busy = false;
if (signal.aborted) return; 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'); events.log('waiting for the next receiver');
const offer = waiting; const offer = waiting;
waiting = undefined; waiting = undefined;
@@ -932,7 +975,12 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
pc.close(); pc.close();
next(); 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 }) => { pc.ondatachannel = ({ channel }) => {
if (settled) return; if (settled) return;
settled = true; settled = true;
@@ -948,7 +996,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
void sendFile(pc, channel, file, events, { ...handshake, start }, signal); void sendFile(pc, channel, file, events, { ...handshake, start }, signal);
}; };
pc.addEventListener('connectionstatechange', () => { pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed') giveUp('receiver did not connect'); if (pc.connectionState === 'failed') unconnected();
}); });
let sdp: string; let sdp: string;
try { try {
@@ -1027,8 +1075,13 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
let isConnected = false; let isConnected = false;
let started = false; let started = false;
let expired = 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. // Without a sender connected the search is over, every offer goes.
const end = (reason: string) => { const end = (reason: string) => {
expiry.close(); expiry.close();
@@ -1041,14 +1094,14 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
// A connected sender keeps its connection, the other offers wait for next or start. // A connected sender keeps its connection, the other offers wait for next or start.
const expiry = deadline(signal, () => { const expiry = deadline(signal, () => {
expired = true; expired = true;
if (!isConnected) return end(nobody); if (!isConnected) return end(nobody());
for (const { tracker } of offers.values()) tracker?.close(); for (const { tracker } of offers.values()) tracker?.close();
}); });
const next = () => { const next = () => {
isConnected = false; isConnected = false;
if (signal.aborted) return; if (signal.aborted) return;
if (expired) return end(nobody); if (expired) return end(nobody());
events.log('looking again'); events.log('looking again');
for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i); for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i);
}; };
@@ -1078,6 +1131,11 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
pc.close(); pc.close();
if (!isConnected && !started && !signal.aborted && !expired) void offer(i); 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 = () => { channel.onopen = () => {
clearTimeout(timeout); clearTimeout(timeout);
if (isConnected || started) return pc.close(); if (isConnected || started) return pc.close();
@@ -1095,8 +1153,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
receiveFile(pc, channel, events, { ...handshake, start }, signal); receiveFile(pc, channel, events, { ...handshake, start }, signal);
}; };
pc.addEventListener('connectionstatechange', () => { pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed' && channel.readyState === 'connecting') if (pc.connectionState === 'failed' && channel.readyState === 'connecting') unconnected();
retry(`sender via ${url} did not connect`);
}); });
pc.setLocalDescription() pc.setLocalDescription()
@@ -1131,7 +1188,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
if (answer === undefined) return events.log(`answer without the code via ${url}`); if (answer === undefined) return events.log(`answer without the code via ${url}`);
events.log(`answer via ${url}`); events.log(`answer via ${url}`);
tracker.close(); 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}`)); 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); padding-bottom: var(--space-8);
} }
main > p,
main > aside, main > aside,
main > details { main > details {
grid-column: 1 / -1; 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 */ /* Cards */
article, article,