diff --git a/.env.example b/.env.example index aa65688..6eade96 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 59ce178..c3f595f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 6973102..6c76fa9 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/ux-roadmap.md b/docs/ux-roadmap.md index c5b9cbf..e7f0126 100644 --- a/docs/ux-roadmap.md +++ b/docs/ux-roadmap.md @@ -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 diff --git a/docs/webtorrent-reconnect.md b/docs/webtorrent-reconnect.md index 1a1f4f8..41021a4 100644 --- a/docs/webtorrent-reconnect.md +++ b/docs/webtorrent-reconnect.md @@ -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=` 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) diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index 8bcaa2a..428da25 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -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('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'); diff --git a/src/components/DeviceSettings.vue b/src/components/DeviceSettings.vue index 61d8f83..2fe389e 100644 --- a/src/components/DeviceSettings.vue +++ b/src/components/DeviceSettings.vue @@ -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({ 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 });