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:
1 parent
21ea9a7e02
commit
bd0154db68
4 files changed
+201
-23
No files matched your search
+109
-1
@@ -31,10 +31,11 @@ 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, and CONNECT_TIMEOUT in src/core.ts.
|
||||
const WINDOW = 8 * 2 ** 20;
|
||||
const PROBE_TIMEOUT = 2000;
|
||||
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.
|
||||
const HELD_SIZE = 3 * WINDOW;
|
||||
// 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');
|
||||
});
|
||||
|
||||
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.
|
||||
@@ -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
|
||||
// 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 +1520,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+79
-22
@@ -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.
|
||||
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 +104,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 +346,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.
|
||||
@@ -738,13 +756,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 +790,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 +805,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 +822,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 +927,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 +950,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 +975,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 +996,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 +1075,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 +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.
|
||||
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 +1131,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 +1153,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 +1188,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}`));
|
||||
},
|
||||
() => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user