diff --git a/.env.example b/.env.example index 6eade96..ebd2621 100644 --- a/.env.example +++ b/.env.example @@ -4,5 +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. +# Optional: the Default tracker under Connection discovery, e.g. the local container. # VITE_TRACKER_URL=ws://localhost:8000 diff --git a/CHANGELOG.md b/CHANGELOG.md index c3f595f..267fe8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,10 +21,13 @@ - **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. +- Experimental tracker reconnect for paired devices. Choose a tracker under + **Network settings → Connection discovery**; during a verified session, one + person proposes it and the other confirms it. Setup reports success only + after both browsers saved it, and later sessions compare both copies so a + pairing missing on one side is turned off on the other. Afterwards 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). diff --git a/docs/webtorrent-reconnect.md b/docs/webtorrent-reconnect.md index 41021a4..4b1f46c 100644 --- a/docs/webtorrent-reconnect.md +++ b/docs/webtorrent-reconnect.md @@ -280,9 +280,24 @@ sealed envelopes), `src/lib/tracker.ts` (WebSocket adapter and attempt logic) an 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. + stores first, then the acceptor; each waits for its IndexedDB write, and the + acceptor acknowledges its completed write before the proposer reports success. + A failed write on either side is reported to both people, and the proposer + removes its stored copy again if the acceptor's write failed. 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. +- Every session that authenticates the paired device exchanges a 128-bit check + value derived from the stored pairing (or an empty value without one) over + the encrypted session. On a mismatch, the side holding a pairing turns it off + and says so. This repairs interrupted setups, and **Turn off reconnect** on + one device reaches the other at the next manual session. A match shows the + pairing as set up on both devices. +- **Connection discovery** in Network settings: Manual codes only, Default + tracker (only when `VITE_TRACKER_URL` is set) or Custom tracker. The choice is + a per-browser preference in `localStorage`, stays editable during a session, + and is resolved to a concrete URL when setup is proposed; existing pairings + keep their tracker. - 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. @@ -311,18 +326,19 @@ 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. +- Firefox and real separate-device networks, tracker outage and cross-tab + behavior (step 5), `connect-src` for the hosted CSP, and the deployment checks. +- Clock-skew detection and a frozen envelope encoding with published test vectors. + +Deliberately not planned for now: + +- Signaling v5. Pairing messages ride the v3 session protocol, so an outdated + peer rejects them; reloading the page updates it. +- Joining adjacent day identifiers around UTC midnight. If one person presses + Reconnect just before UTC midnight and the other just after, they miss each + other until the first presses Reconnect again. +- An interrupted setup is not atomic across two browsers; the check in the + next authenticated session removes a one-sided pairing. ## References diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index 428da25..52cc80d 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -600,16 +600,77 @@ 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); + const both = [identitySender, identityReceiver]; + // Setup itself never contacts the tracker, so these checks run without one. + assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('choose a tracker under Network settings'))); + await input(identitySender, '#discovery', 'custom'); + await wait(identitySender, () => !!document.querySelector('#tracker-url')); + await input(identitySender, '#tracker-url', trackerUrl || 'wss://tracker.example/'); + await wait(identitySender, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Set up reconnect')); + const hasPairing = (session: string) => evaluate(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Turn off reconnect')); + const failStorage = (session: string) => evaluate(session, () => { + const originalOpen = indexedDB.open; + indexedDB.open = () => { + indexedDB.open = originalOpen; + throw new DOMException('Simulated connection storage failure', 'SecurityError'); + }; + }); + // A failed IndexedDB write on either side is reported to both people, and + // the proposer, which stores first, removes its copy when the acceptor fails. + for (const failing of both) { + await failStorage(failing); + await click(identitySender, 'Set up reconnect'); + await wait(identityReceiver, () => document.body.textContent?.includes('proposes reconnecting through')); + await click(identityReceiver, 'Accept'); + for (const session of both) { + await wait(session, () => !!document.querySelector('.reconnect-setup .error')); + assert.equal(await evaluate(session, () => document.body.textContent?.includes('Reconnect is set up')), false); + } + for (const session of both) await wait(session, () => ![...document.querySelectorAll('button')].some(button => button.textContent === 'Turn off reconnect')); + } + console.log('PASS: failed reconnect storage on either side is reported to both peers, and the proposer rolls back its stored pairing.'); + + const setUpReconnect = async () => { 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')); + for (const session of both) await wait(session, () => document.body.textContent?.includes('Reconnect is set up on both devices')); + for (const session of both) assert.ok(await hasPairing(session)); + }; + const exchangeCodes = async () => { + await evaluate(identitySender, () => window.__hellcon.chooseFile(1024, 'manual.bin')); + await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code')); + await input(identityReceiver, '#offer-input', await evaluate(identitySender, () => window.__hellcon.element('#output-code').value)); + await click(identityReceiver, 'Accept & create answer'); + await wait(identityReceiver, () => !!document.querySelector('#output-code')); + await input(identitySender, '#answer-input', await evaluate(identityReceiver, () => window.__hellcon.element('#output-code').value)); + await click(identitySender, 'Connect'); + await wait(identityReceiver, () => !!document.querySelector('.incoming')); + await click(identityReceiver, 'Accept file'); + await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.')); + }; + const disconnectBoth = async () => { + await click(identitySender, 'Disconnect'); + await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reset')); + await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset'); + }; + await setUpReconnect(); + // Turning reconnect off on one device is noticed by the other during the + // next authenticated session, which then turns its own copy off as well. + await disconnectBoth(); + await click(identityReceiver, 'Turn off reconnect'); + await wait(identityReceiver, () => ![...document.querySelectorAll('button')].some(button => button.textContent === 'Turn off reconnect')); + assert.ok(await hasPairing(identitySender)); + await exchangeCodes(); + await wait(identitySender, () => document.body.textContent?.includes('no matching reconnect settings')); + await wait(identitySender, () => ![...document.querySelectorAll('button')].some(button => button.textContent === 'Turn off reconnect')); + console.log('PASS: confirmed reconnect setup; a pairing turned off on one device is removed from the other in the next authenticated session.'); + + if (trackerUrl) { + await setUpReconnect(); if (screenshotDirectory) await evaluate(identitySender, () => window.__hellcon.element('.reconnect-setup').scrollIntoView({ block: 'center' })); await screenshot(identitySender, 'reconnect-set-up'); await click(identitySender, 'Disconnect'); @@ -630,6 +691,7 @@ try { await screenshot(identitySender, 'reconnect-waiting'); await click(identityReceiver, 'Reconnect'); for (const session of both) await wait(session, () => document.body.textContent?.includes('Paired device authenticated')); + for (const session of both) await wait(session, () => document.body.textContent?.includes('is set up on both devices')); 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); diff --git a/src/App.vue b/src/App.vue index 14faf8a..fd09152 100644 --- a/src/App.vue +++ b/src/App.vue @@ -3,6 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'; import ConnectionWorkspace from './components/ConnectionWorkspace.vue'; import AppDialog from './components/AppDialog.vue'; import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts'; +import type { ReconnectPairing } from './lib/reconnect.ts'; import { asError } from './lib/validation.ts'; const logoUrl = `${import.meta.env.BASE_URL}HellNet_alt.png`; @@ -104,6 +105,28 @@ function update(id: string, change: ConnectionUpdate) { } finally { pending--; if (!pending && refreshRequested) void refresh(); } }); } +// Pairing setup needs the committed write, rather than the optimistic update +// used by ordinary settings, before either browser reports success. null +// removes a pairing the peer could not store or does not share. +function saveReconnect(id: string, reconnect: ReconnectPairing | null): Promise { + if (!persistent) { + if (reconnect) return Promise.reject(new Error('Reconnect needs saved connection storage in this browser.')); + update(id, { reconnect }); return Promise.resolve(); + } + pending++; + const operation = writes.then(async () => { + try { + const records = await saveConnection(id, { reconnect }); + if (pending === 1) applyRecords(records); + updates?.postMessage('changed'); + } catch (err) { + refreshRequested = true; + throw err; + } finally { pending--; if (!pending && refreshRequested) void refresh(); } + }); + writes = operation.catch(() => {}); + return operation; +} // Connection setup re-reads the record so trust forgotten in another tab is // never reused from this tab's copy. A failed read stops setup. async function trust(id: string) { @@ -190,7 +213,7 @@ async function remove() { diff --git a/src/components/ConnectionWorkspace.vue b/src/components/ConnectionWorkspace.vue index 1982f40..b0b3434 100644 --- a/src/components/ConnectionWorkspace.vue +++ b/src/components/ConnectionWorkspace.vue @@ -2,7 +2,8 @@ import { ref } from 'vue'; import TransferPanel from './TransferPanel.vue'; import type { SavedConnection, ConnectionUpdate } from '../lib/connections.ts'; -const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise }>(); +import type { ReconnectPairing } from '../lib/reconnect.ts'; +const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise; saveReconnect: (id: string, reconnect: ReconnectPairing | null) => Promise }>(); const emit = defineEmits<{ status: [id: string, state: 'ready' | 'connecting' | 'connected']; update: [id: string, change: ConnectionUpdate]; @@ -28,7 +29,7 @@ function navigate(next: 'send' | 'receive') { - diff --git a/src/components/NetworkSettings.vue b/src/components/NetworkSettings.vue index 365c151..617e2c1 100644 --- a/src/components/NetworkSettings.vue +++ b/src/components/NetworkSettings.vue @@ -1,9 +1,13 @@ +
+ Connection discovery + + + +

