Files
HellCon/tests/reconnect.test.ts
T
SchluffeandClaude Opus 5.5 acba97a7e1 Confirm reconnect pairings and add connection discovery settings
Setup now waits for both IndexedDB writes: the acceptor acknowledges its
write, a failure on either side is reported to both people, and the
proposer removes its copy if the acceptor could not save. Every session
that authenticates the paired device compares a check value derived from
the stored pairing, so a one-sided pairing (interrupted setup, or Turn off
reconnect on one device) is turned off on the other side too.

The tracker is chosen under Network settings > Connection discovery
(manual, default from VITE_TRACKER_URL, or custom), stored per browser and
editable during a session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:30:04 +02:00

120 lines
7.4 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { derivePairing, discoveryId, discoveryTracker, loadDiscovery, openSignal, pairingCheck, parseCheck, parsePairing, pairingNonce, saveDiscovery, sealSignal, signalingKey, signalRole, trackerUrl, CLOCK_TOLERANCE, SIGNAL_LIFETIME, type PairingContext, type SignalRoute } from '../src/lib/reconnect.ts';
import { emptyConnection, updateConnection } from '../src/lib/connections.ts';
const fingerprint = (byte: string) => Array(32).fill(byte).join(' ');
const id = (char: string) => char.repeat(20);
const context: PairingContext = {
proposerNonce: pairingNonce(), acceptorNonce: pairingNonce(),
proposerKey: '04' + 'a'.repeat(128), acceptorKey: '04' + 'b'.repeat(128),
offerFingerprint: fingerprint('AA'), answerFingerprint: fingerprint('BB'),
tracker: 'wss://tracker.example/announce',
};
const route: SignalRoute = { role: 'offer', infoHash: id('h'), offerId: id('o'), from: id('f'), to: '' };
test('both peers derive the same pairing; every input separates it', async () => {
const [first, second] = await Promise.all([derivePairing(context), derivePairing({ ...context })]);
assert.equal(first.extractable, false);
assert.equal(await discoveryId(first, 100), await discoveryId(second, 100));
const sealed = await sealSignal(await signalingKey(first), route, 'HC1.code');
assert.equal(await openSignal(await signalingKey(second), route, sealed), 'HC1.code');
for (const changed of [
{ proposerNonce: pairingNonce() }, { acceptorNonce: pairingNonce() },
{ proposerKey: context.acceptorKey, acceptorKey: context.proposerKey },
{ offerFingerprint: fingerprint('CC') }, { answerFingerprint: fingerprint('CC') },
{ tracker: 'wss://other.example/announce' },
]) {
const other = await derivePairing({ ...context, ...changed });
assert.notEqual(await discoveryId(other, 100), await discoveryId(first, 100));
await assert.rejects(openSignal(await signalingKey(other), route, sealed));
}
await assert.rejects(derivePairing({ ...context, acceptorKey: context.proposerKey }), /two different devices/);
await assert.rejects(derivePairing({ ...context, proposerNonce: 'short' }));
});
test('discovery identifiers are 20 binary bytes and change daily', async () => {
const key = await derivePairing(context);
const today = await discoveryId(key, 20000);
assert.equal(today.length, 20);
assert.ok([...today].every(char => char.charCodeAt(0) < 256));
assert.notEqual(await discoveryId(key, 20001), today);
});
test('envelopes bind role and every routing field, and expire', async () => {
const key = await signalingKey(await derivePairing(context));
const now = 1_000_000_000_000;
const sealed = await sealSignal(key, route, 'HC1.code', now);
assert.equal(signalRole(sealed), 'offer');
assert.equal(await openSignal(key, route, sealed, now), 'HC1.code');
for (const changed of [{ infoHash: id('x') }, { offerId: id('x') }, { from: id('x') }, { to: id('x') }]) {
await assert.rejects(openSignal(key, { ...route, ...changed }, sealed, now));
}
await assert.rejects(openSignal(key, { ...route, role: 'answer' }, sealed, now));
const tampered = sealed.slice(0, -2) + (sealed.endsWith('A') ? 'B' : 'A') + sealed.slice(-1);
await assert.rejects(openSignal(key, route, tampered, now));
await assert.rejects(openSignal(key, route, sealed, now + SIGNAL_LIFETIME + CLOCK_TOLERANCE + 1), /expired/);
await assert.rejects(openSignal(key, route, 'x'.repeat(200_000), now));
const wake = await sealSignal(key, { ...route, role: 'wake' }, '', now);
assert.equal(await openSignal(key, { ...route, role: 'wake' }, wake, now), '');
// A wake never carries a code, and offers always do.
await assert.rejects(openSignal(key, route, await sealSignal(key, route, '', now), now));
});
test('tracker addresses must be secure WebSocket URLs', () => {
assert.equal(trackerUrl(' wss://tracker.example '), 'wss://tracker.example/');
assert.equal(trackerUrl('ws://localhost:8000'), 'ws://localhost:8000/');
for (const bad of ['https://tracker.example', 'ws://tracker.example', 'wss://user:pass@tracker.example', 'wss://tracker.example/#x', 'nonsense', 42]) {
assert.throws(() => trackerUrl(bad));
}
});
test('stored pairings are dropped when the paired device changes', async () => {
const peerKey = context.acceptorKey;
const pairing = { version: 1 as const, trackers: ['wss://tracker.example/'], key: await derivePairing(context), localKey: context.proposerKey, peerKey };
const paired = updateConnection(emptyConnection(), { peerKey });
const reconnecting = updateConnection(paired, { reconnect: pairing });
assert.equal(reconnecting.reconnect?.trackers[0], 'wss://tracker.example/');
assert.equal(updateConnection(reconnecting, { name: 'Laptop' }).reconnect, reconnecting.reconnect);
assert.equal(updateConnection(reconnecting, { peerKey }).reconnect, reconnecting.reconnect);
assert.equal(updateConnection(reconnecting, { peerKey: '' }).reconnect, null);
assert.equal(updateConnection(reconnecting, { peerKey: context.proposerKey }).reconnect, null);
assert.equal(updateConnection(reconnecting, { reconnect: null }).reconnect, null);
assert.throws(() => updateConnection(emptyConnection(), { reconnect: pairing }));
assert.equal(parsePairing(structuredClone(pairing), peerKey)?.key.algorithm.name, 'HKDF');
assert.equal(parsePairing({ ...pairing, trackers: ['http://x'] }, peerKey), null);
assert.equal(parsePairing({ ...pairing, key: 'secret' }, peerKey), null);
});
test('pairing checks match only for the same pairing', async () => {
const [first, second] = await Promise.all([derivePairing(context), derivePairing({ ...context })]);
const check = await pairingCheck(first);
assert.match(check, /^[0-9a-f]{32}$/);
assert.equal(await pairingCheck(second), check);
assert.notEqual(await pairingCheck(await derivePairing({ ...context, acceptorNonce: pairingNonce() })), check);
assert.equal(parseCheck(check), check);
assert.equal(parseCheck(''), '');
for (const bad of ['zz'.repeat(16), 'ab', 42, null]) assert.throws(() => parseCheck(bad));
});
test('discovery preferences resolve to one concrete tracker', () => {
const values = new Map<string, string>();
const storage = { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
Object.defineProperty(globalThis, 'localStorage', { value: storage, configurable: true });
try {
assert.deepEqual(loadDiscovery(''), { choice: 'manual', custom: '' });
assert.deepEqual(loadDiscovery('wss://default.example'), { choice: 'default', custom: '' });
saveDiscovery({ choice: 'custom', custom: 'wss://mine.example/announce' });
const custom = loadDiscovery('wss://default.example');
assert.equal(discoveryTracker(custom, 'wss://default.example'), 'wss://mine.example/announce');
// A fork without a default tracker never resolves a stored Default choice.
saveDiscovery({ choice: 'default', custom: '' });
assert.equal(loadDiscovery('').choice, 'manual');
assert.equal(discoveryTracker(loadDiscovery('wss://default.example'), 'wss://default.example'), 'wss://default.example/');
assert.equal(discoveryTracker({ choice: 'manual', custom: 'wss://ignored.example' }, ''), '');
assert.throws(() => discoveryTracker({ choice: 'custom', custom: 'http://insecure.example' }, ''));
values.set('hellcon-discovery', '{broken');
assert.equal(loadDiscovery('').choice, 'manual');
} finally { Reflect.deleteProperty(globalThis, 'localStorage'); }
});