Add experimental tracker reconnect for paired devices
During a session authenticated by both device identities, one person proposes a WebTorrent tracker and the other confirms it. Both contribute a nonce over the data channel; HKDF binds both device keys, the session fingerprints and the tracker URL into a non-extractable base key stored with the connection. Forget device, a replaced paired device and Turn off reconnect clear it. Reconnect joins a daily swarm derived from that key. Offers, answers and codeless wakes travel as AES-GCM envelopes bound to the tracker routing fields. The lower device key offers; the other device wakes it when it arrives second. Retries are spaced and capped, one attempt per slot runs under a Web Lock, and fresh device proofs still authenticate the session. Checked against tracker.openwebtorrent.com and tracker.webtorrent.dev with the new opt-in browser check (--tracker=<url>). Signaling v5, midnight rollover, clock skew, CSP and real-network checks remain open. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a5935a8324
commit
3659956967
17 files changed
+930
-28
No files matched your search
@@ -4,3 +4,5 @@ TURN_HOST=127.0.0.1
|
||||
TURN_PORT=3478
|
||||
VITE_ICE_ENDPOINT=/api/ice-servers
|
||||
VITE_STUN_URL=stun:127.0.0.1:3478
|
||||
# Optional: prefills the tracker for reconnect setup, e.g. the local container.
|
||||
# VITE_TRACKER_URL=ws://localhost:8000
|
||||
@@ -21,6 +21,11 @@
|
||||
- **Disconnect**, which aborts unfinished writes, and Send/Receive navigation
|
||||
within a live session. The initial receiver can send files without
|
||||
reconnecting.
|
||||
- Experimental tracker reconnect for paired devices. During a verified session,
|
||||
one person proposes a WebTorrent tracker and the other confirms it; later,
|
||||
both press **Reconnect** instead of exchanging codes. The tracker only relays
|
||||
encrypted offers and answers; device proofs still authenticate the session.
|
||||
See the [concept status](docs/webtorrent-reconnect.md#concept-status).
|
||||
- The hosted-first, serverless [UX roadmap](docs/ux-roadmap.md).
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -217,7 +217,9 @@ img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none';
|
||||
frame-ancestors 'none'
|
||||
```
|
||||
|
||||
Inline styles are used for progress and Vue visibility. Custom policies must
|
||||
Inline styles are used for progress and Vue visibility. The experimental
|
||||
tracker reconnect also needs the tracker in `connect-src`, for example
|
||||
`connect-src 'self' wss://tracker.example`. Custom policies must
|
||||
permit same-origin workers and frames. Test headers on the actual host; CSP is
|
||||
defense in depth, not a substitute for trusting the host or a WebRTC egress
|
||||
filter. `robots.txt` and indexing metadata are crawler requests, not access
|
||||
@@ -245,6 +247,7 @@ bun run test # unit tests
|
||||
bun run build
|
||||
bun run test:browser # Chromium integration and axe checks against dist/
|
||||
bun run test:browser --connections # sidebar, persistence, live switching, mobile layout
|
||||
bun run test:browser --tracker=wss://tracker.example # experimental tracker reconnect
|
||||
bun run test:download # real hosted downloads up to 120 MiB, no native picker
|
||||
bun run test:cross-browser # Brave sender → Firefox receiver
|
||||
bun audit
|
||||
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
# Serverless UX roadmap
|
||||
|
||||
The app runs over HTTPS or on localhost. The current build uses manual signaling.
|
||||
The next planned addition is [WebTorrent tracker reconnect](webtorrent-reconnect.md):
|
||||
The next addition is [WebTorrent tracker reconnect](webtorrent-reconnect.md):
|
||||
a configurable default or custom tracker exchanges encrypted connection codes for
|
||||
paired devices, without a Trystero dependency. This replaces the custom rendezvous
|
||||
proposal and the earlier blanket exclusion of a signaling backend. Peer presence,
|
||||
offline wake-up and silent TURN fallback remain outside scope. The reconnect
|
||||
feature is planned, not implemented; the sections below describe current behavior.
|
||||
offline wake-up and silent TURN fallback remain outside scope. An experimental
|
||||
concept of reconnect works; the sections below describe the rest of the app.
|
||||
|
||||
## Connection workspace — implemented
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# WebTorrent tracker reconnect (planned, not implemented)
|
||||
# WebTorrent tracker reconnect (experimental concept)
|
||||
|
||||
This replaces the custom rendezvous server proposal. HellCon will exchange fresh
|
||||
connection codes through a configurable WebTorrent-compatible WebSocket tracker,
|
||||
@@ -8,7 +8,8 @@ client to HellCon. Nostr is outside this plan.
|
||||
|
||||
The [repository-owned tracker container](../tracker/README.md) now provides the
|
||||
development/deployment foundation, using an official Node base and a locked
|
||||
upstream package. Browser pairing, settings and automatic reconnect remain planned.
|
||||
upstream package. A first browser implementation exists to prove the concept;
|
||||
see [Concept status](#concept-status) for what it covers and what is still open.
|
||||
|
||||
Client independence takes priority: anyone can clone, fork, self-host or modify
|
||||
HellCon and choose their own tracker. The client must work with any compatible
|
||||
@@ -269,6 +270,60 @@ behavior, and the small HellCon adapter. Keep a reproducible local tracker fixtu
|
||||
so upgrades can run the same interoperability and reconnect checks. Supporting
|
||||
additional discovery protocols would add independent maintenance and test paths.
|
||||
|
||||
## Concept status
|
||||
|
||||
Implemented in `src/lib/reconnect.ts` (pairing derivation, discovery identifier,
|
||||
sealed envelopes), `src/lib/tracker.ts` (WebSocket adapter and attempt logic) and
|
||||
`TransferPanel.vue`:
|
||||
|
||||
- Setup runs over a verified session whose peer proved the paired device key.
|
||||
Either person proposes a tracker URL; the peer sees the host and accepts or
|
||||
declines. Both contribute 32 random bytes; the HKDF context binds both device
|
||||
keys, both fingerprints of that session and the tracker URL. The proposer
|
||||
stores first, then the acceptor. The base key is a non-extractable CryptoKey
|
||||
in the connection record, which Forget device, a replaced paired device and
|
||||
**Turn off reconnect** clear. A changed local identity blocks the attempt.
|
||||
- The discovery identifier is derived per UTC day; envelopes are AES-256-GCM with
|
||||
a random IV, the role, info_hash, offer ID, source and destination peer IDs
|
||||
as associated data, and a two-minute lifetime with five minutes' tolerance.
|
||||
The decrypted code passes the usual `decodeCode` checks, and the peer's
|
||||
identity key must equal the paired key; fresh device proofs then authenticate
|
||||
the session as before.
|
||||
- Roles differ from the plan above: the lower device key always offers and
|
||||
creates the data channel, so there is no glare. If the other device arrives
|
||||
second, it announces a sealed, codeless **wake** that makes the initiator
|
||||
offer at once. Swarm counts from announce responses (which include the
|
||||
announcing peer) trigger the same. Offers and wakes are spaced 15 seconds apart
|
||||
and capped at 12; each offer uses a fresh peer connection. Envelopes that do
|
||||
not open are ignored, so other clients in a swarm cannot disturb it beyond
|
||||
receiving offers they cannot read.
|
||||
- One attempt per slot and browser profile via Web Locks, a five-minute
|
||||
deadline, a 15-second keepalive announce, `stopped` and socket close on
|
||||
success, cancel, reset, failure and unmount.
|
||||
|
||||
Checked on 2026-10-20 with `node scripts/browser-check.ts --tracker=<url>` against
|
||||
`wss://tracker.openwebtorrent.com` and `wss://tracker.webtorrent.dev`: pairing
|
||||
setup, reload of both pages, Reconnect without codes, device proofs and exact
|
||||
bytes in both directions, both roles. Both trackers report swarm counts, route
|
||||
binary 20-byte identifiers unchanged and remove peers on `stopped`.
|
||||
tracker.openwebtorrent.com relayed 56 KB payloads, tracker.webtorrent.dev 12 KB;
|
||||
typical sealed codes are a few KB. Neither tracker is bundled.
|
||||
|
||||
Still open before this can ship:
|
||||
|
||||
- Signaling v5: pairing messages ride the v3 session protocol, so an older
|
||||
peer rejects them as unexpected, and the device proof does not bind the
|
||||
reconnect version.
|
||||
- Joining adjacent day identifiers around UTC midnight, clock-skew detection,
|
||||
and a frozen envelope encoding with published test vectors.
|
||||
- The **Connection discovery** settings section: the tracker URL is entered in
|
||||
the setup section (prefilled from `VITE_TRACKER_URL`), and changing it means
|
||||
setting up again over a live session.
|
||||
- Storage acknowledgement: each side stores without confirming the write to
|
||||
the other, so a storage failure can leave one side configured.
|
||||
- `connect-src` for the hosted CSP, Firefox and real separate-device networks,
|
||||
tracker outage and cross-tab behavior (step 5), and the deployment checks.
|
||||
|
||||
## References
|
||||
|
||||
- [WebTorrent tracker server and client](https://github.com/webtorrent/bittorrent-tracker)
|
||||
|
||||
@@ -17,6 +17,8 @@ const turn = process.argv.includes('--turn');
|
||||
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp';
|
||||
const streaming = process.argv.includes('--stream-download');
|
||||
const connections = process.argv.includes('--connections');
|
||||
// Opt-in: tracker reconnect against a real WebSocket tracker, e.g. --tracker=wss://tracker.example
|
||||
const trackerUrl = process.argv.find(arg => arg.startsWith('--tracker='))?.slice('--tracker='.length) ?? '';
|
||||
const screenshotDirectory = process.env.BROWSER_SCREENSHOT_DIR || (process.argv.includes('--screenshots') ? join(tmpdir(), 'hellcon-layout') : '');
|
||||
const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null;
|
||||
const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
|
||||
@@ -598,6 +600,49 @@ try {
|
||||
assert.deepEqual(rememberedBytes, { length: 4096, valid: true });
|
||||
console.log('PASS: identities and paired connections persist across reload; fresh mutual proofs authenticate the paired device and transfer exact bytes without manual reconfirmation.');
|
||||
|
||||
if (trackerUrl) {
|
||||
const both = [identitySender, identityReceiver];
|
||||
await input(identitySender, '#tracker-url', trackerUrl);
|
||||
await click(identitySender, 'Set up reconnect');
|
||||
await wait(identityReceiver, () => document.body.textContent?.includes('proposes reconnecting through'));
|
||||
await checkAccessibility(identityReceiver, 'reconnect proposal');
|
||||
if (screenshotDirectory) await evaluate(identityReceiver, () => window.__hellcon.element('.reconnect-setup').scrollIntoView({ block: 'center' }));
|
||||
await screenshot(identityReceiver, 'reconnect-proposal');
|
||||
await click(identityReceiver, 'Accept');
|
||||
for (const session of both) await wait(session, () => document.body.textContent?.includes('Reconnect is set up'));
|
||||
if (screenshotDirectory) await evaluate(identitySender, () => window.__hellcon.element('.reconnect-setup').scrollIntoView({ block: 'center' }));
|
||||
await screenshot(identitySender, 'reconnect-set-up');
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||||
for (const [session, url] of [[identitySender, origin], [identityReceiver, receiverOrigin]]) {
|
||||
await call('Page.navigate', { url }, session);
|
||||
await wait(session, () => !!document.querySelector('#stun-provider'));
|
||||
}
|
||||
await click(identityReceiver, 'Receive');
|
||||
for (const session of both) {
|
||||
await input(session, '#stun-provider', 'none');
|
||||
await wait(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reconnect' && !button.disabled));
|
||||
}
|
||||
await click(identitySender, 'Reconnect');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('Waiting for your peer on'));
|
||||
await checkAccessibility(identitySender, 'reconnect waiting');
|
||||
if (screenshotDirectory) await evaluate(identitySender, () => [...document.querySelectorAll('button')].find(button => button.textContent === 'Reconnect')?.scrollIntoView({ block: 'start' }));
|
||||
await screenshot(identitySender, 'reconnect-waiting');
|
||||
await click(identityReceiver, 'Reconnect');
|
||||
for (const session of both) await wait(session, () => document.body.textContent?.includes('Paired device authenticated'));
|
||||
assert.equal(await evaluate(identitySender, () => !!document.querySelector('#output-code')), false, 'No code is shown on reconnect');
|
||||
for (const [from, to, size] of [[identitySender, identityReceiver, 5000], [identityReceiver, identitySender, 6000]] as const) {
|
||||
await evaluate(from, (size: number) => window.__hellcon.chooseFile(size, 'reconnected.bin'), size);
|
||||
await wait(to, () => !!document.querySelector('.incoming button.primary'));
|
||||
await click(to, 'Accept file');
|
||||
await wait(to, () => !!document.querySelector('a.download'));
|
||||
await wait(from, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
const bytes = await evaluate(to, async () => { const link = window.__hellcon.element<HTMLAnchorElement>('a.download'); const data = new Uint8Array(await (await fetch(link.href)).arrayBuffer()); return { length: data.length, valid: data.every(byte => byte === 123) }; });
|
||||
assert.deepEqual(bytes, { length: size, valid: true });
|
||||
}
|
||||
console.log(`PASS: tracker reconnect through ${new URL(trackerUrl).host}: pairing setup with peer confirmation, reload, Reconnect on both pages without codes, device proofs, exact bytes in both directions.`);
|
||||
}
|
||||
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||||
|
||||
@@ -3,7 +3,7 @@ import { onActivated, onMounted, ref, shallowRef } from 'vue';
|
||||
import { clearIdentityStorage, createIdentity, loadIdentityState, saveIdentityState, type IdentityState } from '../lib/identity.ts';
|
||||
import type { ConnectionUpdate } from '../lib/connections.ts';
|
||||
import { asError } from '../lib/validation.ts';
|
||||
const props = defineProps<{ disabled: boolean; paired: string; remember: boolean }>();
|
||||
const props = defineProps<{ disabled: boolean; paired: string; remember: boolean; reconnect: string }>();
|
||||
const emit = defineEmits<{ update: [change: ConnectionUpdate] }>();
|
||||
const supported = (() => { try { return isSecureContext && !!crypto.subtle && !!window.indexedDB; } catch { return false; } })();
|
||||
const state = shallowRef<IdentityState>({ identity: null });
|
||||
@@ -37,6 +37,7 @@ function create() { void run(async () => { state.value = await saveIdentityState
|
||||
function reset() { void run(async () => { if (!confirmDelete.value) return; state.value = await saveIdentityState({ identity: null }, state.value.revision); confirmDelete.value = false; }); }
|
||||
function toggle(event: Event) { if (!props.disabled && event.target instanceof HTMLInputElement) emit('update', { rememberDevice: event.target.checked }); }
|
||||
function forget() { if (!props.disabled) emit('update', { peerKey: '' }); }
|
||||
function stopReconnect() { if (!props.disabled) emit('update', { reconnect: null }); }
|
||||
async function refreshIdentity() {
|
||||
if (working.value) throw new Error('Wait for the device settings operation to finish before connecting.');
|
||||
if (!supported) return null;
|
||||
@@ -62,6 +63,10 @@ defineExpose({ refreshIdentity });
|
||||
<template v-else>
|
||||
<template v-if="paired">
|
||||
<p class="status">Paired device <code>{{ paired.slice(-12) }}</code>. Later sessions verify it automatically.</p>
|
||||
<template v-if="reconnect">
|
||||
<p class="status">Reconnects without codes through <strong>{{ reconnect }}</strong>.</p>
|
||||
<button @click="stopReconnect">Turn off reconnect</button>
|
||||
</template>
|
||||
<button @click="forget">Forget device</button>
|
||||
</template>
|
||||
<label v-else><input id="remember-device" :checked="remember" type="checkbox" @change="toggle" /> Use my device identity on this connection</label>
|
||||
|
||||
@@ -13,10 +13,16 @@ import { FileSession, QUEUE_LIMIT, type QueueItem } from '../lib/session.ts';
|
||||
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
|
||||
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
|
||||
import type { ConnectionUpdate, SavedConnection } from '../lib/connections.ts';
|
||||
import { derivePairing, discoveryId, pairingNonce, parseNonce, signalingKey, trackerUrl } from '../lib/reconnect.ts';
|
||||
import { ReconnectAttempt } from '../lib/tracker.ts';
|
||||
import type { Identity } from '../lib/identity.ts';
|
||||
|
||||
type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
type Step = 'session-ready' | 'idle' | 'discovering' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
interface Session {
|
||||
pc: RTCPeerConnection;
|
||||
// Offers and creates the data channel. Manual setup follows Send/Receive;
|
||||
// tracker reconnect lets the lower device key offer.
|
||||
initiator: boolean;
|
||||
options: IceOptions;
|
||||
controller: AbortController;
|
||||
transfer: FileSession | null;
|
||||
@@ -86,11 +92,24 @@ const receiveMethod = computed(() => {
|
||||
});
|
||||
const savedToDisk = ref(false);
|
||||
let active: Session | null = null;
|
||||
// Tracker reconnect: one attempt per slot and browser profile, cancelled by
|
||||
// reset, failure and unmount. reconnectRun invalidates stale async steps.
|
||||
let attempt: ReconnectAttempt | null = null, releaseLock: (() => void) | null = null, attemptTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let reconnectRun = 0;
|
||||
const discoveryHost = ref(''), discoveryPeers = ref(0);
|
||||
// Reconnect setup over a session whose peer proved the paired device key.
|
||||
const authenticatedPeer = ref('');
|
||||
const pairingState = ref<'' | 'proposed' | 'incoming' | 'accepted' | 'done'>(''), pairingError = ref('');
|
||||
const proposedTracker = ref(import.meta.env.VITE_TRACKER_URL || ''), incomingTracker = ref('');
|
||||
let pairingSetup: { tracker: string; proposer: string; acceptor?: string; key?: CryptoKey } | null = null;
|
||||
const canPair = computed(() => connected.value && !!authenticatedPeer.value && authenticatedPeer.value === props.connection.peerKey);
|
||||
const trackerHost = (url: string) => { try { return new URL(url).host; } catch { return url; } };
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done', 'session-ready'].includes(step.value));
|
||||
const status = computed(() => ({
|
||||
'session-ready': 'Connected. Add files to send, or wait for your peer.',
|
||||
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
|
||||
discovering: discoveryPeers.value ? 'Your peer is online. Connecting…' : `Waiting for your peer on ${discoveryHost.value}. Ask them to open this connection and press Reconnect.`,
|
||||
gathering: 'Gathering connection info (up to 30 seconds)…',
|
||||
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
|
||||
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
|
||||
@@ -121,6 +140,7 @@ function dispose() {
|
||||
if (incoming.value && receiveState.value && !['done', 'closed'].includes(receiveState.value)) receiveState.value = 'closed';
|
||||
}
|
||||
active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', false);
|
||||
authenticatedPeer.value = ''; pairingState.value = ''; pairingError.value = ''; pairingSetup = null;
|
||||
managedCredentials.value = null; settings.value.allowTurn = false;
|
||||
if (!old) return;
|
||||
clearTimeout(old.timer);
|
||||
@@ -131,9 +151,14 @@ function dispose() {
|
||||
old.transfer?.close();
|
||||
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
|
||||
}
|
||||
function stopAttempt() {
|
||||
reconnectRun++; clearTimeout(attemptTimer);
|
||||
attempt?.close(); attempt = null;
|
||||
releaseLock?.(); releaseLock = null;
|
||||
}
|
||||
function reset(keepNetwork = false) {
|
||||
const allowTurn = settings.value.allowTurn;
|
||||
dispose(); revokeDownload(); clearTimeout(copyTimer);
|
||||
stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer);
|
||||
if (keepNetwork) settings.value.allowTurn = allowTurn;
|
||||
latestDiagnostics = null; diagnosticLines.value = [];
|
||||
managedCredentials.value = null;
|
||||
@@ -148,7 +173,7 @@ function reset(keepNetwork = false) {
|
||||
function fail(session: Session, err: unknown) {
|
||||
if (active !== session) return;
|
||||
session.diagnostics.record('session failed');
|
||||
dispose();
|
||||
stopAttempt(); dispose();
|
||||
managedCredentials.value = null;
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = false;
|
||||
@@ -176,7 +201,7 @@ function pickFiles(event: Event) {
|
||||
}
|
||||
function removeQueued(id: number) { active?.transfer?.remove(id); }
|
||||
function disconnect() {
|
||||
dispose(); step.value = 'closed';
|
||||
stopAttempt(); dispose(); step.value = 'closed';
|
||||
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
|
||||
if (receiveState.value && receiveState.value !== 'done') receiveState.value = 'closed';
|
||||
incoming.value = null; outputCode.value = ''; fps.value = null; verified.value = false;
|
||||
@@ -187,17 +212,25 @@ function attach(session: Session, channel: RTCDataChannel) {
|
||||
if (session.transfer || channel.label !== 'hellcon-v3' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
|
||||
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
|
||||
}
|
||||
session.transfer = new FileSession(channel, !!props.sending, {
|
||||
const transfer = session.transfer = new FileSession(channel, session.initiator, {
|
||||
onReady: () => { if (active === session) {
|
||||
connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer);
|
||||
stopAttempt();
|
||||
// Ready implies both fresh proofs verified, so the key may now be saved.
|
||||
if (session.identityContext && session.remoteHello) {
|
||||
const key = session.remoteHello.key;
|
||||
if (session.expected === key) identityStatus.value = 'Paired device authenticated for this connection.';
|
||||
else if (rememberPeer.value) { emit('update', { peerKey: key }); identityStatus.value = `Device proof checked. Remembered for ${props.connection.name}.`; }
|
||||
if (session.expected === key) { identityStatus.value = 'Paired device authenticated for this connection.'; authenticatedPeer.value = key; }
|
||||
else if (rememberPeer.value) { emit('update', { peerKey: key }); identityStatus.value = `Device proof checked. Remembered for ${props.connection.name}.`; authenticatedPeer.value = key; }
|
||||
else identityStatus.value = 'Device proof checked. This device was not remembered.';
|
||||
}
|
||||
// Files chosen before connecting join the queue once the session is ready,
|
||||
// so a replaced reconnect peer never takes them along.
|
||||
if (selectedFiles.value.length) {
|
||||
try { transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
}
|
||||
} },
|
||||
onPairing: message => void receivePairing(session, message),
|
||||
onQueue: items => { if (active === session) queuedFiles.value = items; },
|
||||
onState: (direction, state, meta) => {
|
||||
if (active !== session) return;
|
||||
@@ -230,11 +263,10 @@ function attach(session: Session, channel: RTCDataChannel) {
|
||||
onClose: () => { if (active === session) disconnect(); },
|
||||
onError: err => fail(session, err),
|
||||
});
|
||||
if (props.sending) { session.transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
|
||||
configureIdentity(session);
|
||||
if (verified.value) session.transfer.verify();
|
||||
}
|
||||
function start() {
|
||||
function start(initiator: boolean) {
|
||||
const chosen = settings.value;
|
||||
const options = {
|
||||
...chosen,
|
||||
@@ -248,7 +280,7 @@ function start() {
|
||||
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
|
||||
});
|
||||
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
|
||||
const session: Session = { pc, options, controller: new AbortController(), transfer: null, diagnostics };
|
||||
const session: Session = { pc, initiator, options, controller: new AbortController(), transfer: null, diagnostics };
|
||||
active = session; emit('sessionChange', true);
|
||||
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
||||
pc.ondatachannel = event => attach(session, event.channel);
|
||||
@@ -273,7 +305,7 @@ async function createCode() {
|
||||
if (!file.value) throw new Error('Choose a file first.');
|
||||
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
||||
}
|
||||
session = start();
|
||||
session = start(!!props.sending);
|
||||
// Re-read saved trust for each connection; another tab may have forgotten
|
||||
// the paired peer or replaced the local identity since this page loaded.
|
||||
if (props.connection.rememberDevice) {
|
||||
@@ -346,7 +378,7 @@ function configureIdentity(session: Session) {
|
||||
else if (session.localHello || session.remoteHello) identityStatus.value = 'Both people must use their device identity to remember each other. Compare fingerprints manually for this connection.';
|
||||
return;
|
||||
}
|
||||
const initiator = !!props.sending;
|
||||
const initiator = session.initiator;
|
||||
const context: IdentityContext = {
|
||||
offer: initiator ? session.localHello : session.remoteHello,
|
||||
answer: initiator ? session.remoteHello : session.localHello,
|
||||
@@ -371,6 +403,178 @@ function verify() {
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
// Holds a Web Lock for the attempt so two tabs of this browser never reconnect
|
||||
// the same slot at once. Resolves null when another tab holds it.
|
||||
function exclusive(name: string) {
|
||||
if (!navigator.locks) return Promise.resolve<(() => void) | null>(() => {});
|
||||
return new Promise<(() => void) | null>(resolve => {
|
||||
navigator.locks.request(name, { ifAvailable: true }, lock => lock ? new Promise<void>(release => resolve(release)) : resolve(null)).catch(() => resolve(null));
|
||||
});
|
||||
}
|
||||
function abortReconnect(err: unknown) {
|
||||
if (active) { fail(active, err); return; }
|
||||
stopAttempt(); settings.value.allowTurn = false;
|
||||
emit('sessionChange', false);
|
||||
error.value = asError(err).message; step.value = 'closed';
|
||||
}
|
||||
interface ReconnectContext { run: number; identity: Identity; peerKey: string }
|
||||
const cancelled = () => new Error('Reconnect cancelled.');
|
||||
// Each offer or answer gets a fresh peer connection; the previous one is closed.
|
||||
async function reconnectPeer(context: ReconnectContext, initiator: boolean) {
|
||||
if (context.run !== reconnectRun) throw cancelled();
|
||||
const allowTurn = settings.value.allowTurn;
|
||||
if (active) dispose();
|
||||
settings.value.allowTurn = allowTurn;
|
||||
fps.value = null; verified.value = false; identityStatus.value = '';
|
||||
const session = start(initiator);
|
||||
session.expected = context.peerKey; session.identity = context.identity; session.localHello = hello(context.identity);
|
||||
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
|
||||
if (active !== session) throw cancelled();
|
||||
session.pc.setConfiguration(iceConfiguration(configured));
|
||||
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
|
||||
return session;
|
||||
}
|
||||
function checkPeer(context: ReconnectContext, key: string | undefined) {
|
||||
if (key !== context.peerKey) throw new Error('A different device answered on this pairing. Exchange codes manually to check it.');
|
||||
}
|
||||
async function reconnectOffer(context: ReconnectContext) {
|
||||
const session = await reconnectPeer(context, true);
|
||||
session.ref = createRef();
|
||||
attach(session, session.pc.createDataChannel('hellcon-v3'));
|
||||
const sdp = await createOffer(session.pc, { ...session.options, signal: session.controller.signal });
|
||||
if (active !== session) throw cancelled();
|
||||
session.diagnostics.record('reconnect offer ready');
|
||||
return encodeCode({ type: 'offer', ref: session.ref, sdp, identity: session.localHello });
|
||||
}
|
||||
async function reconnectAnswer(context: ReconnectContext, text: string) {
|
||||
const session = await reconnectPeer(context, false);
|
||||
const offer = await decodeCode(text, { type: 'offer', allowTurn: session.options.allowTurn });
|
||||
if (active !== session) throw cancelled();
|
||||
checkPeer(context, offer.identity?.key);
|
||||
session.ref = offer.ref; session.remoteHello = offer.identity;
|
||||
const options = { ...session.options, signal: session.controller.signal };
|
||||
const sdp = await createAnswer(session.pc, offer.sdp, options);
|
||||
if (active !== session) throw cancelled();
|
||||
const code = await encodeCode({ type: 'answer', ref: session.ref, sdp, identity: session.localHello });
|
||||
session.diagnostics.record('reconnect answer ready');
|
||||
fps.value = getFingerprints(session.pc, options); configureIdentity(session);
|
||||
return code;
|
||||
}
|
||||
async function reconnectAccept(context: ReconnectContext, text: string) {
|
||||
const session = active;
|
||||
if (context.run !== reconnectRun || !session?.initiator || !session.ref) throw cancelled();
|
||||
const answer = await decodeCode(text, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
|
||||
if (active !== session) throw cancelled();
|
||||
checkPeer(context, answer.identity?.key);
|
||||
session.remoteHello = answer.identity;
|
||||
await acceptAnswer(session.pc, answer.sdp, session.options);
|
||||
if (active !== session) throw cancelled();
|
||||
session.diagnostics.record('answer applied');
|
||||
fps.value = getFingerprints(session.pc, session.options); configureIdentity(session);
|
||||
}
|
||||
async function reconnect() {
|
||||
if (busy.value || connected.value) return;
|
||||
reset(true);
|
||||
const run = reconnectRun;
|
||||
step.value = 'discovering'; discoveryPeers.value = 0; emit('sessionChange', true);
|
||||
try {
|
||||
const release = await exclusive(`hellcon-reconnect-${props.connection.id}`);
|
||||
if (run !== reconnectRun) { release?.(); return; }
|
||||
if (!release) throw new Error('Another HellCon tab is already reconnecting this connection.');
|
||||
releaseLock = release;
|
||||
// Re-read trust and identity: another tab may have forgotten the device.
|
||||
const trust = await props.loadTrust();
|
||||
const pairing = trust.reconnect;
|
||||
if (!pairing) throw new Error('Reconnect is not set up for this connection. Exchange codes manually.');
|
||||
const identity = await devices.value?.refreshIdentity();
|
||||
if (run !== reconnectRun) return;
|
||||
if (!identity || identity.publicKey !== pairing.localKey) throw new Error('This browser’s device identity changed since reconnect was set up. Exchange codes manually and set it up again.');
|
||||
const [infoHash, key] = await Promise.all([discoveryId(pairing.key), signalingKey(pairing.key)]);
|
||||
if (run !== reconnectRun) return;
|
||||
const url = pairing.trackers[0]!;
|
||||
discoveryHost.value = trackerHost(url);
|
||||
const context: ReconnectContext = { run, identity, peerKey: pairing.peerKey };
|
||||
const current: ReconnectAttempt = new ReconnectAttempt({
|
||||
url, infoHash, key, initiator: identity.publicKey < pairing.peerKey,
|
||||
hooks: {
|
||||
createOffer: () => reconnectOffer(context),
|
||||
createAnswer: offer => reconnectAnswer(context, offer),
|
||||
acceptAnswer: answer => reconnectAccept(context, answer),
|
||||
onPeers: count => { if (attempt === current) discoveryPeers.value = count; },
|
||||
onError: err => { if (attempt === current) abortReconnect(err); },
|
||||
},
|
||||
});
|
||||
attempt = current;
|
||||
attemptTimer = setTimeout(() => abortReconnect(new Error('Reconnect timed out. Check that both people pressed Reconnect, or exchange codes manually.')), 5 * 60 * 1000);
|
||||
await current.start();
|
||||
} catch (err) { if (run === reconnectRun) abortReconnect(err); }
|
||||
}
|
||||
function derivePairingKey(session: Session, setup: { tracker: string; proposer: string; acceptor?: string }, proposer: boolean) {
|
||||
const context = session.identityContext, local = session.localHello?.key, remote = session.remoteHello?.key;
|
||||
if (!context || !local || !remote || !setup.acceptor) throw new Error('Reconnect needs a session authenticated by both device identities.');
|
||||
return derivePairing({
|
||||
proposerNonce: setup.proposer, acceptorNonce: setup.acceptor,
|
||||
proposerKey: proposer ? local : remote, acceptorKey: proposer ? remote : local,
|
||||
offerFingerprint: context.offerFingerprint, answerFingerprint: context.answerFingerprint, tracker: setup.tracker,
|
||||
});
|
||||
}
|
||||
function storePairing(session: Session, tracker: string, key: CryptoKey) {
|
||||
emit('update', { reconnect: { version: 1, trackers: [tracker], key, localKey: session.localHello!.key, peerKey: session.remoteHello!.key } });
|
||||
}
|
||||
// The proposer suggests a tracker; the peer sees it and accepts before anything
|
||||
// is stored or contacted. Both contribute a nonce; the proposer stores first.
|
||||
function proposePairing() {
|
||||
const session = active;
|
||||
if (!session?.transfer || !canPair.value || pairingState.value === 'proposed' || pairingState.value === 'accepted') return;
|
||||
try {
|
||||
pairingSetup = { tracker: trackerUrl(proposedTracker.value), proposer: pairingNonce() };
|
||||
session.transfer.sendPairing({ step: 'propose', tracker: pairingSetup.tracker, nonce: pairingSetup.proposer });
|
||||
pairingState.value = 'proposed'; pairingError.value = '';
|
||||
} catch (err) { pairingError.value = asError(err).message; }
|
||||
}
|
||||
async function acceptPairing() {
|
||||
const session = active, setup = pairingSetup;
|
||||
if (!session?.transfer || pairingState.value !== 'incoming' || !setup) return;
|
||||
try {
|
||||
setup.acceptor = pairingNonce();
|
||||
setup.key = await derivePairingKey(session, setup, false);
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
session.transfer.sendPairing({ step: 'accept', nonce: setup.acceptor });
|
||||
pairingState.value = 'accepted';
|
||||
} catch (err) { pairingState.value = ''; pairingError.value = asError(err).message; }
|
||||
}
|
||||
function declinePairing() {
|
||||
try { active?.transfer?.sendPairing({ step: 'decline' }); } catch { /* the session ended */ }
|
||||
pairingState.value = ''; pairingSetup = null;
|
||||
}
|
||||
async function receivePairing(session: Session, message: Record<string, unknown>) {
|
||||
if (active !== session) return;
|
||||
try {
|
||||
if (message.step === 'propose') {
|
||||
if (pairingState.value === 'proposed' || pairingState.value === 'accepted') throw new Error('You both proposed reconnect at once. Let one person set it up.');
|
||||
if (!canPair.value) {
|
||||
session.transfer?.sendPairing({ step: 'decline' });
|
||||
throw new Error('Your peer proposed tracker reconnect, but this connection has not remembered their device.');
|
||||
}
|
||||
pairingSetup = { tracker: trackerUrl(message.tracker), proposer: parseNonce(message.nonce) };
|
||||
incomingTracker.value = pairingSetup.tracker; pairingState.value = 'incoming'; pairingError.value = '';
|
||||
} else if (message.step === 'accept' && pairingState.value === 'proposed' && pairingSetup) {
|
||||
const setup = pairingSetup;
|
||||
setup.acceptor = parseNonce(message.nonce);
|
||||
const key = await derivePairingKey(session, setup, true);
|
||||
if (active !== session || pairingSetup !== setup) return;
|
||||
storePairing(session, setup.tracker, key);
|
||||
session.transfer?.sendPairing({ step: 'done' });
|
||||
pairingState.value = 'done';
|
||||
} else if (message.step === 'done' && pairingState.value === 'accepted' && pairingSetup?.key) {
|
||||
storePairing(session, pairingSetup.tracker, pairingSetup.key);
|
||||
pairingState.value = 'done';
|
||||
} else if (message.step === 'decline') {
|
||||
if (pairingState.value === 'proposed' || pairingState.value === 'accepted') pairingError.value = 'Your peer declined tracker reconnect.';
|
||||
pairingState.value = ''; pairingSetup = null;
|
||||
} else throw new Error('Unexpected reconnect setup message.');
|
||||
} catch (err) { if (active === session) { pairingState.value = ''; pairingSetup = null; pairingError.value = asError(err).message; } }
|
||||
}
|
||||
async function acceptFile() {
|
||||
const session = active, destination = receiveMethod.value;
|
||||
if (!session?.transfer || !incoming.value || !destination || choosing.value || receiveState.value !== 'choose-storage') return;
|
||||
@@ -416,7 +620,7 @@ function formatBytes(bytes: number) {
|
||||
function selectCode(event: FocusEvent) {
|
||||
if (event.target instanceof HTMLTextAreaElement) event.target.select();
|
||||
}
|
||||
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
onBeforeUnmount(() => { stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -434,11 +638,15 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<p v-if="outgoing" class="status">Sending: {{ outgoing.name }} — {{ stateLabel(sendState) }} ({{ progress }}%)</p>
|
||||
<div v-if="outgoing" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Sending progress"><div :style="{ width: progress + '%' }"></div></div>
|
||||
</section>
|
||||
<DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :disabled="busy || connected" @update="emit('update', $event)" />
|
||||
<DeviceSettings ref="devices" :paired="connection.peerKey" :remember="connection.rememberDevice" :reconnect="connection.reconnect ? trackerHost(connection.reconnect.trackers[0]!) : ''" :disabled="busy || connected" @update="emit('update', $event)" />
|
||||
<details class="config-details">
|
||||
<summary>Network settings</summary>
|
||||
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
|
||||
</details>
|
||||
<template v-if="connection.reconnect && !connected">
|
||||
<button class="primary" :disabled="busy" @click="reconnect">Reconnect</button>
|
||||
<p class="status">Both people open {{ connection.name }} and press Reconnect; {{ trackerHost(connection.reconnect.trackers[0]!) }} introduces your browsers. Or exchange codes below.</p>
|
||||
</template>
|
||||
<p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p>
|
||||
<template v-if="!sending">
|
||||
<label class="step" for="offer-input">Paste the sender’s connection code</label>
|
||||
@@ -490,6 +698,25 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
</details>
|
||||
<p v-if="!connected && step === 'done'" class="status">Connection ended. Exchange fresh codes to send more files.</p>
|
||||
<p v-if="connected" class="status">Connection verified. Either person can add files. Keep both tabs open.</p>
|
||||
<section v-if="canPair" class="reconnect-setup" aria-labelledby="reconnect-heading">
|
||||
<h2 id="reconnect-heading" class="step">Reconnect without codes</h2>
|
||||
<template v-if="pairingState === 'incoming'">
|
||||
<p class="status">Your peer proposes reconnecting through <strong>{{ trackerHost(incomingTracker) }}</strong>. The tracker sees both IP addresses and when you connect, but not your files or codes.</p>
|
||||
<div class="session-actions">
|
||||
<button class="primary" @click="acceptPairing">Accept</button>
|
||||
<button @click="declinePairing">Decline</button>
|
||||
</div>
|
||||
</template>
|
||||
<p v-else-if="pairingState === 'proposed' || pairingState === 'accepted'" class="status" role="status">Waiting for your peer to confirm…</p>
|
||||
<p v-else-if="pairingState === 'done'" class="status" role="status">Reconnect is set up. Next time, both people open {{ connection.name }} and press Reconnect.</p>
|
||||
<template v-else>
|
||||
<p class="status">Next time, both people press Reconnect instead of exchanging codes. A WebTorrent tracker introduces your browsers: it sees IP addresses and timing, not files or codes. Your peer confirms the tracker first.</p>
|
||||
<label class="step" for="tracker-url">Tracker address</label>
|
||||
<input id="tracker-url" v-model="proposedTracker" class="stun-input" placeholder="wss://tracker.example" autocomplete="off" spellcheck="false" />
|
||||
<button :disabled="!proposedTracker.trim()" @click="proposePairing">{{ connection.reconnect ? 'Set up reconnect again' : 'Set up reconnect' }}</button>
|
||||
</template>
|
||||
<p v-if="pairingError" class="error" role="alert">{{ pairingError }}</p>
|
||||
</section>
|
||||
<div v-if="step !== 'idle'" class="session-actions">
|
||||
<button v-if="connected || busy" @click="disconnect">Disconnect</button>
|
||||
<button @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
||||
|
||||
Vendored
+1
@@ -8,6 +8,7 @@ declare module '*.vue' {
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_ICE_ENDPOINT?: string;
|
||||
readonly VITE_STUN_URL?: string;
|
||||
readonly VITE_TRACKER_URL?: string;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
|
||||
+3
-3
@@ -20,13 +20,13 @@ export interface Signal {
|
||||
}
|
||||
export interface DecodeOptions extends Pick<IceOptions, 'allowTurn'> { type?: Signal['type']; ref?: string }
|
||||
|
||||
function toBase64Url(bytes: Uint8Array) {
|
||||
export function toBase64Url(bytes: Uint8Array) {
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
||||
}
|
||||
function fromBase64Url(text: string) {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) throw new Error(INVALID);
|
||||
export function fromBase64Url(text: string, invalid = INVALID) {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) throw new Error(invalid);
|
||||
return Uint8Array.from(atob(text.replaceAll('-', '+').replaceAll('_', '/')), char => char.charCodeAt(0));
|
||||
}
|
||||
async function deflate(text: string) {
|
||||
|
||||
+14
-4
@@ -1,3 +1,4 @@
|
||||
import { parsePairing, type ReconnectPairing } from './reconnect.ts';
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export const CONNECTION_LIMIT = 100;
|
||||
@@ -9,8 +10,10 @@ export interface SavedConnection {
|
||||
peerKey: string;
|
||||
// Per-connection opt-in to include this browser's identity in codes.
|
||||
rememberDevice: boolean;
|
||||
// Tracker reconnect with the paired device. Cleared whenever that device changes.
|
||||
reconnect: ReconnectPairing | null;
|
||||
}
|
||||
export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean };
|
||||
export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean } | { reconnect: ReconnectPairing | null };
|
||||
export function connectionName(value: string) {
|
||||
const name = value.trim();
|
||||
if (!name || name.length > 80) throw new Error('Use a connection name between 1 and 80 characters.');
|
||||
@@ -20,18 +23,25 @@ export function updateConnection(current: SavedConnection, update: ConnectionUpd
|
||||
if ('name' in update) return { ...current, name: connectionName(update.name) };
|
||||
if ('peerKey' in update) {
|
||||
if (update.peerKey && !/^04[0-9a-f]{128}$/.test(update.peerKey)) throw new Error('Invalid paired device.');
|
||||
return { ...current, peerKey: update.peerKey };
|
||||
return { ...current, peerKey: update.peerKey, reconnect: update.peerKey === current.peerKey ? current.reconnect : null };
|
||||
}
|
||||
if ('rememberDevice' in update) return { ...current, rememberDevice: update.rememberDevice === true };
|
||||
if ('reconnect' in update) {
|
||||
if (!update.reconnect) return { ...current, reconnect: null };
|
||||
const reconnect = parsePairing(update.reconnect, current.peerKey);
|
||||
if (!reconnect) throw new Error('Reconnect needs this connection’s paired device. Pair again and retry.');
|
||||
return { ...current, reconnect };
|
||||
}
|
||||
throw new Error('Invalid connection update.');
|
||||
}
|
||||
export function emptyConnection(number = 1): SavedConnection {
|
||||
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false };
|
||||
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false, reconnect: null };
|
||||
}
|
||||
function validateConnection(value: unknown): SavedConnection {
|
||||
if (!isRecord(value) || typeof value.id !== 'string' || !value.id || !Number.isSafeInteger(value.number) || (value.number as number) < 1 ||
|
||||
typeof value.name !== 'string' || typeof value.peerKey !== 'string') throw new Error('Saved connections are unreadable.');
|
||||
return updateConnection({ id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true }, { peerKey: value.peerKey });
|
||||
const record = updateConnection({ id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true, reconnect: null }, { peerKey: value.peerKey });
|
||||
return { ...record, reconnect: parsePairing(value.reconnect, record.peerKey) };
|
||||
}
|
||||
async function database() {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { fromBase64Url, MAX_CODE_LENGTH, toBase64Url } from './codes.ts';
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
// Tracker reconnect for paired devices. Both peers contribute a nonce over an
|
||||
// authenticated session; HKDF turns them into a stored base key, from which a
|
||||
// daily swarm identifier and a signaling key are derived. Trackers only see
|
||||
// sealed envelopes; device proofs still authenticate every reconnected session.
|
||||
export const RECONNECT_VERSION = 1;
|
||||
export interface ReconnectPairing {
|
||||
version: 1;
|
||||
// Agreed at pairing time, in order. The first release contacts only the first.
|
||||
trackers: string[];
|
||||
// Non-extractable HKDF base key.
|
||||
key: CryptoKey;
|
||||
localKey: string;
|
||||
peerKey: string;
|
||||
}
|
||||
export interface PairingContext {
|
||||
proposerNonce: string; acceptorNonce: string;
|
||||
proposerKey: string; acceptorKey: string;
|
||||
offerFingerprint: string; answerFingerprint: string;
|
||||
tracker: string;
|
||||
}
|
||||
export type SignalRole = 'wake' | 'offer' | 'answer';
|
||||
// Tracker routing fields as 20-character binary strings; `to` is empty for offers.
|
||||
export interface SignalRoute { role: SignalRole; infoHash: string; offerId: string; from: string; to: string }
|
||||
|
||||
const PREFIX = 'HCR1.';
|
||||
const ROLES: Record<SignalRole, string> = { wake: 'w', offer: 'o', answer: 'a' };
|
||||
// Envelopes expire quickly; the tolerance absorbs clock differences between devices.
|
||||
export const SIGNAL_LIFETIME = 2 * 60 * 1000;
|
||||
export const CLOCK_TOLERANCE = 5 * 60 * 1000;
|
||||
export const MAX_ENVELOPE_LENGTH = Math.ceil((MAX_CODE_LENGTH + 256) * 4 / 3) + 64;
|
||||
const INVALID = 'Invalid reconnect message.';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const label = (...parts: (string | number)[]) => encoder.encode(JSON.stringify(['HellCon reconnect', RECONNECT_VERSION, ...parts]));
|
||||
const hex = (bytes: Uint8Array) => Array.from(bytes, n => n.toString(16).padStart(2, '0')).join('');
|
||||
const binaryHex = (text: string) => hex(Uint8Array.from(text, char => char.charCodeAt(0)));
|
||||
function unhex(value: unknown, length: number) {
|
||||
if (typeof value !== 'string' || value.length !== length * 2 || !/^[0-9a-f]+$/.test(value)) throw new Error('Invalid reconnect setup.');
|
||||
return Uint8Array.from(value.match(/../g)!, n => parseInt(n, 16));
|
||||
}
|
||||
|
||||
export function pairingNonce() { return hex(crypto.getRandomValues(new Uint8Array(32))); }
|
||||
export function parseNonce(value: unknown) { unhex(value, 32); return value as string; }
|
||||
export const utcDay = (time = Date.now()) => Math.floor(time / 86_400_000);
|
||||
|
||||
// Accepts one secure WebSocket URL; plain ws:// only for this machine.
|
||||
export function trackerUrl(value: unknown) {
|
||||
if (typeof value !== 'string' || value.length > 1024) throw new Error('Enter a tracker address starting with wss://.');
|
||||
let url: URL;
|
||||
try { url = new URL(value.trim()); } catch { throw new Error('Enter a tracker address starting with wss://.'); }
|
||||
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
||||
if (url.protocol !== 'wss:' && !(url.protocol === 'ws:' && loopback)) throw new Error('Enter a tracker address starting with wss://.');
|
||||
if (url.username || url.password || url.hash) throw new Error('Tracker addresses cannot contain credentials or a fragment.');
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export async function derivePairing(context: PairingContext) {
|
||||
const ikm = new Uint8Array(64);
|
||||
ikm.set(unhex(context.proposerNonce, 32)); ikm.set(unhex(context.acceptorNonce, 32), 32);
|
||||
unhex(context.proposerKey, 65); unhex(context.acceptorKey, 65);
|
||||
if (context.proposerKey === context.acceptorKey) throw new Error('Reconnect needs two different devices.');
|
||||
const salt = await crypto.subtle.digest('SHA-256', label('pairing', context.proposerKey, context.acceptorKey, context.offerFingerprint, context.answerFingerprint, trackerUrl(context.tracker)));
|
||||
const input = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info: label('base') }, input, 256);
|
||||
return crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits', 'deriveKey']);
|
||||
}
|
||||
|
||||
// The tracker's info_hash for one UTC day, as a 20-byte binary string.
|
||||
export async function discoveryId(key: CryptoKey, day = utcDay()) {
|
||||
const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: label('discovery', day) }, key, 160);
|
||||
return String.fromCharCode(...new Uint8Array(bits));
|
||||
}
|
||||
|
||||
export function signalingKey(key: CryptoKey) {
|
||||
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: label('signaling') }, key, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
|
||||
function associatedData(route: SignalRoute) {
|
||||
return label('signal', route.role, binaryHex(route.infoHash), binaryHex(route.offerId), binaryHex(route.from), binaryHex(route.to));
|
||||
}
|
||||
|
||||
export function signalRole(text: unknown): SignalRole | null {
|
||||
if (typeof text !== 'string' || !text.startsWith(PREFIX)) return null;
|
||||
return (Object.keys(ROLES) as SignalRole[]).find(role => text.startsWith(`${PREFIX}${ROLES[role]}.`)) ?? null;
|
||||
}
|
||||
|
||||
// Wakes carry no code; offers and answers carry a complete HellCon code.
|
||||
export async function sealSignal(key: CryptoKey, route: SignalRoute, code: string, now = Date.now()) {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const plain = encoder.encode(JSON.stringify({ expires: now + SIGNAL_LIFETIME, code }));
|
||||
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: associatedData(route) }, key, plain));
|
||||
const body = new Uint8Array(iv.length + sealed.length);
|
||||
body.set(iv); body.set(sealed, iv.length);
|
||||
return `${PREFIX}${ROLES[route.role]}.${toBase64Url(body)}`;
|
||||
}
|
||||
|
||||
export async function openSignal(key: CryptoKey, route: SignalRoute, text: unknown, now = Date.now()) {
|
||||
if (typeof text !== 'string' || text.length > MAX_ENVELOPE_LENGTH || signalRole(text) !== route.role) throw new Error(INVALID);
|
||||
const body = fromBase64Url(text.slice(PREFIX.length + 2), INVALID);
|
||||
if (body.length < 12 + 16) throw new Error(INVALID);
|
||||
let data: unknown;
|
||||
try {
|
||||
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: body.subarray(0, 12), additionalData: associatedData(route) }, key, body.subarray(12));
|
||||
data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain));
|
||||
} catch { throw new Error(INVALID); }
|
||||
if (!isRecord(data) || typeof data.code !== 'string' || typeof data.expires !== 'number' || (route.role === 'wake') !== !data.code) throw new Error(INVALID);
|
||||
if (data.expires < now - CLOCK_TOLERANCE || data.expires > now + SIGNAL_LIFETIME + CLOCK_TOLERANCE) throw new Error('Reconnect message expired. Check both devices’ clocks.');
|
||||
return data.code;
|
||||
}
|
||||
|
||||
// Storage validation: an unusable pairing is dropped rather than failing the record.
|
||||
export function parsePairing(value: unknown, peerKey: string): ReconnectPairing | null {
|
||||
if (!isRecord(value) || value.version !== RECONNECT_VERSION || !peerKey || value.peerKey !== peerKey) return null;
|
||||
if (!(value.key instanceof CryptoKey) || value.key.algorithm.name !== 'HKDF' || typeof value.localKey !== 'string' || !/^04[0-9a-f]{128}$/.test(value.localKey)) return null;
|
||||
if (!Array.isArray(value.trackers) || value.trackers.length < 1 || value.trackers.length > 4) return null;
|
||||
try { return { version: RECONNECT_VERSION, trackers: value.trackers.map(trackerUrl), key: value.key, localKey: value.localKey, peerKey }; }
|
||||
catch { return null; }
|
||||
}
|
||||
@@ -13,6 +13,8 @@ export interface SessionCallbacks {
|
||||
onDecline(direction: 'send' | 'receive', meta: FileMetadata): void;
|
||||
onError(error: Error): void;
|
||||
onClose(): void;
|
||||
// Reconnect setup messages, delivered only after both peers verified.
|
||||
onPairing?(message: Record<string, unknown>): void;
|
||||
}
|
||||
export interface SessionAuthentication { sign(): Promise<string>; verify(proof: unknown): Promise<void> }
|
||||
interface Active { id: number; transfer: Transfer; meta: FileMetadata }
|
||||
@@ -91,6 +93,10 @@ export class FileSession {
|
||||
for (const file of files) { this.pending.push({ id: this.nextId, file }); this.nextId += 2; }
|
||||
this.callbacks.onQueue([...this.pending]); this.pump();
|
||||
}
|
||||
sendPairing(message: Record<string, unknown>) {
|
||||
if (!this.started || this.closed) throw new Error('Connection ended.');
|
||||
this.control({ ...message, type: 'pairing' });
|
||||
}
|
||||
remove(id: number) { this.pending = this.pending.filter(item => item.id !== id); this.callbacks.onQueue([...this.pending]); }
|
||||
accept(destination: FileDestination | null = null) {
|
||||
if (!this.incoming) throw new Error('File is no longer available.');
|
||||
@@ -170,6 +176,7 @@ export class FileSession {
|
||||
this.peerReady = true; this.ready(); return;
|
||||
}
|
||||
if (!this.started) throw new Error('File data arrived before verification.');
|
||||
if (msg.type === 'pairing' && this.callbacks.onPairing) { this.callbacks.onPairing(msg); return; }
|
||||
if (typeof msg.id !== 'number' || !Number.isInteger(msg.id) || msg.id <= 0 || msg.id > 0xffffffff) throw new Error('Invalid file ID.');
|
||||
if (msg.type === 'start') {
|
||||
if (this.incoming || msg.id % 2 !== (this.initiator ? 0 : 1) || msg.id <= this.lastRemoteId) throw new Error('Unexpected file offer.');
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { MAX_ENVELOPE_LENGTH, openSignal, sealSignal, signalRole, type SignalRoute } from './reconnect.ts';
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
|
||||
// A minimal WebTorrent WebSocket tracker client: announce, offers routed by the
|
||||
// tracker to registered peers, and answers addressed with to_peer_id. It never
|
||||
// carries file data. Identifiers are 20-character binary strings, as on the wire.
|
||||
const ID_LENGTH = 20;
|
||||
const MAX_FRAME = MAX_ENVELOPE_LENGTH + 4096;
|
||||
// Re-announce while waiting so the swarm count stays current; trackers drop
|
||||
// peers whose socket closes, so this is not needed to stay registered.
|
||||
const KEEPALIVE = 15_000;
|
||||
export const randomId = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(ID_LENGTH)));
|
||||
const isId = (value: unknown): value is string => typeof value === 'string' && value.length === ID_LENGTH && !/[^\x00-\xff]/.test(value);
|
||||
|
||||
export interface TrackerSignal { peerId: string; offerId: string; sdp: string }
|
||||
export interface TrackerEvents {
|
||||
// Other peers currently announced in this swarm.
|
||||
onPeers(count: number): void;
|
||||
onOffer(signal: TrackerSignal): void;
|
||||
onAnswer(signal: TrackerSignal): void;
|
||||
onError(error: Error): void;
|
||||
}
|
||||
export type SocketFactory = (url: string) => WebSocket;
|
||||
|
||||
export class TrackerClient {
|
||||
readonly peerId = randomId();
|
||||
private socket: WebSocket | null = null;
|
||||
private timer?: ReturnType<typeof setTimeout>;
|
||||
private closed = false;
|
||||
private readonly url: string;
|
||||
private readonly infoHash: string;
|
||||
private readonly events: TrackerEvents;
|
||||
private readonly connectSocket: SocketFactory;
|
||||
constructor(url: string, infoHash: string, events: TrackerEvents, connectSocket: SocketFactory = url => new WebSocket(url)) {
|
||||
if (!isId(infoHash)) throw new Error('Invalid tracker swarm.');
|
||||
this.url = url; this.infoHash = infoHash; this.events = events; this.connectSocket = connectSocket;
|
||||
}
|
||||
connect() {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let socket: WebSocket;
|
||||
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; }
|
||||
this.socket = socket;
|
||||
const timeout = setTimeout(() => { reject(new Error('The tracker did not respond.')); this.close(); }, 15_000);
|
||||
socket.onopen = () => { clearTimeout(timeout); this.announce('started'); resolve(); };
|
||||
socket.onclose = () => {
|
||||
clearTimeout(timeout);
|
||||
if (this.closed) return;
|
||||
const error = new Error('Could not reach the tracker, or it closed the connection.');
|
||||
reject(error); this.fail(error);
|
||||
};
|
||||
socket.onmessage = event => this.receive(event.data);
|
||||
});
|
||||
}
|
||||
announce(event?: 'started' | 'stopped', offers: { offerId: string; sdp: string }[] = []) {
|
||||
this.send({
|
||||
...(event ? { event } : {}), numwant: offers.length, uploaded: 0, downloaded: 0, left: 1,
|
||||
...(event === 'stopped' ? {} : { offers: offers.map(item => ({ offer_id: item.offerId, offer: { type: 'offer', sdp: item.sdp } })) }),
|
||||
});
|
||||
clearTimeout(this.timer);
|
||||
if (!this.closed) this.timer = setTimeout(() => this.announce(), KEEPALIVE);
|
||||
}
|
||||
answer(to: string, offerId: string, sdp: string) {
|
||||
if (!isId(to) || !isId(offerId)) throw new Error('Invalid tracker route.');
|
||||
this.send({ to_peer_id: to, offer_id: offerId, answer: { type: 'answer', sdp }, uploaded: 0, downloaded: 0, left: 1 });
|
||||
}
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer);
|
||||
const socket = this.socket;
|
||||
if (!socket) return;
|
||||
socket.onopen = socket.onclose = socket.onmessage = null;
|
||||
try { if (socket.readyState === WebSocket.OPEN) this.send({ event: 'stopped', numwant: 0, uploaded: 0, downloaded: 0, left: 1 }, true); } catch { /* best effort */ }
|
||||
socket.close();
|
||||
}
|
||||
private send(data: object, closing = false) {
|
||||
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 }));
|
||||
}
|
||||
private fail(error: Error) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.events.onError(error);
|
||||
}
|
||||
private receive(raw: unknown) {
|
||||
if (this.closed) return;
|
||||
let data: unknown;
|
||||
try {
|
||||
if (typeof raw !== 'string' || raw.length > MAX_FRAME) throw new Error();
|
||||
data = JSON.parse(raw);
|
||||
} catch { this.fail(new Error('The tracker sent an invalid message.')); return; }
|
||||
if (!isRecord(data)) { this.fail(new Error('The tracker sent an invalid message.')); return; }
|
||||
if (typeof data['failure reason'] === 'string') { this.fail(new Error(`The tracker refused the request: ${data['failure reason'].slice(0, 200)}`)); return; }
|
||||
// Scrapes and other swarms on a shared socket are not ours to handle.
|
||||
if (data.action !== 'announce' || data.info_hash !== this.infoHash) return;
|
||||
const { complete, incomplete } = data;
|
||||
if (Number.isSafeInteger(complete) && Number.isSafeInteger(incomplete)) this.events.onPeers(Math.max(0, (complete as number) + (incomplete as number) - 1));
|
||||
if (!isId(data.peer_id) || data.peer_id === this.peerId || !isId(data.offer_id)) return;
|
||||
const signal = (value: unknown, type: string) => isRecord(value) && value.type === type && typeof value.sdp === 'string' ? value.sdp : null;
|
||||
const offer = signal(data.offer, 'offer'), answer = signal(data.answer, 'answer');
|
||||
if (offer !== null) this.events.onOffer({ peerId: data.peer_id, offerId: data.offer_id, sdp: offer });
|
||||
else if (answer !== null) this.events.onAnswer({ peerId: data.peer_id, offerId: data.offer_id, sdp: answer });
|
||||
}
|
||||
}
|
||||
|
||||
export interface AttemptHooks {
|
||||
// Each call replaces the previous local peer connection.
|
||||
createOffer(): Promise<string>;
|
||||
createAnswer(offer: string): Promise<string>;
|
||||
acceptAnswer(answer: string): Promise<void>;
|
||||
onPeers(count: number): void;
|
||||
onError(error: Error): void;
|
||||
}
|
||||
export interface AttemptOptions {
|
||||
url: string; infoHash: string; key: CryptoKey;
|
||||
// The device with the lower public key offers; the other wakes it.
|
||||
initiator: boolean;
|
||||
hooks: AttemptHooks;
|
||||
connectSocket?: SocketFactory;
|
||||
}
|
||||
// Spacing and cap for offers or wakes, so a missing or misbehaving peer cannot
|
||||
// cause unbounded peer connections or tracker traffic.
|
||||
export const RETRY_INTERVAL = 15_000;
|
||||
export const MAX_SIGNALS = 12;
|
||||
const SEEN_LIMIT = 64;
|
||||
|
||||
// One reconnect attempt over one tracker. Whoever arrives second signals at
|
||||
// once: the initiator with an offer, the other device with a sealed wake that
|
||||
// prompts the initiator to offer. Envelopes that do not open are ignored, since
|
||||
// other clients may share a swarm.
|
||||
export class ReconnectAttempt {
|
||||
private readonly tracker: TrackerClient;
|
||||
private readonly options: AttemptOptions;
|
||||
private offerId = '';
|
||||
private lastSignal = 0;
|
||||
private signals = 0;
|
||||
private working = false;
|
||||
private answered = false;
|
||||
private closed = false;
|
||||
private readonly seen = new Set<string>();
|
||||
constructor(options: AttemptOptions) {
|
||||
this.options = options;
|
||||
this.tracker = new TrackerClient(options.url, options.infoHash, {
|
||||
onPeers: count => { if (!this.closed) { options.hooks.onPeers(count); if (count > 0) void this.signal(); } },
|
||||
onOffer: signal => void this.receiveOffer(signal),
|
||||
onAnswer: signal => void this.receiveAnswer(signal),
|
||||
onError: error => this.fail(error),
|
||||
}, options.connectSocket);
|
||||
}
|
||||
start() { return this.tracker.connect(); }
|
||||
close() { this.closed = true; this.tracker.close(); }
|
||||
private fail(error: unknown) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.options.hooks.onError(asError(error));
|
||||
}
|
||||
private route(role: SignalRoute['role'], offerId: string, from: string, to = ''): SignalRoute {
|
||||
return { role, infoHash: this.options.infoHash, offerId, from, to };
|
||||
}
|
||||
private async signal(force = false) {
|
||||
// Signaling stops once an answer was sent or applied. If the responder's
|
||||
// answer is lost, the initiator is still unanswered and offers again.
|
||||
if (this.closed || this.working || this.answered) return;
|
||||
if (!force && Date.now() - this.lastSignal < RETRY_INTERVAL) return;
|
||||
if (this.signals >= MAX_SIGNALS) { this.fail(new Error('Your peer did not respond. Check that both people pressed Reconnect, or exchange codes manually.')); return; }
|
||||
this.signals++; this.working = true; this.lastSignal = Date.now();
|
||||
try {
|
||||
const { initiator, key } = this.options, offerId = randomId();
|
||||
const code = initiator ? await this.options.hooks.createOffer() : '';
|
||||
if (this.closed) return;
|
||||
const sdp = await sealSignal(key, this.route(initiator ? 'offer' : 'wake', offerId, this.tracker.peerId), code);
|
||||
if (this.closed) return;
|
||||
if (initiator) this.offerId = offerId;
|
||||
this.tracker.announce(undefined, [{ offerId, sdp }]);
|
||||
} catch (error) { this.fail(error); }
|
||||
finally { this.working = false; }
|
||||
}
|
||||
private fresh(offerId: string) {
|
||||
if (this.seen.has(offerId)) return false;
|
||||
if (this.seen.size >= SEEN_LIMIT) this.seen.delete(this.seen.values().next().value!);
|
||||
this.seen.add(offerId);
|
||||
return true;
|
||||
}
|
||||
private async receiveOffer({ peerId, offerId, sdp }: TrackerSignal) {
|
||||
const role = signalRole(sdp);
|
||||
if (this.closed || !this.fresh(offerId) || (role === 'wake') !== this.options.initiator || role === 'answer' || !role) return;
|
||||
let code: string;
|
||||
try { code = await openSignal(this.options.key, this.route(role, offerId, peerId), sdp); }
|
||||
catch { return; }
|
||||
if (this.closed) return;
|
||||
// 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 (this.working) return;
|
||||
this.working = true;
|
||||
try {
|
||||
const answer = await this.options.hooks.createAnswer(code);
|
||||
if (this.closed) return;
|
||||
const sealed = await sealSignal(this.options.key, this.route('answer', offerId, this.tracker.peerId, peerId), answer);
|
||||
if (this.closed) return;
|
||||
this.tracker.answer(peerId, offerId, sealed);
|
||||
this.answered = true;
|
||||
} catch (error) { this.fail(error); }
|
||||
finally { this.working = false; }
|
||||
}
|
||||
private async receiveAnswer({ peerId, offerId, sdp }: TrackerSignal) {
|
||||
if (this.closed || !this.options.initiator || !this.offerId || offerId !== this.offerId) return;
|
||||
let code: string;
|
||||
try { code = await openSignal(this.options.key, this.route('answer', offerId, peerId, this.tracker.peerId), sdp); }
|
||||
catch { return; }
|
||||
if (this.closed || offerId !== this.offerId) return;
|
||||
this.offerId = '';
|
||||
this.answered = true;
|
||||
try { await this.options.hooks.acceptAnswer(code); }
|
||||
catch (error) { this.fail(error); }
|
||||
}
|
||||
}
|
||||
@@ -330,6 +330,8 @@ summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
input[type=file] { max-width: 100%; font-size: 0.8rem; }
|
||||
input[type=file]::file-selector-button { border: 1px solid #505667; border-radius: 6px; padding: 0.45rem 0.65rem; margin-right: 0.6rem; background: #242a36; color: var(--text); cursor: pointer; }
|
||||
.session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
|
||||
.reconnect-setup { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; border-top: 1px solid var(--border); padding-top: var(--space-md); }
|
||||
.reconnect-setup .status { margin: 0; line-height: 1.6; }
|
||||
.session-actions button { font-size: 0.88rem; }
|
||||
.storage-error { color: #ffb4a9; background: #422725; border: 1px solid #8e5147; border-radius: 8px; padding: 1rem; font-size: 0.85rem; line-height: 1.6; }
|
||||
.mobile-bar { display: none; }
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { derivePairing, discoveryId, openSignal, parsePairing, pairingNonce, 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);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { ReconnectAttempt, TrackerClient, type AttemptHooks } from '../src/lib/tracker.ts';
|
||||
import { derivePairing, discoveryId, pairingNonce, signalingKey } from '../src/lib/reconnect.ts';
|
||||
|
||||
// An in-memory tracker with the routing of webtorrent/bittorrent-tracker:
|
||||
// counts include the announcing peer, offers go to other registered peers,
|
||||
// answers go to to_peer_id. Messages are delivered asynchronously.
|
||||
class FakeTracker {
|
||||
peers = new Map<string, FakeSocket>();
|
||||
frames: Record<string, unknown>[] = [];
|
||||
refuse = '';
|
||||
connect = (_url: string) => new FakeSocket(this) as unknown as WebSocket;
|
||||
handle(socket: FakeSocket, data: Record<string, unknown>) {
|
||||
this.frames.push(data);
|
||||
const reply = (target: FakeSocket, message: object) => target.deliver({ action: 'announce', info_hash: data.info_hash, ...message });
|
||||
if (this.refuse) { reply(socket, { 'failure reason': this.refuse }); return; }
|
||||
const peerId = data.peer_id as string;
|
||||
if (data.event === 'stopped') { this.peers.delete(peerId); return; }
|
||||
this.peers.set(peerId, socket);
|
||||
if (data.answer) {
|
||||
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 });
|
||||
return;
|
||||
}
|
||||
reply(socket, { interval: 120, complete: 0, incomplete: this.peers.size });
|
||||
const others = [...this.peers].filter(([id]) => id !== peerId).map(([, peer]) => peer);
|
||||
for (const [index, item] of ((data.offers ?? []) as { offer_id: string; offer: unknown }[]).entries()) {
|
||||
const target = others[index];
|
||||
if (target) reply(target, { peer_id: peerId, offer_id: item.offer_id, offer: item.offer });
|
||||
}
|
||||
}
|
||||
}
|
||||
class FakeSocket {
|
||||
readyState = 0;
|
||||
onopen: (() => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
onmessage: ((event: { data: string }) => void) | null = null;
|
||||
tracker: FakeTracker;
|
||||
constructor(tracker: FakeTracker) { this.tracker = tracker; setTimeout(() => { this.readyState = 1; this.onopen?.(); }); }
|
||||
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) }); }); }
|
||||
close() { this.readyState = 3; }
|
||||
}
|
||||
|
||||
async function pairing() {
|
||||
const key = await derivePairing({
|
||||
proposerNonce: pairingNonce(), acceptorNonce: pairingNonce(), proposerKey: '04' + 'a'.repeat(128), acceptorKey: '04' + 'b'.repeat(128),
|
||||
offerFingerprint: Array(32).fill('AA').join(' '), answerFingerprint: Array(32).fill('BB').join(' '), tracker: 'wss://tracker.test/',
|
||||
});
|
||||
return { infoHash: await discoveryId(key), key: await signalingKey(key) };
|
||||
}
|
||||
function peer(tracker: FakeTracker, shared: { infoHash: string; key: CryptoKey }, initiator: boolean) {
|
||||
const log = { offers: 0, answered: [] as string[], accepted: [] as string[], errors: [] as string[] };
|
||||
let done: () => void;
|
||||
const finished = new Promise<void>(resolve => { done = resolve; });
|
||||
const hooks: AttemptHooks = {
|
||||
createOffer: async () => `HC1.offer-${++log.offers}`,
|
||||
createAnswer: async offer => { log.answered.push(offer); return `HC1.answer-to-${offer}`; },
|
||||
acceptAnswer: async answer => { log.accepted.push(answer); done(); },
|
||||
onPeers: () => {},
|
||||
onError: error => { log.errors.push(error.message); done(); },
|
||||
};
|
||||
const attempt = new ReconnectAttempt({ url: 'wss://tracker.test/', ...shared, initiator, hooks, connectSocket: tracker.connect });
|
||||
return { attempt, log, finished };
|
||||
}
|
||||
const settle = () => new Promise(resolve => setTimeout(resolve, 20));
|
||||
|
||||
for (const initiatorFirst of [true, false]) {
|
||||
test(`peers connect when the ${initiatorFirst ? 'initiator' : 'responder'} arrives first`, async () => {
|
||||
const tracker = new FakeTracker(), shared = await pairing();
|
||||
const initiator = peer(tracker, shared, true), responder = peer(tracker, shared, false);
|
||||
const [first, second] = initiatorFirst ? [initiator, responder] : [responder, initiator];
|
||||
await first.attempt.start(); await settle();
|
||||
await second.attempt.start();
|
||||
await initiator.finished;
|
||||
assert.equal(initiator.log.offers, 1, 'One offer without waiting for a retry');
|
||||
assert.deepEqual(responder.log.answered, ['HC1.offer-1']);
|
||||
assert.deepEqual(initiator.log.accepted, ['HC1.answer-to-HC1.offer-1']);
|
||||
// Routing data only: no codes in clear on the tracker.
|
||||
assert.ok(tracker.frames.every(frame => !JSON.stringify(frame).includes('HC1.')));
|
||||
initiator.attempt.close(); responder.attempt.close();
|
||||
await settle();
|
||||
assert.equal(tracker.peers.size, 0, 'Both peers send stopped on close');
|
||||
});
|
||||
}
|
||||
|
||||
test('a client with another key in the swarm is ignored', async () => {
|
||||
const tracker = new FakeTracker(), shared = await pairing(), other = await pairing();
|
||||
const stranger = peer(tracker, { ...other, infoHash: shared.infoHash }, false);
|
||||
const initiator = peer(tracker, shared, true);
|
||||
await stranger.attempt.start(); 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 count alone does, and the stranger cannot open that offer.
|
||||
assert.equal(initiator.log.offers, 1);
|
||||
assert.deepEqual(stranger.log.answered, []);
|
||||
assert.deepEqual(initiator.log.errors, []);
|
||||
initiator.attempt.close(); stranger.attempt.close();
|
||||
});
|
||||
|
||||
test('tracker refusals and invalid frames end the attempt', async () => {
|
||||
const tracker = new FakeTracker(), shared = await pairing();
|
||||
tracker.refuse = 'swarm limit';
|
||||
const refused = peer(tracker, shared, true);
|
||||
await refused.attempt.start();
|
||||
await refused.finished;
|
||||
assert.match(refused.log.errors[0]!, /refused the request: swarm limit/);
|
||||
|
||||
const errors: string[] = [];
|
||||
let socket: FakeSocket | undefined;
|
||||
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);
|
||||
await client.connect();
|
||||
socket!.onmessage?.({ data: 'not json' });
|
||||
assert.deepEqual(errors, ['The tracker sent an invalid message.']);
|
||||
assert.throws(() => new TrackerClient('wss://tracker.test/', 'short', { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: () => {} }));
|
||||
});
|
||||
Reference in new issue
Block a user