A WebTorrent tracker lets paired devices find each other, so both people press Reconnect instead of exchanging codes. Its operator sees your IP addresses and when your devices meet, not your codes or files. This applies to new reconnect setups; existing ones keep their tracker.

+
diff --git a/src/components/TransferPanel.vue b/src/components/TransferPanel.vue index 3125660..d03753b 100644 --- a/src/components/TransferPanel.vue +++ b/src/components/TransferPanel.vue @@ -2,7 +2,7 @@ import { asError } from '../lib/validation.ts'; import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts'; import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts'; -import { computed, onBeforeUnmount, ref, watch } from 'vue'; +import { computed, onActivated, onBeforeUnmount, ref, watch } from 'vue'; import DeviceSettings from './DeviceSettings.vue'; import { hello, signIdentity, verifyIdentity, type IdentityState, type IdentityHello, type IdentityContext } from '../lib/identity.ts'; import NetworkSettings from './NetworkSettings.vue'; @@ -13,7 +13,7 @@ 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 { derivePairing, discoveryId, discoveryTracker, loadDiscovery, pairingCheck, pairingNonce, parseCheck, parseNonce, saveDiscovery, signalingKey, trackerUrl, type ReconnectPairing } from '../lib/reconnect.ts'; import { ReconnectAttempt } from '../lib/tracker.ts'; import type { Identity } from '../lib/identity.ts'; @@ -37,7 +37,7 @@ interface Session { timer?: ReturnType; } -const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise }>(); +const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise; saveReconnect: (reconnect: ReconnectPairing | null) => Promise }>(); const devices = ref | null>(null); const identityStatus = ref(''); // Offered on the verification step whenever the verified peer would change @@ -82,6 +82,12 @@ const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || ''; const defaultStun = import.meta.env.VITE_STUN_URL || ''; const settings = ref({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' }); const managedCredentials = ref(null); +// Shared by all connections in this browser; reloaded when a cached workspace +// returns, since another connection may have changed it. +const defaultTracker = import.meta.env.VITE_TRACKER_URL || ''; +const discovery = ref(loadDiscovery(defaultTracker)); +watch(discovery, saveDiscovery, { deep: true }); +onActivated(() => { discovery.value = loadDiscovery(defaultTracker); }); // Every size is received the same way: streamed to Downloads where supported, otherwise // through the native save picker, otherwise buffered in memory (capped) and saved on completion. const receiveMethod = computed(() => { @@ -99,9 +105,16 @@ 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 pairingState = ref<'' | 'proposed' | 'incoming' | 'accepted' | 'saving' | 'awaiting-stored' | 'done'>(''), pairingError = ref(''); +// Set when the peer's stored pairing matched this one during this session. +const pairingConfirmed = ref(false); +const incomingTracker = ref(''); +let pairingSetup: { tracker: string; proposer: string; acceptor?: string; key?: CryptoKey; stored?: boolean } | null = null; +const pairingBusy = () => ['proposed', 'accepted', 'saving', 'awaiting-stored'].includes(pairingState.value); +const selectedTracker = computed(() => { + try { return { url: discoveryTracker(discovery.value, defaultTracker), error: '' }; } + catch (err) { return { url: '', error: asError(err).message }; } +}); 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 | undefined; @@ -140,7 +153,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; + authenticatedPeer.value = ''; pairingState.value = ''; pairingError.value = ''; pairingSetup = null; pairingConfirmed.value = false; managedCredentials.value = null; settings.value.allowTurn = false; if (!old) return; clearTimeout(old.timer); @@ -222,6 +235,7 @@ function attach(session: Session, channel: RTCDataChannel) { 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.'; + if (authenticatedPeer.value) void sendPairingCheck(session); } // Files chosen before connecting join the queue once the session is ready, // so a replaced reconnect peer never takes them along. @@ -518,16 +532,38 @@ function derivePairingKey(session: Session, setup: { tracker: string; proposer: 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 } }); +async function storePairing(session: Session, setup: NonNullable, key: CryptoKey) { + await props.saveReconnect({ version: 1, trackers: [setup.tracker], key, localKey: session.localHello!.key, peerKey: session.remoteHello!.key }); + setup.stored = true; +} +// Each authenticated session compares stored pairings, so an interrupted setup, +// a failed write or Turn off reconnect on one side is noticed on the other. +async function sendPairingCheck(session: Session) { + const pairing = props.connection.reconnect; + try { + const value = pairing && pairing.peerKey === authenticatedPeer.value ? await pairingCheck(pairing.key) : ''; + if (active === session) session.transfer?.sendPairing({ step: 'check', value }); + } catch { /* the session ended */ } +} +async function receivePairingCheck(session: Session, value: string) { + const pairing = props.connection.reconnect; + if (!pairing || !authenticatedPeer.value || pairing.peerKey !== authenticatedPeer.value) return; + const matches = value === await pairingCheck(pairing.key); + if (active !== session || pairingBusy() || props.connection.reconnect !== pairing) return; + if (matches) { pairingConfirmed.value = true; return; } + await props.saveReconnect(null); + if (active === session) pairingError.value = 'Your peer’s device has no matching reconnect settings, so reconnect was turned off here as well. Set it up again to use it.'; } // 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. +// is stored or contacted. Both contribute a nonce; the proposer stores first, +// and the acceptor's write is acknowledged before either reports success. If +// the peer's write fails, the proposer removes its own copy again. function proposePairing() { const session = active; - if (!session?.transfer || !canPair.value || pairingState.value === 'proposed' || pairingState.value === 'accepted') return; + if (!session?.transfer || !canPair.value || pairingBusy()) return; try { - pairingSetup = { tracker: trackerUrl(proposedTracker.value), proposer: pairingNonce() }; + if (!selectedTracker.value.url) throw new Error(selectedTracker.value.error || 'Choose a tracker under Network settings → Connection discovery.'); + pairingSetup = { tracker: selectedTracker.value.url, 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; } @@ -551,7 +587,7 @@ async function receivePairing(session: Session, message: Record 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 (pairingBusy()) 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.'); @@ -563,17 +599,43 @@ async function receivePairing(session: Session, message: Record setup.acceptor = parseNonce(message.nonce); const key = await derivePairingKey(session, setup, true); if (active !== session || pairingSetup !== setup) return; - storePairing(session, setup.tracker, key); + pairingState.value = 'saving'; + await storePairing(session, setup, key); + if (active !== session || pairingSetup !== setup) return; session.transfer?.sendPairing({ step: 'done' }); - pairingState.value = 'done'; + pairingState.value = 'awaiting-stored'; } 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.'; + const setup = pairingSetup; + const key = setup.key!; + pairingState.value = 'saving'; + await storePairing(session, setup, key); + if (active !== session || pairingSetup !== setup) return; + session.transfer?.sendPairing({ step: 'stored' }); + pairingState.value = 'done'; pairingConfirmed.value = true; + } else if (message.step === 'stored' && pairingState.value === 'awaiting-stored' && pairingSetup) { + pairingState.value = 'done'; pairingConfirmed.value = true; + } else if (message.step === 'error') { + // Without a setup in progress, this side already reported its own error. + const setup = pairingSetup; + if (!setup) return; pairingState.value = ''; pairingSetup = null; + pairingError.value = 'Your peer could not finish reconnect setup. Check their browser storage and try again.'; + if (setup.stored) { + try { await props.saveReconnect(null); } + catch (err) { pairingError.value = `Your peer could not finish reconnect setup, and turning it off here failed too: ${asError(err).message}`; } + } + } else if (message.step === 'decline') { + if (pairingBusy()) pairingError.value = 'Your peer declined tracker reconnect.'; + pairingState.value = ''; pairingSetup = null; + } else if (message.step === 'check') { + await receivePairingCheck(session, parseCheck(message.value)); } else throw new Error('Unexpected reconnect setup message.'); - } catch (err) { if (active === session) { pairingState.value = ''; pairingSetup = null; pairingError.value = asError(err).message; } } + } catch (err) { if (active === session) { + if (pairingSetup && message.step !== 'error') { + try { session.transfer?.sendPairing({ step: 'error' }); } catch { /* the session ended */ } + } + pairingState.value = ''; pairingSetup = null; pairingError.value = asError(err).message; + } } } async function acceptFile() { const session = active, destination = receiveMethod.value; @@ -641,7 +703,7 @@ onBeforeUnmount(() => { stopAttempt(); dispose(); revokeDownload(); clearTimeout
Network settings - +
+

