Release 0.0.6 with reconnect fixes and regression coverage
This commit is contained in:
1 parent
acba97a7e1
commit
9f3f21884f
10 files changed
+279
-36
No files matched your search
+27
-1
@@ -1,6 +1,32 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [0.0.5] - Draft (unreleased)
|
## [0.0.6] - 2026-10-21
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Cancelling tracker reconnect now settles the pending WebSocket connection
|
||||||
|
immediately and clears its timeout. Socket send failures are reported cleanly.
|
||||||
|
- Late answers cannot reach a replacement WebRTC connection while its new offer
|
||||||
|
is gathering.
|
||||||
|
- Unauthenticated tracker messages cannot suppress valid offers or evict entries
|
||||||
|
from the replay cache.
|
||||||
|
- Rapidly accepting a reconnect proposal twice no longer starts competing key
|
||||||
|
derivations or leaves setup with an unexpected-message error.
|
||||||
|
- Tracker integration tests run in a fresh container on every invocation instead
|
||||||
|
of reusing Docker's cached test results.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Regression coverage for tracker cancellation and failures, stale answers,
|
||||||
|
replay handling, retry limits, pairing verification, repeated acceptance and
|
||||||
|
reconnect lock handoff between browser tabs.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Document experimental tracker reconnect setup, privacy, revocation and limits
|
||||||
|
in the README.
|
||||||
|
|
||||||
|
## [0.0.5] - Development draft
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
# HellCon
|
# HellCon
|
||||||
|
|
||||||
Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release
|
Current version: **0.0.6**. See the [changelog](CHANGELOG.md) for release
|
||||||
notes and compatibility changes.
|
notes and compatibility changes.
|
||||||
|
|
||||||
Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts, no
|
Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts or
|
||||||
signaling backend, and no server-side file storage: you exchange connection codes
|
server-side file storage. Exchange connection codes through a messenger, or
|
||||||
yourself, through any messenger. Connections are direct by
|
opt in to experimental tracker reconnect for remembered devices. Manual codes
|
||||||
|
need no signaling backend. Connections are direct by
|
||||||
default. A TURN relay is used only when both people opt in.
|
default. A TURN relay is used only when both people opt in.
|
||||||
|
|
||||||
This is experimental software, not independently audited or battle-tested.
|
This is experimental software, not independently audited or battle-tested.
|
||||||
@@ -27,9 +28,9 @@ has its own setup and live session.
|
|||||||
|
|
||||||
Switching connections keeps active transfers and selected files alive while the
|
Switching connections keeps active transfers and selected files alive while the
|
||||||
tab stays open. Closing or reloading the page ends live sessions and discards
|
tab stays open. Closing or reloading the page ends live sessions and discards
|
||||||
selected files; reconnect with fresh codes. On small screens, **Show
|
selected files; reconnect with fresh codes or a saved tracker pairing. On small
|
||||||
connections** opens the sidebar, and the bar beside it shows the open connection
|
screens, **Show connections** opens the sidebar, and the bar beside it shows the
|
||||||
and its status.
|
open connection and its status.
|
||||||
|
|
||||||
Names and remembered devices are saved in this browser. Transfer history, file
|
Names and remembered devices are saved in this browser. Transfer history, file
|
||||||
contents, connection codes, and relay credentials are not. Clearing site data
|
contents, connection codes, and relay credentials are not. Clearing site data
|
||||||
@@ -135,6 +136,28 @@ remembering. Public identities in codes can link sessions. Browser-stored keys
|
|||||||
are usable by any code the host serves, so they do not protect against a
|
are usable by any code the host serves, so they do not protect against a
|
||||||
malicious host. See [the identity protocol and storage](docs/device-identities.md).
|
malicious host. See [the identity protocol and storage](docs/device-identities.md).
|
||||||
|
|
||||||
|
### Experimental reconnect without codes
|
||||||
|
|
||||||
|
Once both browsers have remembered each other in a verified session:
|
||||||
|
|
||||||
|
1. Under **Network settings → Connection discovery**, choose a custom `wss://`
|
||||||
|
WebTorrent tracker, or the host's default if one is configured.
|
||||||
|
2. Click **Set up reconnect**. The other person checks the tracker host and
|
||||||
|
accepts. Both browsers must save the settings before setup reports success.
|
||||||
|
3. After disconnecting or reloading, both people open their saved connection and
|
||||||
|
press **Reconnect**. Fresh device proofs authenticate the session; each file
|
||||||
|
still requires acceptance. TURN still requires both people to opt in.
|
||||||
|
|
||||||
|
The tracker sees IP addresses, timing and encrypted signaling sizes; codes and
|
||||||
|
files remain private from it. The pairing key stays in browser storage. Changing
|
||||||
|
Connection discovery applies to new setups; existing pairings keep their tracker.
|
||||||
|
**Turn off reconnect** removes the local pairing. The other browser removes its
|
||||||
|
copy at the next authenticated manual session if the pairings no longer match.
|
||||||
|
|
||||||
|
If reconnect fails, exchange fresh codes. Reconnect attempts started on opposite
|
||||||
|
sides of UTC midnight need restarting. See the [implementation status and
|
||||||
|
limits](docs/webtorrent-reconnect.md#concept-status).
|
||||||
|
|
||||||
## Privacy and security
|
## Privacy and security
|
||||||
|
|
||||||
### Connection codes
|
### Connection codes
|
||||||
@@ -328,8 +351,9 @@ bun run tracker:down
|
|||||||
```
|
```
|
||||||
|
|
||||||
See [the tracker README](tracker/README.md) for configuration and VPS use.
|
See [the tracker README](tracker/README.md) for configuration and VPS use.
|
||||||
Automatic reconnect in the browser is still
|
The browser supports opt-in [experimental tracker reconnect](#experimental-reconnect-without-codes).
|
||||||
[planned](docs/webtorrent-reconnect.md); the app uses manual codes.
|
For a local integration check, run `bun run test:browser --tracker=ws://127.0.0.1:8000`
|
||||||
|
after building the app and starting the tracker.
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "hellcon",
|
"name": "hellcon",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.5",
|
"version": "0.0.6",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
"turn:down": "docker compose --env-file .env.development down",
|
"turn:down": "docker compose --env-file .env.development down",
|
||||||
"tracker:up": "docker compose -f compose.tracker.yaml up -d --build --wait",
|
"tracker:up": "docker compose -f compose.tracker.yaml up -d --build --wait",
|
||||||
"tracker:down": "docker compose -f compose.tracker.yaml down",
|
"tracker:down": "docker compose -f compose.tracker.yaml down",
|
||||||
"test:tracker": "docker build --target test -t hellcon-tracker:test tracker",
|
"test:tracker": "docker build --target test -t hellcon-tracker:test tracker && docker run --rm hellcon-tracker:test",
|
||||||
"test:turn": "node scripts/browser-check.ts --turn",
|
"test:turn": "node scripts/browser-check.ts --turn",
|
||||||
"build": "vue-tsc --noEmit && vite build",
|
"build": "vue-tsc --noEmit && vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
|
|||||||
@@ -636,7 +636,9 @@ try {
|
|||||||
await checkAccessibility(identityReceiver, 'reconnect proposal');
|
await checkAccessibility(identityReceiver, 'reconnect proposal');
|
||||||
if (screenshotDirectory) await evaluate(identityReceiver, () => window.__hellcon.element('.reconnect-setup').scrollIntoView({ block: 'center' }));
|
if (screenshotDirectory) await evaluate(identityReceiver, () => window.__hellcon.element('.reconnect-setup').scrollIntoView({ block: 'center' }));
|
||||||
await screenshot(identityReceiver, 'reconnect-proposal');
|
await screenshot(identityReceiver, 'reconnect-proposal');
|
||||||
await click(identityReceiver, 'Accept');
|
// Two clicks can arrive before Vue rerenders the button. Consent must
|
||||||
|
// start only one key derivation and send only one acceptance.
|
||||||
|
await evaluate(identityReceiver, () => { window.__hellcon.click('Accept'); window.__hellcon.click('Accept'); });
|
||||||
for (const session of both) await wait(session, () => document.body.textContent?.includes('Reconnect is set up on both devices'));
|
for (const session of both) await wait(session, () => document.body.textContent?.includes('Reconnect is set up on both devices'));
|
||||||
for (const session of both) assert.ok(await hasPairing(session));
|
for (const session of both) assert.ok(await hasPairing(session));
|
||||||
};
|
};
|
||||||
@@ -684,8 +686,21 @@ try {
|
|||||||
await input(session, '#stun-provider', 'none');
|
await input(session, '#stun-provider', 'none');
|
||||||
await wait(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reconnect' && !button.disabled));
|
await wait(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reconnect' && !button.disabled));
|
||||||
}
|
}
|
||||||
|
const competing = await page();
|
||||||
|
await wait(competing, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reconnect' && !button.disabled));
|
||||||
|
await input(competing, '#stun-provider', 'none');
|
||||||
await click(identitySender, 'Reconnect');
|
await click(identitySender, 'Reconnect');
|
||||||
await wait(identitySender, () => document.body.textContent?.includes('Waiting for your peer on'));
|
await wait(identitySender, () => document.body.textContent?.includes('Waiting for your peer on'));
|
||||||
|
await click(competing, 'Reconnect');
|
||||||
|
await wait(competing, () => document.body.textContent?.includes('Another HellCon tab is already reconnecting'));
|
||||||
|
assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('Waiting for your peer on')));
|
||||||
|
await click(identitySender, 'Cancel connection');
|
||||||
|
await click(competing, 'Reset'); await click(competing, 'Reconnect');
|
||||||
|
await wait(competing, () => document.body.textContent?.includes('Waiting for your peer on'));
|
||||||
|
await click(competing, 'Cancel connection');
|
||||||
|
await click(identitySender, 'Reconnect');
|
||||||
|
await wait(identitySender, () => document.body.textContent?.includes('Waiting for your peer on'));
|
||||||
|
console.log('PASS: another tab cannot reconnect the same slot; cancellation releases the lock for either tab to retry.');
|
||||||
await checkAccessibility(identitySender, 'reconnect waiting');
|
await checkAccessibility(identitySender, 'reconnect waiting');
|
||||||
if (screenshotDirectory) await evaluate(identitySender, () => [...document.querySelectorAll('button')].find(button => button.textContent === 'Reconnect')?.scrollIntoView({ block: 'start' }));
|
if (screenshotDirectory) await evaluate(identitySender, () => [...document.querySelectorAll('button')].find(button => button.textContent === 'Reconnect')?.scrollIntoView({ block: 'start' }));
|
||||||
await screenshot(identitySender, 'reconnect-waiting');
|
await screenshot(identitySender, 'reconnect-waiting');
|
||||||
|
|||||||
@@ -571,13 +571,19 @@ function proposePairing() {
|
|||||||
async function acceptPairing() {
|
async function acceptPairing() {
|
||||||
const session = active, setup = pairingSetup;
|
const session = active, setup = pairingSetup;
|
||||||
if (!session?.transfer || pairingState.value !== 'incoming' || !setup) return;
|
if (!session?.transfer || pairingState.value !== 'incoming' || !setup) return;
|
||||||
|
// Claim this proposal before key derivation yields; a second click must not
|
||||||
|
// replace its nonce or send a second acceptance while Vue is rerendering.
|
||||||
|
pairingState.value = 'accepted';
|
||||||
try {
|
try {
|
||||||
setup.acceptor = pairingNonce();
|
setup.acceptor = pairingNonce();
|
||||||
setup.key = await derivePairingKey(session, setup, false);
|
setup.key = await derivePairingKey(session, setup, false);
|
||||||
if (active !== session || pairingSetup !== setup) return;
|
if (active !== session || pairingSetup !== setup) return;
|
||||||
session.transfer.sendPairing({ step: 'accept', nonce: setup.acceptor });
|
session.transfer.sendPairing({ step: 'accept', nonce: setup.acceptor });
|
||||||
pairingState.value = 'accepted';
|
} catch (err) {
|
||||||
} catch (err) { pairingState.value = ''; pairingError.value = asError(err).message; }
|
if (active !== session || pairingSetup !== setup) return;
|
||||||
|
try { session.transfer.sendPairing({ step: 'error' }); } catch { /* the session ended */ }
|
||||||
|
pairingState.value = ''; pairingSetup = null; pairingError.value = asError(err).message;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
function declinePairing() {
|
function declinePairing() {
|
||||||
try { active?.transfer?.sendPairing({ step: 'decline' }); } catch { /* the session ended */ }
|
try { active?.transfer?.sendPairing({ step: 'decline' }); } catch { /* the session ended */ }
|
||||||
|
|||||||
+27
-9
@@ -26,6 +26,8 @@ export class TrackerClient {
|
|||||||
readonly peerId = randomId();
|
readonly peerId = randomId();
|
||||||
private socket: WebSocket | null = null;
|
private socket: WebSocket | null = null;
|
||||||
private timer?: ReturnType<typeof setTimeout>;
|
private timer?: ReturnType<typeof setTimeout>;
|
||||||
|
private connectTimer?: ReturnType<typeof setTimeout>;
|
||||||
|
private rejectConnect?: (error: Error) => void;
|
||||||
private closed = false;
|
private closed = false;
|
||||||
private readonly url: string;
|
private readonly url: string;
|
||||||
private readonly infoHash: string;
|
private readonly infoHash: string;
|
||||||
@@ -36,18 +38,25 @@ export class TrackerClient {
|
|||||||
this.url = url; this.infoHash = infoHash; this.events = events; this.connectSocket = connectSocket;
|
this.url = url; this.infoHash = infoHash; this.events = events; this.connectSocket = connectSocket;
|
||||||
}
|
}
|
||||||
connect() {
|
connect() {
|
||||||
|
if (this.closed) return Promise.reject(new Error('The tracker connection is closed.'));
|
||||||
|
if (this.socket) return Promise.reject(new Error('The tracker connection has already started.'));
|
||||||
return new Promise<void>((resolve, reject) => {
|
return new Promise<void>((resolve, reject) => {
|
||||||
let socket: WebSocket;
|
let socket: WebSocket;
|
||||||
try { socket = this.connectSocket(this.url); }
|
try { socket = this.connectSocket(this.url); }
|
||||||
catch { reject(new Error('Could not open the tracker connection. Check the tracker address and the site’s connect-src policy.')); return; }
|
catch { reject(new Error('Could not open the tracker connection. Check the tracker address and the site’s connect-src policy.')); return; }
|
||||||
this.socket = socket;
|
this.socket = socket;
|
||||||
const timeout = setTimeout(() => { reject(new Error('The tracker did not respond.')); this.close(); }, 15_000);
|
this.rejectConnect = reject;
|
||||||
socket.onopen = () => { clearTimeout(timeout); this.announce('started'); resolve(); };
|
this.connectTimer = setTimeout(() => this.fail(new Error('The tracker did not respond.')), 15_000);
|
||||||
|
socket.onopen = () => {
|
||||||
|
clearTimeout(this.connectTimer);
|
||||||
|
this.announce('started');
|
||||||
|
this.rejectConnect = undefined;
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
socket.onclose = () => {
|
socket.onclose = () => {
|
||||||
clearTimeout(timeout);
|
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
const error = new Error('Could not reach the tracker, or it closed the connection.');
|
const error = new Error('Could not reach the tracker, or it closed the connection.');
|
||||||
reject(error); this.fail(error);
|
this.fail(error);
|
||||||
};
|
};
|
||||||
socket.onmessage = event => this.receive(event.data);
|
socket.onmessage = event => this.receive(event.data);
|
||||||
});
|
});
|
||||||
@@ -66,7 +75,9 @@ export class TrackerClient {
|
|||||||
}
|
}
|
||||||
close() {
|
close() {
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
this.closed = true; clearTimeout(this.timer);
|
this.closed = true; clearTimeout(this.timer); clearTimeout(this.connectTimer);
|
||||||
|
this.rejectConnect?.(new Error('Tracker connection cancelled.'));
|
||||||
|
this.rejectConnect = undefined;
|
||||||
const socket = this.socket;
|
const socket = this.socket;
|
||||||
if (!socket) return;
|
if (!socket) return;
|
||||||
socket.onopen = socket.onclose = socket.onmessage = null;
|
socket.onopen = socket.onclose = socket.onmessage = null;
|
||||||
@@ -75,10 +86,13 @@ export class TrackerClient {
|
|||||||
}
|
}
|
||||||
private send(data: object, closing = false) {
|
private send(data: object, closing = false) {
|
||||||
if ((this.closed && !closing) || this.socket?.readyState !== WebSocket.OPEN) return;
|
if ((this.closed && !closing) || this.socket?.readyState !== WebSocket.OPEN) return;
|
||||||
this.socket.send(JSON.stringify({ action: 'announce', info_hash: this.infoHash, peer_id: this.peerId, ...data }));
|
try { this.socket.send(JSON.stringify({ action: 'announce', info_hash: this.infoHash, peer_id: this.peerId, ...data })); }
|
||||||
|
catch { this.fail(new Error('Could not send to the tracker.')); }
|
||||||
}
|
}
|
||||||
private fail(error: Error) {
|
private fail(error: Error) {
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
|
this.rejectConnect?.(error);
|
||||||
|
this.rejectConnect = undefined;
|
||||||
this.close(); this.events.onError(error);
|
this.close(); this.events.onError(error);
|
||||||
}
|
}
|
||||||
private receive(raw: unknown) {
|
private receive(raw: unknown) {
|
||||||
@@ -164,6 +178,9 @@ export class ReconnectAttempt {
|
|||||||
this.signals++; this.working = true; this.lastSignal = Date.now();
|
this.signals++; this.working = true; this.lastSignal = Date.now();
|
||||||
try {
|
try {
|
||||||
const { initiator, key } = this.options, offerId = randomId();
|
const { initiator, key } = this.options, offerId = randomId();
|
||||||
|
// createOffer replaces the local peer immediately. Its previous answer
|
||||||
|
// must stop being eligible before gathering or encryption yields.
|
||||||
|
if (initiator) this.offerId = '';
|
||||||
const code = initiator ? await this.options.hooks.createOffer() : '';
|
const code = initiator ? await this.options.hooks.createOffer() : '';
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
const sdp = await sealSignal(key, this.route(initiator ? 'offer' : 'wake', offerId, this.tracker.peerId), code);
|
const sdp = await sealSignal(key, this.route(initiator ? 'offer' : 'wake', offerId, this.tracker.peerId), code);
|
||||||
@@ -181,14 +198,15 @@ export class ReconnectAttempt {
|
|||||||
}
|
}
|
||||||
private async receiveOffer({ peerId, offerId, sdp }: TrackerSignal) {
|
private async receiveOffer({ peerId, offerId, sdp }: TrackerSignal) {
|
||||||
const role = signalRole(sdp);
|
const role = signalRole(sdp);
|
||||||
if (this.closed || !this.fresh(offerId) || (role === 'wake') !== this.options.initiator || role === 'answer' || !role) return;
|
if (this.closed || this.seen.has(offerId) || (role === 'wake') !== this.options.initiator || role === 'answer' || !role) return;
|
||||||
let code: string;
|
let code: string;
|
||||||
try { code = await openSignal(this.options.key, this.route(role, offerId, peerId), sdp); }
|
try { code = await openSignal(this.options.key, this.route(role, offerId, peerId), sdp); }
|
||||||
catch { return; }
|
catch { return; }
|
||||||
if (this.closed) return;
|
// Only authenticated messages consume replay slots. Invalid tracker
|
||||||
|
// traffic must not suppress a valid offer or evict previously seen ones.
|
||||||
|
if (this.closed || this.working || !this.fresh(offerId)) return;
|
||||||
// A wake means the peer just arrived: offer now unless an offer is very recent.
|
// A wake means the peer just arrived: offer now unless an offer is very recent.
|
||||||
if (role === 'wake') { if (Date.now() - this.lastSignal > 3000) void this.signal(true); return; }
|
if (role === 'wake') { if (Date.now() - this.lastSignal > 3000) void this.signal(true); return; }
|
||||||
if (this.working) return;
|
|
||||||
this.working = true;
|
this.working = true;
|
||||||
try {
|
try {
|
||||||
const answer = await this.options.hooks.createAnswer(code);
|
const answer = await this.options.hooks.createAnswer(code);
|
||||||
|
|||||||
+27
-1
@@ -21,13 +21,14 @@ const tick = () => new Promise<void>(resolve => setImmediate(resolve));
|
|||||||
async function until(check: () => boolean) { for (let n = 0; n < 500; n++) { if (check()) return; await tick(); } assert.fail('Condition did not become true'); }
|
async function until(check: () => boolean) { for (let n = 0; n < 500; n++) { if (check()) return; await tick(); } assert.fail('Condition did not become true'); }
|
||||||
const file = (name: string, size = 3) => new File([new Uint8Array(size).fill(42)], name);
|
const file = (name: string, size = 3) => new File([new Uint8Array(size).fill(42)], name);
|
||||||
function side(channel: Channel, initiator: boolean) {
|
function side(channel: Channel, initiator: boolean) {
|
||||||
const state = { ready: false, queue: [] as QueueItem[], send: '' as TransferState | '', receive: '' as TransferState | '', results: [] as { direction: string; result: TransferResult }[], declined: [] as string[], errors: [] as string[], closed: false };
|
const state = { ready: false, queue: [] as QueueItem[], send: '' as TransferState | '', receive: '' as TransferState | '', results: [] as { direction: string; result: TransferResult }[], declined: [] as string[], errors: [] as string[], closed: false, pairings: [] as Record<string, unknown>[] };
|
||||||
const callbacks: SessionCallbacks = {
|
const callbacks: SessionCallbacks = {
|
||||||
onReady() { state.ready = true; }, onQueue(items) { state.queue = items; },
|
onReady() { state.ready = true; }, onQueue(items) { state.queue = items; },
|
||||||
onState(direction, value) { state[direction] = value; }, onProgress() {},
|
onState(direction, value) { state[direction] = value; }, onProgress() {},
|
||||||
onComplete(direction, result) { state.results.push({ direction, result }); },
|
onComplete(direction, result) { state.results.push({ direction, result }); },
|
||||||
onDecline(direction, meta) { state.declined.push(meta.name); state[direction] = ''; },
|
onDecline(direction, meta) { state.declined.push(meta.name); state[direction] = ''; },
|
||||||
onError(error) { state.errors.push(error.message); }, onClose() { state.closed = true; },
|
onError(error) { state.errors.push(error.message); }, onClose() { state.closed = true; },
|
||||||
|
onPairing(message) { state.pairings.push(message); },
|
||||||
};
|
};
|
||||||
return { session: new FileSession(channel, initiator, callbacks), state, channel };
|
return { session: new FileSession(channel, initiator, callbacks), state, channel };
|
||||||
}
|
}
|
||||||
@@ -144,3 +145,28 @@ test('invalid or missing identity proof closes the session without releasing fil
|
|||||||
assert.match(first.state.errors.join(''), /Device proof failed/);
|
assert.match(first.state.errors.join(''), /Device proof failed/);
|
||||||
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
|
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('pairing messages wait for mutual verification and device proofs', async t => {
|
||||||
|
const { first, second } = pair(t);
|
||||||
|
let release!: () => void;
|
||||||
|
const proof = new Promise<void>(resolve => { release = resolve; });
|
||||||
|
t.after(() => release());
|
||||||
|
for (const side of [first, second]) side.session.authenticate({ sign: async () => 'proof', verify: () => proof });
|
||||||
|
first.session.verify(); second.session.verify(); await tick();
|
||||||
|
assert.throws(() => first.session.sendPairing({ step: 'propose' }));
|
||||||
|
assert.deepEqual(second.state.pairings, []);
|
||||||
|
release(); await until(() => first.state.ready && second.state.ready);
|
||||||
|
first.session.sendPairing({ step: 'check', value: '' });
|
||||||
|
await until(() => second.state.pairings.length === 1);
|
||||||
|
assert.deepEqual(second.state.pairings, [{ v: 3, type: 'pairing', step: 'check', value: '' }]);
|
||||||
|
first.session.close();
|
||||||
|
assert.throws(() => first.session.sendPairing({ step: 'propose' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unsolicited pairing messages before verification never reach the setup handler', async t => {
|
||||||
|
const { first } = pair(t);
|
||||||
|
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'pairing', step: 'propose' }) }));
|
||||||
|
await until(() => first.state.closed);
|
||||||
|
assert.deepEqual(first.state.pairings, []);
|
||||||
|
assert.match(first.state.errors[0]!, /before verification/);
|
||||||
|
});
|
||||||
+135
-8
@@ -1,7 +1,7 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { ReconnectAttempt, TrackerClient, type AttemptHooks } from '../src/lib/tracker.ts';
|
import { ReconnectAttempt, TrackerClient, RETRY_INTERVAL, MAX_SIGNALS, type AttemptHooks } from '../src/lib/tracker.ts';
|
||||||
import { derivePairing, discoveryId, pairingNonce, signalingKey } from '../src/lib/reconnect.ts';
|
import { derivePairing, discoveryId, pairingNonce, sealSignal, signalingKey } from '../src/lib/reconnect.ts';
|
||||||
|
|
||||||
// An in-memory tracker with the routing of webtorrent/bittorrent-tracker:
|
// An in-memory tracker with the routing of webtorrent/bittorrent-tracker:
|
||||||
// counts include the announcing peer, offers go to other registered peers,
|
// counts include the announcing peer, offers go to other registered peers,
|
||||||
@@ -10,6 +10,8 @@ class FakeTracker {
|
|||||||
peers = new Map<string, FakeSocket>();
|
peers = new Map<string, FakeSocket>();
|
||||||
frames: Record<string, unknown>[] = [];
|
frames: Record<string, unknown>[] = [];
|
||||||
refuse = '';
|
refuse = '';
|
||||||
|
holdAnswers = false;
|
||||||
|
answers: (() => void)[] = [];
|
||||||
connect = (_url: string) => new FakeSocket(this) as unknown as WebSocket;
|
connect = (_url: string) => new FakeSocket(this) as unknown as WebSocket;
|
||||||
handle(socket: FakeSocket, data: Record<string, unknown>) {
|
handle(socket: FakeSocket, data: Record<string, unknown>) {
|
||||||
this.frames.push(data);
|
this.frames.push(data);
|
||||||
@@ -20,7 +22,10 @@ class FakeTracker {
|
|||||||
this.peers.set(peerId, socket);
|
this.peers.set(peerId, socket);
|
||||||
if (data.answer) {
|
if (data.answer) {
|
||||||
const target = this.peers.get(data.to_peer_id as string);
|
const target = this.peers.get(data.to_peer_id as string);
|
||||||
if (target) reply(target, { peer_id: peerId, offer_id: data.offer_id, answer: data.answer });
|
if (target) {
|
||||||
|
const deliver = () => reply(target, { peer_id: peerId, offer_id: data.offer_id, answer: data.answer });
|
||||||
|
if (this.holdAnswers) this.answers.push(deliver); else deliver();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
reply(socket, { interval: 120, complete: 0, incomplete: this.peers.size });
|
reply(socket, { interval: 120, complete: 0, incomplete: this.peers.size });
|
||||||
@@ -37,7 +42,7 @@ class FakeSocket {
|
|||||||
onclose: (() => void) | null = null;
|
onclose: (() => void) | null = null;
|
||||||
onmessage: ((event: { data: string }) => void) | null = null;
|
onmessage: ((event: { data: string }) => void) | null = null;
|
||||||
tracker: FakeTracker;
|
tracker: FakeTracker;
|
||||||
constructor(tracker: FakeTracker) { this.tracker = tracker; setTimeout(() => { this.readyState = 1; this.onopen?.(); }); }
|
constructor(tracker: FakeTracker) { this.tracker = tracker; setTimeout(() => { if (this.readyState !== 0) return; this.readyState = 1; this.onopen?.(); }); }
|
||||||
send(text: string) { const data = JSON.parse(text); setTimeout(() => this.tracker.handle(this, data)); }
|
send(text: string) { const data = JSON.parse(text); setTimeout(() => this.tracker.handle(this, data)); }
|
||||||
deliver(message: object) { setTimeout(() => { if (this.readyState === 1) this.onmessage?.({ data: JSON.stringify(message) }); }); }
|
deliver(message: object) { setTimeout(() => { if (this.readyState === 1) this.onmessage?.({ data: JSON.stringify(message) }); }); }
|
||||||
close() { this.readyState = 3; }
|
close() { this.readyState = 3; }
|
||||||
@@ -50,7 +55,7 @@ async function pairing() {
|
|||||||
});
|
});
|
||||||
return { infoHash: await discoveryId(key), key: await signalingKey(key) };
|
return { infoHash: await discoveryId(key), key: await signalingKey(key) };
|
||||||
}
|
}
|
||||||
function peer(tracker: FakeTracker, shared: { infoHash: string; key: CryptoKey }, initiator: boolean) {
|
function peer(tracker: FakeTracker, shared: { infoHash: string; key: CryptoKey }, initiator: boolean, overrides: Partial<AttemptHooks> = {}) {
|
||||||
const log = { offers: 0, answered: [] as string[], accepted: [] as string[], errors: [] as string[] };
|
const log = { offers: 0, answered: [] as string[], accepted: [] as string[], errors: [] as string[] };
|
||||||
let done: () => void;
|
let done: () => void;
|
||||||
const finished = new Promise<void>(resolve => { done = resolve; });
|
const finished = new Promise<void>(resolve => { done = resolve; });
|
||||||
@@ -60,16 +65,22 @@ function peer(tracker: FakeTracker, shared: { infoHash: string; key: CryptoKey }
|
|||||||
acceptAnswer: async answer => { log.accepted.push(answer); done(); },
|
acceptAnswer: async answer => { log.accepted.push(answer); done(); },
|
||||||
onPeers: () => {},
|
onPeers: () => {},
|
||||||
onError: error => { log.errors.push(error.message); done(); },
|
onError: error => { log.errors.push(error.message); done(); },
|
||||||
|
...overrides,
|
||||||
};
|
};
|
||||||
const attempt = new ReconnectAttempt({ url: 'wss://tracker.test/', ...shared, initiator, hooks, connectSocket: tracker.connect });
|
const attempt = new ReconnectAttempt({ url: 'wss://tracker.test/', ...shared, initiator, hooks, connectSocket: tracker.connect });
|
||||||
return { attempt, log, finished };
|
return { attempt, log, finished };
|
||||||
}
|
}
|
||||||
const settle = () => new Promise(resolve => setTimeout(resolve, 20));
|
const settle = () => new Promise(resolve => setTimeout(resolve, 20));
|
||||||
|
async function until(check: () => boolean) {
|
||||||
|
for (let n = 0; n < 100; n++) { if (check()) return; await settle(); }
|
||||||
|
assert.fail('Expected tracker activity did not arrive');
|
||||||
|
}
|
||||||
|
|
||||||
for (const initiatorFirst of [true, false]) {
|
for (const initiatorFirst of [true, false]) {
|
||||||
test(`peers connect when the ${initiatorFirst ? 'initiator' : 'responder'} arrives first`, async () => {
|
test(`peers connect when the ${initiatorFirst ? 'initiator' : 'responder'} arrives first`, { timeout: 5000 }, async t => {
|
||||||
const tracker = new FakeTracker(), shared = await pairing();
|
const tracker = new FakeTracker(), shared = await pairing();
|
||||||
const initiator = peer(tracker, shared, true), responder = peer(tracker, shared, false);
|
const initiator = peer(tracker, shared, true), responder = peer(tracker, shared, false);
|
||||||
|
t.after(() => { initiator.attempt.close(); responder.attempt.close(); });
|
||||||
const [first, second] = initiatorFirst ? [initiator, responder] : [responder, initiator];
|
const [first, second] = initiatorFirst ? [initiator, responder] : [responder, initiator];
|
||||||
await first.attempt.start(); await settle();
|
await first.attempt.start(); await settle();
|
||||||
await second.attempt.start();
|
await second.attempt.start();
|
||||||
@@ -85,10 +96,11 @@ for (const initiatorFirst of [true, false]) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
test('a client with another key in the swarm is ignored', async () => {
|
test('a client with another key in the swarm is ignored', async t => {
|
||||||
const tracker = new FakeTracker(), shared = await pairing(), other = await pairing();
|
const tracker = new FakeTracker(), shared = await pairing(), other = await pairing();
|
||||||
const stranger = peer(tracker, { ...other, infoHash: shared.infoHash }, false);
|
const stranger = peer(tracker, { ...other, infoHash: shared.infoHash }, false);
|
||||||
const initiator = peer(tracker, shared, true);
|
const initiator = peer(tracker, shared, true);
|
||||||
|
t.after(() => { initiator.attempt.close(); stranger.attempt.close(); });
|
||||||
await stranger.attempt.start(); await settle();
|
await stranger.attempt.start(); await settle();
|
||||||
await initiator.attempt.start(); await settle(); await settle();
|
await initiator.attempt.start(); await settle(); await settle();
|
||||||
// The stranger's wake does not open, so it never prompts an offer by itself;
|
// The stranger's wake does not open, so it never prompts an offer by itself;
|
||||||
@@ -99,10 +111,11 @@ test('a client with another key in the swarm is ignored', async () => {
|
|||||||
initiator.attempt.close(); stranger.attempt.close();
|
initiator.attempt.close(); stranger.attempt.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('tracker refusals and invalid frames end the attempt', async () => {
|
test('tracker refusals and invalid frames end the attempt', { timeout: 5000 }, async t => {
|
||||||
const tracker = new FakeTracker(), shared = await pairing();
|
const tracker = new FakeTracker(), shared = await pairing();
|
||||||
tracker.refuse = 'swarm limit';
|
tracker.refuse = 'swarm limit';
|
||||||
const refused = peer(tracker, shared, true);
|
const refused = peer(tracker, shared, true);
|
||||||
|
t.after(() => refused.attempt.close());
|
||||||
await refused.attempt.start();
|
await refused.attempt.start();
|
||||||
await refused.finished;
|
await refused.finished;
|
||||||
assert.match(refused.log.errors[0]!, /refused the request: swarm limit/);
|
assert.match(refused.log.errors[0]!, /refused the request: swarm limit/);
|
||||||
@@ -111,8 +124,122 @@ test('tracker refusals and invalid frames end the attempt', async () => {
|
|||||||
let socket: FakeSocket | undefined;
|
let socket: FakeSocket | undefined;
|
||||||
const client = new TrackerClient('wss://tracker.test/', shared.infoHash, { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: error => errors.push(error.message) },
|
const client = new TrackerClient('wss://tracker.test/', shared.infoHash, { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: error => errors.push(error.message) },
|
||||||
() => (socket = new FakeSocket(new FakeTracker())) as unknown as WebSocket);
|
() => (socket = new FakeSocket(new FakeTracker())) as unknown as WebSocket);
|
||||||
|
t.after(() => client.close());
|
||||||
await client.connect();
|
await client.connect();
|
||||||
socket!.onmessage?.({ data: 'not json' });
|
socket!.onmessage?.({ data: 'not json' });
|
||||||
assert.deepEqual(errors, ['The tracker sent an invalid message.']);
|
assert.deepEqual(errors, ['The tracker sent an invalid message.']);
|
||||||
assert.throws(() => new TrackerClient('wss://tracker.test/', 'short', { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: () => {} }));
|
assert.throws(() => new TrackerClient('wss://tracker.test/', 'short', { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: () => {} }));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('cancelling a connecting socket settles immediately and clears its timeout', async t => {
|
||||||
|
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||||
|
const socket = new FakeSocket(new FakeTracker());
|
||||||
|
const errors: string[] = [];
|
||||||
|
const client = new TrackerClient('wss://tracker.test/', 'h'.repeat(20), {
|
||||||
|
onPeers() {}, onOffer() {}, onAnswer() {}, onError: error => errors.push(error.message),
|
||||||
|
}, () => socket as unknown as WebSocket);
|
||||||
|
const outcome = client.connect().then(() => 'opened', error => error.message);
|
||||||
|
let settled = false;
|
||||||
|
void outcome.then(() => { settled = true; });
|
||||||
|
client.close();
|
||||||
|
await Promise.resolve(); await Promise.resolve();
|
||||||
|
assert.equal(settled, true, 'Cancel must settle the pending connect without waiting 15 seconds');
|
||||||
|
assert.match(await outcome, /cancelled/i);
|
||||||
|
t.mock.timers.tick(30000);
|
||||||
|
assert.equal(socket.readyState, 3);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
await assert.rejects(client.connect(), /closed/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const failure of ['timeout', 'close', 'send'] as const) {
|
||||||
|
test(`tracker ${failure} failure rejects the handshake and reports one error`, async t => {
|
||||||
|
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||||
|
const socket = new FakeSocket(new FakeTracker()), errors: string[] = [];
|
||||||
|
const client = new TrackerClient('wss://tracker.test/', 'h'.repeat(20), {
|
||||||
|
onPeers() {}, onOffer() {}, onAnswer() {}, onError: error => errors.push(error.message),
|
||||||
|
}, () => socket as unknown as WebSocket);
|
||||||
|
t.after(() => client.close());
|
||||||
|
const connecting = client.connect();
|
||||||
|
const expected = failure === 'timeout' ? /did not respond/ : failure === 'close' ? /closed the connection/ : /Could not send/;
|
||||||
|
const rejected = assert.rejects(connecting, expected);
|
||||||
|
if (failure === 'timeout') {
|
||||||
|
// Keep the fake handshake pending rather than letting its open timer fire.
|
||||||
|
socket.readyState = 2;
|
||||||
|
t.mock.timers.tick(15000);
|
||||||
|
} else if (failure === 'close') socket.onclose?.();
|
||||||
|
else {
|
||||||
|
socket.send = () => { throw new Error('Socket send failed'); };
|
||||||
|
t.mock.timers.tick(0);
|
||||||
|
}
|
||||||
|
await rejected;
|
||||||
|
t.mock.timers.tick(30000);
|
||||||
|
assert.equal(errors.length, 1);
|
||||||
|
assert.match(errors[0]!, expected);
|
||||||
|
assert.equal(socket.readyState, 3);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a late answer cannot be applied while a replacement offer is gathering', { timeout: 5000 }, async t => {
|
||||||
|
t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
|
||||||
|
const tracker = new FakeTracker(), shared = await pairing();
|
||||||
|
tracker.holdAnswers = true;
|
||||||
|
let offers = 0, release!: () => void;
|
||||||
|
const gathering = new Promise<void>(resolve => { release = resolve; });
|
||||||
|
const initiator = peer(tracker, shared, true, { createOffer: async () => {
|
||||||
|
offers++;
|
||||||
|
if (offers === 2) await gathering;
|
||||||
|
return `HC1.offer-${offers}`;
|
||||||
|
} });
|
||||||
|
const responder = peer(tracker, shared, false);
|
||||||
|
t.after(() => { release(); initiator.attempt.close(); responder.attempt.close(); });
|
||||||
|
await responder.attempt.start(); await settle(); await initiator.attempt.start();
|
||||||
|
await until(() => tracker.answers.length === 1);
|
||||||
|
const offer = tracker.frames.find(frame => (frame.offers as unknown[])?.length)!;
|
||||||
|
const socket = tracker.peers.get(offer.peer_id as string)!;
|
||||||
|
t.mock.timers.tick(RETRY_INTERVAL);
|
||||||
|
socket.deliver({ action: 'announce', info_hash: shared.infoHash, complete: 0, incomplete: 2 });
|
||||||
|
await until(() => offers === 2);
|
||||||
|
tracker.answers.shift()!(); await settle();
|
||||||
|
assert.deepEqual(initiator.log.accepted, [], 'The old peer connection has already been disposed');
|
||||||
|
tracker.holdAnswers = false; release();
|
||||||
|
await until(() => initiator.log.accepted.length === 1);
|
||||||
|
assert.deepEqual(initiator.log.accepted, ['HC1.answer-to-HC1.offer-2']);
|
||||||
|
assert.deepEqual(initiator.log.errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unauthenticated frames cannot poison or evict the offer replay cache', async t => {
|
||||||
|
const tracker = new FakeTracker(), shared = await pairing();
|
||||||
|
const responder = peer(tracker, shared, false);
|
||||||
|
t.after(() => responder.attempt.close());
|
||||||
|
await responder.attempt.start(); await until(() => tracker.peers.size === 1);
|
||||||
|
const socket = [...tracker.peers.values()][0]!;
|
||||||
|
const route = { role: 'offer' as const, infoHash: shared.infoHash, offerId: 'o'.repeat(20), from: 'p'.repeat(20), to: '' };
|
||||||
|
const sdp = await sealSignal(shared.key, route, 'HC1.valid');
|
||||||
|
const deliver = (id: string, text: string) => socket.deliver({ action: 'announce', info_hash: shared.infoHash, peer_id: route.from, offer_id: id, offer: { type: 'offer', sdp: text } });
|
||||||
|
deliver(route.offerId, 'HCR1.o.invalid'); await settle();
|
||||||
|
deliver(route.offerId, sdp);
|
||||||
|
await until(() => responder.log.answered.length === 1);
|
||||||
|
for (let n = 0; n < 70; n++) deliver(String(n).padStart(20, 'x'), 'HCR1.o.invalid');
|
||||||
|
await settle(); deliver(route.offerId, sdp); await settle();
|
||||||
|
assert.deepEqual(responder.log.answered, ['HC1.valid']);
|
||||||
|
assert.deepEqual(responder.log.errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unanswered offers stop at the retry limit and closing stops further work', async t => {
|
||||||
|
t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
|
||||||
|
const tracker = new FakeTracker(), shared = await pairing();
|
||||||
|
const initiator = peer(tracker, shared, true);
|
||||||
|
t.after(() => initiator.attempt.close());
|
||||||
|
await initiator.attempt.start(); await until(() => tracker.peers.size === 1);
|
||||||
|
const socket = [...tracker.peers.values()][0]!;
|
||||||
|
const count = () => socket.deliver({ action: 'announce', info_hash: shared.infoHash, complete: 0, incomplete: 2 });
|
||||||
|
for (let n = 1; n <= MAX_SIGNALS; n++) {
|
||||||
|
count(); await until(() => tracker.frames.filter(frame => (frame.offers as unknown[])?.length).length === n);
|
||||||
|
t.mock.timers.tick(RETRY_INTERVAL);
|
||||||
|
}
|
||||||
|
count(); await until(() => initiator.log.errors.length === 1);
|
||||||
|
assert.match(initiator.log.errors[0]!, /did not respond/);
|
||||||
|
count(); await settle();
|
||||||
|
assert.equal(initiator.log.offers, MAX_SIGNALS);
|
||||||
|
assert.equal(socket.readyState, 3);
|
||||||
|
});
|
||||||
+1
-1
@@ -10,7 +10,7 @@ RUN npm ci --omit=dev --omit=optional --ignore-scripts --no-audit --no-fund \
|
|||||||
FROM dependencies AS test
|
FROM dependencies AS test
|
||||||
COPY server.mjs healthcheck.mjs test.mjs ./
|
COPY server.mjs healthcheck.mjs test.mjs ./
|
||||||
USER node
|
USER node
|
||||||
RUN node --test test.mjs
|
CMD ["node", "--test", "test.mjs"]
|
||||||
|
|
||||||
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS runtime
|
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS runtime
|
||||||
ENV NODE_ENV=production PORT=8000 DEBUG=""
|
ENV NODE_ENV=production PORT=8000 DEBUG=""
|
||||||
|
|||||||
+3
-2
@@ -26,8 +26,9 @@ its health check; it does not start coturn or require `.env.development`. Vite
|
|||||||
continues to run on the host. No service is enabled at boot and the development
|
continues to run on the host. No service is enabled at boot and the development
|
||||||
container has no automatic restart policy.
|
container has no automatic restart policy.
|
||||||
|
|
||||||
`test:tracker` builds the Dockerfile's test target and runs native Node WebSocket
|
`test:tracker` builds the Dockerfile's test target, then runs it in a fresh
|
||||||
clients against the actual tracker server. It tests both arrival orders, counts
|
container so Docker's build cache cannot skip the tests. Native Node WebSocket
|
||||||
|
clients exercise the actual tracker server. Coverage includes both arrival orders, counts
|
||||||
in announce replies, a 64 KiB code after AES-GCM/base64 encoding, answer routing,
|
in announce replies, a 64 KiB code after AES-GCM/base64 encoding, answer routing,
|
||||||
disconnect cleanup, graceful termination, disabled HTTP and WebSocket scrape,
|
disconnect cleanup, graceful termination, disabled HTTP and WebSocket scrape,
|
||||||
malformed/oversized messages, swarm/rate limits, per-socket swarm and peer ID
|
malformed/oversized messages, swarm/rate limits, per-socket swarm and peer ID
|
||||||
|
|||||||
Reference in new issue
Block a user