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

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

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

349 lines
20 KiB
Markdown

# 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,
using a small client adapter built on native browser APIs. Deploy an existing
tracker implementation; do not add Trystero or the WebTorrent file-transfer
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. 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
tracker and must not depend on a particular operator or on HellCon-specific
server extensions. Vue remains the only runtime dependency.
## User experience and scope
A paired connection gets a **Reconnect** button. Both people open that connection
and press Reconnect; the app negotiates a new WebRTC connection and authenticates
the remembered device. Both pages must be open. Files still require acceptance.
Manual code exchange remains available for initial pairing and recovery.
Network settings gain an independent **Connection discovery** section:
- **Manual codes**, **Default tracker**, or **Custom tracker**.
- Custom tracker: one `wss://` URL, including any required path.
- The default URL comes from `VITE_TRACKER_URL`; if unset, offer Manual and Custom.
- Show the selected host and explain that it can observe which clients meet.
- Leave STUN selection and explicit TURN consent as separate controls.
- The selection applies to new pairings; existing pairings keep their stored
trackers.
There is no public peer directory, background presence, offline wake-up, file
storage, torrent file generation, DHT, or BitTorrent piece transfer. The tracker
only handles discovery and signaling. Reconnecting establishes a new session;
it does not resume an interrupted file transfer.
The first release contacts one agreed tracker per pairing, but pairings store
and negotiate an ordered tracker list so fallback trackers can be added later
without a storage migration or pairing protocol change. Contacting several
trackers and automatic fallback between operators are deferred. Selecting an
endpoint is not authorization to contact additional public trackers.
## Pairing and persistence
After mutual device verification on a manual connection, both users can enable
**Reconnect using this tracker**. This opt-in is separate from remembering a
device and starts unticked. The manual session's offerer proposes the selected
tracker URL; the recipient sees and confirms it before the app stores or
contacts it.
Add a versioned pairing exchange to the authenticated data channel. Both peers
contribute 32 random bytes. Derive a shared HKDF-SHA-256 base key from the ordered
contributions and a context binding both device keys and connection fingerprints.
Use an unambiguous, versioned encoding and separate derivation labels for each
purpose. Store the base key as a non-extractable CryptoKey.
The connection record stores the paired key, the local identity public key used
for pairing, the shared key, the agreed ordered list of concrete tracker URLs (one
entry in the first release), and the reconnect
protocol version. Resolve Default to a concrete URL at pairing time: changing a
build default must not silently move existing pairings to another operator.
Both peers acknowledge the pairing settings over the verified channel before
showing reconnect as configured. An interrupted exchange or storage failure can
leave only one peer configured; show the failure and allow manual setup to repair
the pairing. Do not claim atomic persistence across two browsers.
Forget device, Remove connection, identity deletion/replacement, or replacement
of the paired device invalidates reconnect credentials. Re-read identity and
pairing state before each attempt and propagate local revocation across tabs.
Clearing browser storage loses pairing. A non-extractable key remains usable by
trusted application code; it does not protect against a compromised app host.
Changing a pairing's tracker requires coordination. While connected, propose and
confirm the replacement over the authenticated channel. If the old tracker is
unavailable, exchange manual codes to agree on a replacement. A local edit alone
cannot inform an offline peer.
## Client architecture
Keep `src/lib/webrtc.ts`, device proofs, and the existing file session as the
transport and authentication foundation. Separate setup lifecycle code from
`TransferPanel.vue` so manual and tracker setup can feed the same session without
duplicating verification, cancellation, TURN consent, or transfer behavior.
Introduce focused modules for pairing storage/derivation, encrypted signaling,
and the WebSocket tracker adapter. The adapter handles tracker announcements,
offer routing, answers, retries, and cleanup. It never receives file contents.
Use native `WebSocket`, `RTCPeerConnection`, and Web Crypto. Basic WebTorrent
tracker signaling requires no Nostr-style Schnorr signature library. Preserve
HellCon's P-256 identity proofs; tracker peer IDs are routing identifiers only.
Server-side dependencies are maintained separately from the browser bundle.
Keep the encrypted signaling exchange independent of the WebSocket transport.
The [peer mesh idea](ux-roadmap.md#later-peer-mesh-exploratory-unscheduled) may
later let an open, verified peer forward the same sealed exchange over a data
channel, leaving the tracker as a fallback. That idea is unscheduled and not part
of this plan.
## Discovery and encrypted signaling
Derive a 20-byte discovery identifier from the pairing secret with a dedicated
HKDF label and UTC day. Use it as the tracker's `info_hash`; it identifies a
private pairing, not a file. Derive a separate AES-256-GCM signaling key with a
different label. Near UTC midnight, temporarily join adjacent day identifiers,
deduplicate attempts, and close the unused route. Estimate clock skew from the
`Date` header of a same-origin response where available, and report skew beyond
the expiry tolerance.
Randomize the 20-byte tracker `peer_id` per reconnect attempt and keep it stable
only for that attempt. The peer that finds the other already registered sends
the offer: announce responses report swarm counts, so the second arrival can
gather a fresh offer immediately. If both offer at once, the offer from the
lower paired device public key wins and the other peer discards its own. Reject
equal identities for this automatic role scheme and leave manual setup available.
Use the WebSocket tracker's normal `announce`, `offers`, `offer_id`, `answer`,
and `to_peer_id` fields. Encode 20-byte identifiers as the protocol's binary
strings inside JSON, not hex strings. Use constant placeholder transfer counters
where needed; never expose actual filenames or transferred byte counts.
Carry a versioned encrypted HellCon envelope in the offer/answer `sdp` string,
following the opaque-payload approach used by Trystero. The decrypted envelope
contains the complete HellCon identity-enabled code. Only decrypted and validated
SDP reaches `setRemoteDescription`. This is a HellCon signaling convention over
a tracker protocol, not interoperability with ordinary torrent clients or with
Trystero rooms.
Each envelope uses a fresh random 96-bit AES-GCM IV. Authenticate the protocol
version, discovery identifier, offer ID, message role, source peer ID, and answer
destination in unambiguously encoded associated data. Include attempt nonces and
an expiry inside the ciphertext; answers must bind the outstanding offer nonce.
Fix the allowed clock skew together with the encoding.
Freeze the exact encoding and publish test vectors before implementation ships.
Track outstanding offers and bounded duplicate caches. Ignore exact retransmits,
reject mismatched answers, and never reuse an offer from a disposed peer
connection. Expiry and duplicate checks reduce replay; they do not guarantee
that a captured offer is undeliverable after browser reload. Fresh device proofs
bound to both session nonces and fingerprints remain mandatory before releasing
file metadata. Invalid or changed identity ends automatic reconnect; switching
to manual verification requires a deliberate new manual setup.
## Connection lifecycle and failure handling
Trackers forward offers only to peers already registered; registration alone
does not guarantee delivery. The first arrival registers without offers and
keeps its registration alive at the tracker interval; the second arrival offers.
If a tracker reports no usable counts, fall back to bounded periodic offers and
gather a fresh offer for each one: never resend an offer whose candidates may
have expired. Configure our tracker for interactive discovery. Respect custom
tracker pacing and show a waiting state rather than assuming immediate matching.
Limit each slot to one reconnect attempt per browser profile with a Web Locks
(`navigator.locks`) lock; propagate revocation through the existing
`BroadcastChannel`. Bound in-flight negotiations, frame sizes, peer counts and
retry state. Multiple tabs or a third party must not cause unbounded peer
allocation. Do not assume the tracker enforces two clients per room.
Trackers deliver each offer to a random registered peer, so a third peer in the
swarm can receive an offer meant for the paired device and stall the attempt.
Send at most one offer per counted peer, up to a small cap, and report this as
a failed attempt, not an authentication failure; it denies service but cannot
authenticate as the paired device.
Use a five-minute total attempt deadline and retain the existing ICE gathering
limit. Validate incoming frames before decrypting or creating peers. Handle
tracker rejection, malformed data, socket loss, an absent peer, stale answers,
and authentication failure with specific errors and a manual-code recovery path.
After mutual authentication, stop announcing, send a best-effort stopped event,
and close the tracker socket. Cancel, timeout and Reset also dispose timers,
sockets and pending WebRTC peers. Tracker loss after setup does not interrupt
an established transfer. A later reconnect creates fresh signaling state.
## Compatibility and rollout
Plan signaling v5 for identity-enabled sessions to negotiate the pairing exchange
and bind that version into device proofs. Temporary manual v3 sessions remain
available. Existing paired v4 slots retain their trusted device key but require
one new manual session on compatible builds to enable tracker reconnect.
Use an IndexedDB schema migration without dropping names, history or trust.
Clearing reconnect settings must not delete unrelated connection history.
Document version mismatch errors and make the tracker mode's capabilities
explicit; an older HellCon client must not silently skip authentication.
## Self-hosting and custom endpoints
Run a pinned release of `webtorrent/bittorrent-tracker` with WebSocket support in
a dedicated container behind the existing HTTPS reverse proxy. Expose a single
`wss://` endpoint; disable UDP/HTTP tracker APIs and public statistics. Keep the
backend port private. Build the image from a pinned package version and
lockfile; the tracker never enters HellCon's `package.json`. Run it from Compose
for local development, as with coturn, and set explicit CPU/memory, connection,
frame-size and request-rate limits in the deployment configuration.
The reverse proxy alone provides no rate limiting. Where the pinned release lacks
per-IP limits, swarm caps or origin checks, the container runs a small start
script around the tracker library that adds them and trusts forwarded client
addresses only from the proxy. These are operator protections: the client must
not depend on them, and custom trackers without them must still work.
Configure short announcement intervals and cleanup of stale peers and empty
swarms. Bound the total number of swarms as well as peers per swarm. Disable
payload/debug logging and identifying access logs on the tracker path. Health
checks and aggregate metrics must not expose pairing identifiers or IPs.
Origin checks can restrict normal browser use but cannot authenticate arbitrary
clients or prevent deliberate abuse.
For Custom, require a valid `wss://` URL without embedded credentials or a fragment;
allow `ws://` loopback only in local development. Do not implement arbitrary
tracker-specific login schemes in the first release. Unsupported authentication
or payload policies produce a clear error.
To support arbitrary user-selected secure WebSocket endpoints, the hosted build
will need `connect-src 'self' wss:` in place of its current self-only policy.
This deliberately trades a narrower exfiltration boundary for client
independence; document the broader network permission. Self-hosters may retain
an explicit
host allowlist; the UI must explain when their CSP blocks a custom endpoint.
Public tracker compatibility is a release gate, not a blanket promise. Verify
encrypted offer forwarding, identifier encoding, payload limits, announcement
timing and usage policy against the selected implementation. Record the tested
server version and configuration. No public tracker is bundled without a policy
and availability review.
## Privacy limits
The tracker sees connecting IPs, Origin, discovery identifiers, temporary peer
IDs, routing fields, timing and ciphertext sizes. It can associate the clients
it matches. Other clients may also observe or probe discovery identifiers if a
tracker exposes them. An unguessable identifier helps against guessing; the
pairing secret and device proofs protect access even if that identifier leaks.
Rotating identifiers removes a stable protocol label but does not prevent IP or
timing correlation. No-log configuration reduces retained data; it cannot stop
a malicious operator recording traffic. Self-hosting changes who observes this
metadata. Direct WebRTC traffic also exposes endpoints to network observers.
The feature provides convenient encrypted signaling, not anonymity.
## Implementation steps and acceptance checks
1. Prove interoperability with a pinned tracker: two native WebSocket clients
exchange bounded opaque offer/answer payloads in both arrival orders. Confirm
that announce responses count WebSocket peers and that a maximum-size code
fits the frame limit after encryption and encoding. Resolve tracker
restrictions before building the UI.
2. Add pairing negotiation, migration and revocation; test matching derivations,
domain separation, day boundaries, interrupted pairing and storage failures.
3. Add encrypted envelopes and the adapter; test tampering, replay, duplicate
routing, stale answers, third peers, retry bounds and complete cancellation.
4. Integrate discovery settings and Reconnect with the existing setup lifecycle.
Pair two browsers manually, reload both, reconnect without copying codes,
authenticate the saved peer and transfer exact bytes in both directions.
5. Verify Chromium/Firefox combinations, real separate-device networks, explicit
TURN use, tracker outage, endpoint changes, clock skew, cross-tab attempts,
forgotten devices and manual fallback. Local success alone is insufficient.
6. Validate the deployment's TLS, CSP, rate/resource limits, cleanup, log behavior
and upgrade procedure. Update user documentation only when the feature ships.
Maintenance centers on the pinned tracker and its dependencies, browser/network
behavior, and the small HellCon adapter. Keep a reproducible local tracker fixture
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; 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.
The decrypted code passes the usual `decodeCode` checks, and the peer's
identity key must equal the paired key; fresh device proofs then authenticate
the session as before.
- Roles differ from the plan above: the lower device key always offers and
creates the data channel, so there is no glare. If the other device arrives
second, it announces a sealed, codeless **wake** that makes the initiator
offer at once. Swarm counts from announce responses (which include the
announcing peer) trigger the same. Offers and wakes are spaced 15 seconds apart
and capped at 12; each offer uses a fresh peer connection. Envelopes that do
not open are ignored, so other clients in a swarm cannot disturb it beyond
receiving offers they cannot read.
- One attempt per slot and browser profile via Web Locks, a five-minute
deadline, a 15-second keepalive announce, `stopped` and socket close on
success, cancel, reset, failure and unmount.
Checked on 2026-10-20 with `node scripts/browser-check.ts --tracker=<url>` against
`wss://tracker.openwebtorrent.com` and `wss://tracker.webtorrent.dev`: pairing
setup, reload of both pages, Reconnect without codes, device proofs and exact
bytes in both directions, both roles. Both trackers report swarm counts, route
binary 20-byte identifiers unchanged and remove peers on `stopped`.
tracker.openwebtorrent.com relayed 56 KB payloads, tracker.webtorrent.dev 12 KB;
typical sealed codes are a few KB. Neither tracker is bundled.
Still open before this can ship:
- 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
- [WebTorrent tracker server and client](https://github.com/webtorrent/bittorrent-tracker)
- [WebSocket request parsing](https://github.com/webtorrent/bittorrent-tracker/blob/master/lib/server/parse-websocket.js)
- [Trystero tracker adapter, for protocol reference](https://github.com/dmotz/trystero/blob/main/packages/torrent/src/index.ts)
- [Existing device authentication](device-identities.md)