Saving reconnect settings…

+

Waiting for your peer to save reconnect settings…

Waiting for your peer to confirm…

-

Reconnect is set up. Next time, both people open {{ connection.name }} and press Reconnect.

+

Reconnect is set up on both devices. Next time, both people open {{ connection.name }} and press Reconnect.

diff --git a/src/lib/reconnect.ts b/src/lib/reconnect.ts index 1863c39..9600896 100644 --- a/src/lib/reconnect.ts +++ b/src/lib/reconnect.ts @@ -111,6 +111,41 @@ export async function openSignal(key: CryptoKey, route: SignalRoute, text: unkno return data.code; } +// Compared over each authenticated session, so a pairing stored or turned off +// on only one side is noticed. It travels only inside the encrypted session. +export async function pairingCheck(key: CryptoKey) { + return hex(new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: label('check') }, key, 128))); +} +export function parseCheck(value: unknown) { + if (value === '') return value; + unhex(value, 16); + return value as string; +} + +// Connection discovery: a per-browser preference for new reconnect setups. +// Existing pairings keep the tracker they were set up with. +export type DiscoveryChoice = 'manual' | 'default' | 'custom'; +export interface DiscoverySettings { choice: DiscoveryChoice; custom: string } +const DISCOVERY_STORAGE = 'hellcon-discovery'; +export function loadDiscovery(defaultTracker: string): DiscoverySettings { + const fallback: DiscoverySettings = { choice: defaultTracker ? 'default' : 'manual', custom: '' }; + try { + const data: unknown = JSON.parse(localStorage.getItem(DISCOVERY_STORAGE) ?? 'null'); + if (!isRecord(data) || !['manual', 'default', 'custom'].includes(data.choice as string) || typeof data.custom !== 'string') return fallback; + const choice = data.choice === 'default' && !defaultTracker ? 'manual' : data.choice as DiscoveryChoice; + return { choice, custom: data.custom.slice(0, 1024) }; + } catch { return fallback; } +} +export function saveDiscovery(settings: DiscoverySettings) { + try { localStorage.setItem(DISCOVERY_STORAGE, JSON.stringify({ choice: settings.choice, custom: settings.custom })); } + catch { /* the preference lasts for this page */ } +} +// The concrete tracker a new pairing would use, or '' for manual codes. +export function discoveryTracker(settings: DiscoverySettings, defaultTracker: string) { + if (settings.choice === 'manual') return ''; + return trackerUrl(settings.choice === 'default' ? defaultTracker : settings.custom); +} + // 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; diff --git a/tests/reconnect.test.ts b/tests/reconnect.test.ts index 197d13d..8060378 100644 --- a/tests/reconnect.test.ts +++ b/tests/reconnect.test.ts @@ -1,6 +1,6 @@ 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 { derivePairing, discoveryId, discoveryTracker, loadDiscovery, openSignal, pairingCheck, parseCheck, parsePairing, pairingNonce, saveDiscovery, sealSignal, signalingKey, signalRole, trackerUrl, CLOCK_TOLERANCE, SIGNAL_LIFETIME, type PairingContext, type SignalRoute } from '../src/lib/reconnect.ts'; import { emptyConnection, updateConnection } from '../src/lib/connections.ts'; const fingerprint = (byte: string) => Array(32).fill(byte).join(' '); @@ -85,3 +85,35 @@ test('stored pairings are dropped when the paired device changes', async () => { assert.equal(parsePairing({ ...pairing, trackers: ['http://x'] }, peerKey), null); assert.equal(parsePairing({ ...pairing, key: 'secret' }, peerKey), null); }); + +test('pairing checks match only for the same pairing', async () => { + const [first, second] = await Promise.all([derivePairing(context), derivePairing({ ...context })]); + const check = await pairingCheck(first); + assert.match(check, /^[0-9a-f]{32}$/); + assert.equal(await pairingCheck(second), check); + assert.notEqual(await pairingCheck(await derivePairing({ ...context, acceptorNonce: pairingNonce() })), check); + assert.equal(parseCheck(check), check); + assert.equal(parseCheck(''), ''); + for (const bad of ['zz'.repeat(16), 'ab', 42, null]) assert.throws(() => parseCheck(bad)); +}); + +test('discovery preferences resolve to one concrete tracker', () => { + const values = new Map(); + const storage = { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } }; + Object.defineProperty(globalThis, 'localStorage', { value: storage, configurable: true }); + try { + assert.deepEqual(loadDiscovery(''), { choice: 'manual', custom: '' }); + assert.deepEqual(loadDiscovery('wss://default.example'), { choice: 'default', custom: '' }); + saveDiscovery({ choice: 'custom', custom: 'wss://mine.example/announce' }); + const custom = loadDiscovery('wss://default.example'); + assert.equal(discoveryTracker(custom, 'wss://default.example'), 'wss://mine.example/announce'); + // A fork without a default tracker never resolves a stored Default choice. + saveDiscovery({ choice: 'default', custom: '' }); + assert.equal(loadDiscovery('').choice, 'manual'); + assert.equal(discoveryTracker(loadDiscovery('wss://default.example'), 'wss://default.example'), 'wss://default.example/'); + assert.equal(discoveryTracker({ choice: 'manual', custom: 'wss://ignored.example' }, ''), ''); + assert.throws(() => discoveryTracker({ choice: 'custom', custom: 'http://insecure.example' }, '')); + values.set('hellcon-discovery', '{broken'); + assert.equal(loadDiscovery('').choice, 'manual'); + } finally { Reflect.deleteProperty(globalThis, 'localStorage'); } +});