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
@@ -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; }
|
||||
|
||||
Reference in new issue
Block a user