Compare commits

...
4 Commits
Author SHA1 Message Date
Schluffe 9f3f21884f Release 0.0.6 with reconnect fixes and regression coverage 2026-10-21 00:39:08 +02:00
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
SchluffeandClaude Opus 5.5 3659956967 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>
2026-10-20 20:51:05 +02:00
SchluffeandClaude Opus 5.5 a5935a8324 Remove shareable invitation links
Codes are exchanged by copy and paste again. The URL fragment intake,
the invitation dialog, the BroadcastChannel answer relay and the Share
link / Copy link controls are gone, along with their tests, browser
check scenarios and design doc. Code fields no longer accept links.

The compressed HC1 codes with typed offers/answers and echoed refs stay.
An optional signaling backend is the intended way to simplify the
exchange instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:47:07 +02:00
31 changed files with 1502 additions and 648 deletions

No files matched your search

+2
View File
@@ -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: the Default tracker under Connection discovery, e.g. the local container.
# VITE_TRACKER_URL=ws://localhost:8000
+37 -10
View File
@@ -1,6 +1,32 @@
# Changelog
## [0.0.5] - Draft (unreleased)
## [0.0.6] - 2026-10-21
### Fixed
- Cancelling tracker reconnect now settles the pending WebSocket connection
immediately and clears its timeout. Socket send failures are reported cleanly.
- Late answers cannot reach a replacement WebRTC connection while its new offer
is gathering.
- Unauthenticated tracker messages cannot suppress valid offers or evict entries
from the replay cache.
- Rapidly accepting a reconnect proposal twice no longer starts competing key
derivations or leaves setup with an unexpected-message error.
- Tracker integration tests run in a fresh container on every invocation instead
of reusing Docker's cached test results.
### Added
- Regression coverage for tracker cancellation and failures, stale answers,
replay handling, retry limits, pairing verification, repeated acceptance and
reconnect lock handoff between browser tabs.
### Changed
- Document experimental tracker reconnect setup, privacy, revocation and limits
in the README.
## [0.0.5] - Development draft
### Added
@@ -21,13 +47,14 @@
- **Disconnect**, which aborts unfinished writes, and Send/Receive navigation
within a live session. The initial receiver can send files without
reconnecting.
- Shareable invitation links. Codes travel in the URL fragment, which is never
sent to the host and is removed from the address bar on opening. An offer
link opens a preview that suggests an idle connection (the one paired with
the sender's device first) and fills in the code without answering. An answer
link opened in the same browser connects the waiting sender tab; elsewhere it
shows the answer to copy. **Share link** uses the Web Share API where
available; **Copy link** and the bare code always remain.
- 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).
### Changed
@@ -38,8 +65,8 @@
Base64url of deflated JSON). Each code states whether it is an offer or an
answer and carries a reference shared by both, so a pasted offer in the
answer field, or an answer to a different code, is rejected with a clear
message while the live offer stays valid. Codes may be pasted as part of a
link. Codes from earlier 0.0.5 drafts are rejected.
message while the live offer stays valid. Codes from earlier 0.0.5 drafts are
rejected.
- Replace the receive-storage choice with a single **Accept file** button that
treats every file size the same: stream to Downloads where supported, else
use the native save picker, else buffer up to 64 MiB in memory and hand it
+44 -28
View File
@@ -1,11 +1,12 @@
# HellCon
Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release
Current version: **0.0.6**. See the [changelog](CHANGELOG.md) for release
notes and compatibility changes.
Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts, no
signaling backend, and no server-side file storage: you exchange invitation links
or connection codes yourself, through any messenger. Connections are direct by
Browser-to-browser file sharing with Vue 3 and WebRTC. There are no accounts or
server-side file storage. Exchange connection codes through a messenger, or
opt in to experimental tracker reconnect for remembered devices. Manual codes
need no signaling backend. Connections are direct by
default. A TURN relay is used only when both people opt in.
This is experimental software, not independently audited or battle-tested.
@@ -27,9 +28,9 @@ has its own setup and live session.
Switching connections keeps active transfers and selected files alive while the
tab stays open. Closing or reloading the page ends live sessions and discards
selected files; reconnect with fresh codes. On small screens, **Show
connections** opens the sidebar, and the bar beside it shows the open connection
and its status.
selected files; reconnect with fresh codes or a saved tracker pairing. On small
screens, **Show connections** opens the sidebar, and the bar beside it shows the
open connection and its status.
Names and remembered devices are saved in this browser. Transfer history, file
contents, connection codes, and relay credentials are not. Clearing site data
@@ -40,16 +41,12 @@ so and temporary sessions still work.
1. **Create a code.** The person starting picks one or more files, chooses a
STUN provider (PageQuit by default, Google, Cloudflare, custom, or None), and
clicks **Create code**. They send the link privately to the receiver through
an authenticated channel, with **Share link** where supported or **Copy
link**. The bare code is under **Show code instead**.
2. **Answer it.** The receiver opens the link or pastes the link or code. An
opened link shows a preview and lets them pick which connection receives it;
nothing is sent until they click **Accept & create answer**. They send the
answer link back. Opened in the browser that holds the sender's tab, it
connects that tab directly; elsewhere it shows the answer for the sender to
paste. Gathering waits up to 30 seconds and fails rather than exporting
incomplete connection information.
clicks **Create code**. They send the code privately to the receiver through
an authenticated channel.
2. **Answer it.** The receiver pastes the code and clicks **Accept & create
answer**, then sends the answer back for the sender to paste. Gathering waits
up to 30 seconds and fails rather than exporting incomplete connection
information.
3. **Compare fingerprints.** Both people compare **both full SHA-256 certificate
fingerprints** over a channel they trust for authenticity, such as in person.
Your fingerprint must equal their “Their fingerprint”, and vice versa. Compare
@@ -139,9 +136,31 @@ remembering. Public identities in codes can link sessions. Browser-stored keys
are usable by any code the host serves, so they do not protect against a
malicious host. See [the identity protocol and storage](docs/device-identities.md).
### Experimental reconnect without codes
Once both browsers have remembered each other in a verified session:
1. Under **Network settings → Connection discovery**, choose a custom `wss://`
WebTorrent tracker, or the host's default if one is configured.
2. Click **Set up reconnect**. The other person checks the tracker host and
accepts. Both browsers must save the settings before setup reports success.
3. After disconnecting or reloading, both people open their saved connection and
press **Reconnect**. Fresh device proofs authenticate the session; each file
still requires acceptance. TURN still requires both people to opt in.
The tracker sees IP addresses, timing and encrypted signaling sizes; codes and
files remain private from it. The pairing key stays in browser storage. Changing
Connection discovery applies to new setups; existing pairings keep their tracker.
**Turn off reconnect** removes the local pairing. The other browser removes its
copy at the next authenticated manual session if the pairings no longer match.
If reconnect fails, exchange fresh codes. Reconnect attempts started on opposite
sides of UTC midnight need restarting. See the [implementation status and
limits](docs/webtorrent-reconnect.md#concept-status).
## Privacy and security
### Codes and links
### Connection codes
Connection codes are **compressed and Base64url-encoded, not encrypted** (`HC1.`
followed by deflated JSON). They contain SDP: candidate addresses, temporary ICE
@@ -150,13 +169,6 @@ messaging service, may learn these details. Treat codes as private and do not
publish them. The browser may obscure local addresses, but this app does not
provide anonymity.
Invitation links carry the code after `#`. Browsers do not send this fragment to
the host, and the app removes it from the address bar on opening. Otherwise a
link is as sensitive as its code; browser history, including synced history, may
keep it. Opening an offer link never answers automatically. Answer links reach
the waiting tab over a same-origin `BroadcastChannel`. See [the invitation
design](docs/invitations.md).
File transfers use protocol **v3**; codes from older builds are rejected before
connecting.
@@ -228,7 +240,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
@@ -256,6 +270,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
@@ -336,8 +351,9 @@ bun run tracker:down
```
See [the tracker README](tracker/README.md) for configuration and VPS use.
Automatic reconnect in the browser is still
[planned](docs/webtorrent-reconnect.md); the app uses manual codes.
The browser supports opt-in [experimental tracker reconnect](#experimental-reconnect-without-codes).
For a local integration check, run `bun run test:browser --tracker=ws://127.0.0.1:8000`
after building the app and starting the tracker.
## Roadmap
-128
View File
@@ -1,128 +0,0 @@
# Shareable invitations
Phase 4 of the [UX roadmap](ux-roadmap.md). The sender shares a link instead of
a pasted code; the receiver opens it, previews it and creates an answer, which
returns as a link as well. Pasteable codes remain the universal fallback. No
server, storage service or new dependency is involved; Vue remains the only
runtime dependency.
## Why the fragment
The code travels after `#`. Browsers never send the fragment in HTTP requests or
`Referer` headers, so the app host, its service worker, proxies and network
observers do not receive it. Over HTTPS, an observer sees the hostname and IP
addresses only, as today.
Everyone the link is shared with sees it: the recipient, the messenger and, for
messengers without end-to-end encryption, their servers. That is the same
exposure as a pasted code. Browser history, including synced history, may keep
the full URL even after the app clears it; this is the one addition compared with
pasting. Codes are not secrets and stop working when the session ends, but they
contain IP addresses. Fingerprint comparison and device proofs, not code secrecy,
prevent a leaked or substituted code from being used for interception.
## Code format
Measured in headless Chromium (2 host candidates, 1 with STUN): current codes are
1.0–1.5 KB; deflated and base64url-encoded they are 650–780 characters, including
a v4 identity. More interfaces and TURN candidates grow both; a code stays well
below 2 KB in typical cases.
One encoding serves codes and links: a versioned prefix followed by base64url of
`deflate-raw`-compressed JSON (native `CompressionStream`). The JSON keeps the
existing session versions (3 temporary, 4 with identity) and adds:
- `type`: `offer` or `answer`. Pasting an offer into the answer field, or the
reverse, fails with a clear message instead of an SDP error.
- `ref`: 16 random bytes chosen by the offerer and echoed by the answerer. An
answer for a different offer is rejected before it reaches the peer connection.
It also addresses answer links to the waiting tab (see below).
Decoding bounds the compressed input and stops decompression once the output
exceeds `MAX_SIGNAL_LENGTH`, so a small hostile link cannot expand without limit.
Decoding becomes asynchronous: parse once into a validated structure
(`type`, `ref`, `sdp`, `identity`) and pass that around instead of re-decoding
text in `TransferPanel`. 0.0.5 is unreleased and already incompatible with 0.0.4,
so no legacy encoding is accepted; a recognizable old code reports that both
people need the current version.
A link is the current app URL (from `location`, so any self-hosted path works)
with the code as its fragment. Every code field accepts either a bare code or a
full link and uses the part after `#`. A link from another HellCon host can be
pasted into one's own instance; opening it directly would use that host's
origin, without one's saved connections and identity.
## Receiving an invitation
`main.ts` reads the fragment before mounting, removes it with
`history.replaceState`, and hands it to the app; `hashchange` covers a link
pasted into an already open tab. Invalid fragments show an error and are
discarded the same way.
An offer opens an import dialog. It never creates an answer automatically,
because answering reveals the receiver's addresses to whoever made the link.
The dialog shows:
- that this is an invitation to receive files and that it only works while the
sender's page is waiting (setup times out after 5 minutes);
- the device status: no identity, a new device, or a key matching a slot's paired
device. A match is a suggestion; the fresh device proof still decides;
- whether the code contains a TURN relay, which requires the receiver's explicit
TURN opt-in as today;
- a slot selector: the matching paired slot if idle, otherwise the current slot
if idle, otherwise **New connection**. Busy slots are unavailable.
**Open** selects the slot, switches it to Receive, fills the code and focuses
**Accept & create answer**. Network settings and identity behave as for a pasted
code.
## Returning the answer
The answer is shared as a link too. Opened from a messenger it lands in a new tab,
but the sender's offer lives only in memory in the original tab. The new tab
posts `{ ref, code }` on a `BroadcastChannel`. A panel waiting in `offer-ready`
with that `ref` acknowledges and applies the answer as if Connect had been
pressed; fingerprint comparison or the device proof follows as usual. A second
delivery of the same answer is acknowledged as already used.
After an acknowledgement the new tab says the answer was delivered and the user
can switch back; pages cannot focus another tab. Without an acknowledgement
within about a second, for example in a messenger's in-app browser with separate
storage or in another browser, it shows the answer with **Copy** and explains
where to paste it. The channel is same-origin; other sites cannot post to it.
## Sharing UI
Where `navigator.share` accepts a URL, offer **Share link**; always offer
**Copy link**, with the bare code in a collapsed section. The privacy note says
that a link is as sensitive as a code, may remain in browser history, and should
be sent privately. Status texts name the 5-minute limit while waiting.
QR codes stay deferred. Measured sizes fit a QR code, but generating one needs a
hand-written encoder or a dependency, and scanning adds camera handling.
## Implementation steps and acceptance checks
Steps 1–5 and 7 are implemented (`src/lib/codes.ts`, `src/lib/invitations.ts`,
`InvitationDialog.vue`, and the invitation flow in `scripts/browser-check.ts`,
which opens the fallback on a second origin instead of a separate browser
context). Step 6 still needs manual verification.
1. Codec module with Node tests: round trips for both types and versions, bare
code vs. link, whitespace, invalid base64url, oversized input, decompression
bomb, wrong `type`, `ref` mismatch, old-format detection.
2. Switch signaling to the parsed structure; keep existing webrtc/session tests
green and add `ref` validation in `useAnswer`.
3. Fragment intake, import dialog and slot selection through `App` →
`ConnectionWorkspace` → `TransferPanel`.
4. Answer relay and fallback; Share/Copy link UI.
5. Browser check: offer link in a second page shows the dialog and a clean URL;
accepting it and opening the answer link in a third page connects the sender's
tab; exact bytes transfer. Repeat the answer link in a separate browser context
for the fallback. Run axe on the dialog.
6. Manually verify on phones with at least two messengers: link length intact,
preview fetches without the fragment, in-app browser behaviour, Web Share.
7. Update README, CHANGELOG and the roadmap.
The shorter encoding also reduces the payload the planned
[tracker reconnect](webtorrent-reconnect.md) carries.
+10 -16
View File
@@ -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
@@ -86,23 +86,17 @@ storage denial/recovery, and protocol-version validation. Design and review note
are in [the device identity protocol](device-identities.md); this is not an
independent cryptographic audit.
## 4. Shareable invitations — implemented
## 4. Compressed connection codes — implemented
Detailed in [the invitation design](invitations.md).
Offers and answers are shared as links with the compressed code in the URL
fragment, through **Share link** where supported or **Copy link**; the bare code
stays available. Opening a link clears the fragment. An offer opens an import
preview with slot selection and never answers automatically. An answer link
reaches the waiting sender tab in the same browser over `BroadcastChannel` and
otherwise falls back to copy and paste. An answer exchange remains necessary.
Still open: manual checks of link length, previews and in-app browsers across
real messengers and phones. QR codes remain deferred.
Offers and answers are compressed `HC1.` codes that state their type and share a
reference, so mixed-up or stale codes are rejected with a specific message.
Shareable invitation links were built on top and removed again: they did not make
real-world connections more reliable. An optional signaling backend is the
intended way to simplify the exchange.
## 5. Guided connection flow
Present one primary next action across Choose files → Share invitation → Connect
Present one primary next action across Choose files → Share code → Connect
→ Verify → Transfer. Collapse completed setup steps, expose advanced network
settings on demand, and keep relay consent explicit. Show session state separately
from file progress. Distinguish connected, awaiting acceptance, saving, completed,
+73 -2
View File
@@ -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,76 @@ 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; 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)
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "hellcon",
"private": true,
"version": "0.0.5",
"version": "0.0.6",
"license": "MIT",
"type": "module",
"scripts": {
@@ -11,7 +11,7 @@
"turn:down": "docker compose --env-file .env.development down",
"tracker:up": "docker compose -f compose.tracker.yaml up -d --build --wait",
"tracker:down": "docker compose -f compose.tracker.yaml down",
"test:tracker": "docker build --target test -t hellcon-tracker:test tracker",
"test:tracker": "docker build --target test -t hellcon-tracker:test tracker && docker run --rm hellcon-tracker:test",
"test:turn": "node scripts/browser-check.ts --turn",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
+123 -98
View File
@@ -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-'));
@@ -49,7 +51,6 @@ interface ProtocolResults {
'Browser.setDownloadBehavior': object;
'Target.createTarget': { targetId: string };
'Target.attachToTarget': { sessionId: string };
'Target.closeTarget': object;
'Runtime.enable': object;
'Page.enable': object;
'Page.navigate': object;
@@ -100,11 +101,9 @@ async function wait(session: string, check: () => unknown) {
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
}
const targets = new Map<string, string>();
async function page(url = origin) {
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
targets.set(sessionId, targetId);
await call('Runtime.enable', {}, sessionId);
await call('Page.enable', {}, sessionId);
// Background tabs otherwise skip focus/blur events, which the name editor relies on.
@@ -117,8 +116,7 @@ async function page(url = origin) {
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
await call('Page.navigate', { url }, sessionId);
for (let n = 0; n < 100; n++) {
// The app removes invitation fragments from the address bar.
try { if (await evaluate(sessionId, (expected: string) => location.href.startsWith(expected) && document.readyState === 'complete', url.split('#')[0]!)) break; }
try { if (await evaluate(sessionId, (expected: string) => location.href.startsWith(expected) && document.readyState === 'complete', url)) break; }
catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; }
await new Promise(resolve => setTimeout(resolve, 20));
}
@@ -143,7 +141,6 @@ const screenshot = async (session: string, name: string) => {
const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session);
await writeFile(join(screenshotDirectory, name + '.png'), Buffer.from(data, 'base64'));
};
const closePage = (session: string) => call('Target.closeTarget', { targetId: targets.get(session) });
const dialogText = (session: string) => evaluate(session, () => document.querySelector('dialog[open]')?.textContent ?? '');
const click = (session: string, label: string) => evaluate(session, (label: string) => window.__hellcon.click(label), label);
const input = (session: string, selector: string, value: string) => evaluate(session, (selector: string, value: string) => window.__hellcon.input(selector, value), selector, value);
@@ -151,30 +148,12 @@ const enableTurn = (session: string) => evaluate(session, () => {
const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input');
if (!checkbox.checked) checkbox.click();
});
let checkedCodeLayout = false;
async function connect(sender: string, receiver: string, size: number, changedIdentity = false) {
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
await input(sender, '#stun-provider', provider);
await input(receiver, '#stun-provider', provider);
if (turn) { await enableTurn(sender); await enableTurn(receiver); }
await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code'));
if (!checkedCodeLayout) {
const layout = await evaluate(sender, () => {
const details = window.__hellcon.element<HTMLDetailsElement>('.code-details');
const closedByDefault = !details.open;
details.open = true;
const code = window.__hellcon.element<HTMLTextAreaElement>('#output-code').getBoundingClientRect();
const copy = window.__hellcon.element<HTMLButtonElement>('.code-entry button').getBoundingClientRect();
const answer = window.__hellcon.element<HTMLTextAreaElement>('#answer-input').getBoundingClientRect();
const connect = window.__hellcon.element<HTMLButtonElement>('#answer-input + button').getBoundingClientRect();
details.open = false;
return { closedByDefault, codeGap: copy.top - code.bottom, answerGap: connect.top - answer.bottom, codeWidth: code.width, answerWidth: answer.width };
});
assert.equal(layout.closedByDefault, true, 'Code alternative starts collapsed');
assert.ok(Math.abs(layout.codeGap - layout.answerGap) < 1, 'Code and answer buttons have matching spacing');
assert.ok(Math.abs(layout.codeWidth - layout.answerWidth) < 1, 'Code and answer fields have matching width');
checkedCodeLayout = true;
}
const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.ok(offer.startsWith(CODE_PREFIX));
await input(receiver, '#offer-input', 'invalid-code!');
@@ -564,62 +543,6 @@ try {
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
if (!turn) {
// Invitation links: the offer opens a dialog in a fresh page, the answer link
// reaches the sender's tab, and other origins fall back to copy and paste.
const inviter = await page();
await evaluate(inviter, () => window.__hellcon.chooseFile(3000, 'invited.bin'));
await input(inviter, '#stun-provider', provider);
await click(inviter, 'Create code'); await wait(inviter, () => !!document.querySelector('#output-link'));
const offerLink = await evaluate(inviter, () => window.__hellcon.element<HTMLInputElement>('#output-link').value);
const offerCode = await evaluate(inviter, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.equal(offerLink, `${origin}/#${offerCode}`);
const invited = await page(offerLink);
await wait(invited, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files'));
assert.equal(await evaluate(invited, () => location.href), `${origin}/`);
assert.match(await dialogText(invited), /temporary identity/);
await checkAccessibility(invited, 'Invitation dialog');
if (screenshotDirectory) await evaluate(inviter, () => window.__hellcon.element('#output-link').scrollIntoView({ block: 'center' }));
await screenshot(inviter, 'invitation-share');
await screenshot(invited, 'invitation-offer');
await call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, invited);
assert.equal(await evaluate(invited, () => document.documentElement.scrollWidth <= innerWidth), true, 'Invitation dialog must not overflow horizontally');
await screenshot(invited, 'invitation-offer-mobile');
await click(invited, 'Open'); await wait(invited, () => !document.querySelector('dialog[open]'));
await wait(invited, () => document.activeElement?.textContent === 'Accept & create answer');
assert.equal(await evaluate(invited, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').value), offerCode);
assert.equal(await evaluate(invited, () => window.__hellcon.element('.tabs button[aria-pressed=true]').textContent), 'Receive');
await input(invited, '#stun-provider', provider);
await click(invited, 'Accept & create answer'); await wait(invited, () => !!document.querySelector('#output-link'));
const answerLink = await evaluate(invited, () => window.__hellcon.element<HTMLInputElement>('#output-link').value);
const answerCode = await evaluate(invited, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
const elsewhere = await page(answerLink.replace('127.0.0.1', 'localhost'));
await wait(elsewhere, () => document.querySelector('dialog[open]')?.textContent?.includes('Paste this answer in the sender’s tab'));
assert.equal(await evaluate(elsewhere, () => window.__hellcon.element<HTMLTextAreaElement>('#invitation-answer').value), answerCode);
await checkAccessibility(elsewhere, 'Answer fallback dialog');
await screenshot(elsewhere, 'invitation-answer-fallback');
assert.equal(await evaluate(inviter, () => !!document.querySelector('.fingerprint')), false);
const relay = await page(answerLink);
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Answer delivered'));
await wait(inviter, () => !!document.querySelector('.fingerprint'));
await evaluate(relay, (link: string) => { location.hash = link.split('#')[1]!; }, answerLink);
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Answer already used'));
assert.equal(await evaluate(relay, () => location.hash), '');
await click(relay, 'Close');
await evaluate(relay, () => { location.hash = 'HC1.not-a-code'; });
await wait(relay, () => document.querySelector('dialog[open]')?.textContent?.includes('Link could not be opened'));
await click(inviter, 'Both fingerprints match — confirm'); await click(invited, 'Both fingerprints match — confirm');
await wait(invited, () => !!document.querySelector('.incoming'));
await click(invited, 'Accept file');
await wait(inviter, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
const invitedBytes = await evaluate(invited, async () => {
const link = window.__hellcon.element<HTMLAnchorElement>('a.download');
const bytes = new Uint8Array(await (await fetch(link.href)).arrayBuffer());
return { name: link.download, length: bytes.length, valid: bytes.every(byte => byte === 123) };
});
assert.deepEqual(invitedBytes, { name: 'invited.bin', length: 3000, valid: true });
for (const session of [inviter, invited, elsewhere, relay]) await closePage(session);
console.log('PASS: offer links open a reviewed import with a clean URL; answer links connect the waiting tab once, fall back to copy and paste elsewhere, and transfer exact bytes.');
const identitySender = await page();
const receiverOrigin = origin.replace('127.0.0.1', 'localhost');
const identityReceiver = await page(receiverOrigin);
@@ -665,24 +588,6 @@ try {
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
const offer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
assert.ok((await decodeCode(offer)).identity);
// Another receiver tab whose current slot is a new one: the invitation still
// suggests the slot paired with the sender's device, and Open hands it there.
const invitedPaired = await page(receiverOrigin);
await click(invitedPaired, 'Add connection');
await wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2');
await evaluate(invitedPaired, (code: string) => { location.hash = code; }, offer);
await wait(invitedPaired, () => document.querySelector('dialog[open]')?.textContent?.includes('Invitation to receive files'));
assert.match(await dialogText(invitedPaired), /matches the paired device of Con 1/);
assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element<HTMLSelectElement>('#invitation-target').selectedOptions[0]?.textContent?.trim()), 'Con 1 · paired device');
await click(invitedPaired, 'Open'); await wait(invitedPaired, () => !document.querySelector('dialog[open]'));
assert.equal(await evaluate(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1');
assert.equal(await evaluate(invitedPaired, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').value), offer);
await evaluate(invitedPaired, () => [...document.querySelectorAll<HTMLElement>('.connection-name')].find(item => item.textContent === 'Con 2')?.click());
await wait(invitedPaired, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2');
await click(invitedPaired, 'Remove Con 2'); await click(invitedPaired, 'Remove connection');
await wait(invitedPaired, () => document.querySelectorAll('.connection-link').length === 1);
await closePage(invitedPaired);
console.log('PASS: an invitation from a paired device suggests its slot over the current one and hands the code to it.');
await input(identityReceiver, '#offer-input', offer); await click(identityReceiver, 'Accept & create answer');
await wait(identityReceiver, () => !!document.querySelector('#output-code'));
const answer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
@@ -695,6 +600,126 @@ 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.');
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');
// Two clicks can arrive before Vue rerenders the button. Consent must
// start only one key derivation and send only one acceptance.
await evaluate(identityReceiver, () => { window.__hellcon.click('Accept'); window.__hellcon.click('Accept'); });
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<HTMLTextAreaElement>('#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<HTMLTextAreaElement>('#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');
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));
}
const competing = await page();
await wait(competing, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reconnect' && !button.disabled));
await input(competing, '#stun-provider', 'none');
await click(identitySender, 'Reconnect');
await wait(identitySender, () => document.body.textContent?.includes('Waiting for your peer on'));
await click(competing, 'Reconnect');
await wait(competing, () => document.body.textContent?.includes('Another HellCon tab is already reconnecting'));
assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('Waiting for your peer on')));
await click(identitySender, 'Cancel connection');
await click(competing, 'Reset'); await click(competing, 'Reconnect');
await wait(competing, () => document.body.textContent?.includes('Waiting for your peer on'));
await click(competing, 'Cancel connection');
await click(identitySender, 'Reconnect');
await wait(identitySender, () => document.body.textContent?.includes('Waiting for your peer on'));
console.log('PASS: another tab cannot reconnect the same slot; cancellation releases the lock for either tab to retry.');
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'));
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);
await wait(to, () => !!document.querySelector('.incoming button.primary'));
await click(to, 'Accept file');
await wait(to, () => !!document.querySelector('a.download'));
await wait(from, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
const bytes = await evaluate(to, async () => { const link = window.__hellcon.element<HTMLAnchorElement>('a.download'); const data = new Uint8Array(await (await fetch(link.href)).arrayBuffer()); return { length: data.length, valid: data.every(byte => byte === 123) }; });
assert.deepEqual(bytes, { length: size, valid: true });
}
console.log(`PASS: tracker reconnect through ${new URL(trackerUrl).host}: pairing setup with peer confirmation, reload, Reconnect on both pages without codes, device proofs, exact bytes in both directions.`);
}
await click(identitySender, 'Disconnect');
await wait(identityReceiver, () => !document.querySelector('.incoming'));
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
+27 -29
View File
@@ -2,14 +2,10 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
import AppDialog from './components/AppDialog.vue';
import InvitationDialog from './components/InvitationDialog.vue';
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts';
import { takeFragment } from './lib/invitations.ts';
import type { ReconnectPairing } from './lib/reconnect.ts';
import { asError } from './lib/validation.ts';
// A code from the link this page was opened with, already removed from the URL.
const props = defineProps<{ initialCode?: string }>();
const logoUrl = `${import.meta.env.BASE_URL}HellNet_alt.png`;
const giteaIconUrl = `${import.meta.env.BASE_URL}gitea.svg`;
const connections = ref<SavedConnection[]>([]), selected = ref('');
@@ -22,10 +18,6 @@ let renameContainer: HTMLElement | null = null;
const removalTarget = computed(() => connections.value.find(item => item.id === removalId.value));
const error = ref(''), removalError = ref('');
const heading = ref<HTMLElement | null>(null);
// An opened link awaiting review, and an accepted offer on its way to a slot.
const invitation = ref<{ code: string } | null>(null);
const handoff = ref<{ connection: string; code: string } | null>(null);
const canAdd = computed(() => !adding.value && !removing.value && connections.value.length < CONNECTION_LIMIT);
let persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
let updates: BroadcastChannel | undefined;
function select(id: string) {
@@ -81,15 +73,8 @@ onMounted(async () => {
updates.onmessage = () => { void refresh(); };
}
window.addEventListener('focus', refresh);
window.addEventListener('hashchange', openLink);
if (props.initialCode) invitation.value = { code: props.initialCode };
});
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); window.removeEventListener('hashchange', openLink); });
// A link opened in an existing tab only changes the fragment.
function openLink() {
const code = takeFragment();
if (code) invitation.value = { code };
}
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
async function add() {
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
adding.value = true;
@@ -97,18 +82,10 @@ async function add() {
await writes;
if (persistent) connections.value = await addConnection();
else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1));
const id = connections.value.at(-1)!.id;
select(id); updates?.postMessage('changed');
return id;
select(connections.value.at(-1)!.id); updates?.postMessage('changed');
} catch (err) { error.value = asError(err).message; }
finally { adding.value = false; }
}
async function openInvitation(target: string, code: string) {
const id = target === 'new' ? await add() : target;
if (!id || !connections.value.some(item => item.id === id)) return;
if ((states.value[id] ?? 'ready') !== 'ready') { error.value = 'That connection is in use. Open the link again and choose another connection.'; return; }
select(id); handoff.value = { connection: id, code };
}
function update(id: string, change: ConnectionUpdate) {
const index = connections.value.findIndex(item => item.id === id);
if (index < 0) return;
@@ -128,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<void> {
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) {
@@ -214,8 +213,8 @@ async function remove() {
<p v-if="error" class="storage-error" role="alert">{{ error }}</p>
<template v-for="item in connections" :key="item.id">
<KeepAlive>
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :invitation="handoff?.connection === item.id ? handoff : null"
@status="setStatus" @update="update" @invitation-taken="handoff = null" />
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :save-reconnect="saveReconnect"
@status="setStatus" @update="update" />
</KeepAlive>
</template>
<p v-if="!current" class="status">Opening your connections…</p>
@@ -231,5 +230,4 @@ async function remove() {
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
</template>
</AppDialog>
<InvitationDialog v-if="current" v-model="invitation" :connections="connections" :states="states" :current="current.id" :can-add="canAdd" @open="openInvitation" />
</template>
+4 -14
View File
@@ -1,12 +1,12 @@
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';
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<SavedConnection>; invitation?: { code: string } | null }>();
import type { ReconnectPairing } from '../lib/reconnect.ts';
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection>; saveReconnect: (id: string, reconnect: ReconnectPairing | null) => Promise<void> }>();
const emit = defineEmits<{
status: [id: string, state: 'ready' | 'connecting' | 'connected'];
update: [id: string, change: ConnectionUpdate];
invitationTaken: [];
}>();
const mode = ref<'send' | 'receive'>('send');
const sessionActive = ref(false), connected = ref(false);
@@ -17,16 +17,6 @@ function navigate(next: 'send' | 'receive') {
if (connected.value) { direction.value = next; panel.value?.focusDirection(next); }
else if (!sessionActive.value) mode.value = next;
}
// An accepted invitation switches an idle slot to Receive and fills the code;
// the user still creates the answer.
watch(() => props.invitation, async invitation => {
if (!invitation) return;
emit('invitationTaken');
if (sessionActive.value) return;
mode.value = 'receive';
await nextTick();
panel.value?.importCode(invitation.code);
}, { immediate: true });
</script>
<template>
@@ -39,7 +29,7 @@ watch(() => props.invitation, async invitation => {
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'send' }" :aria-pressed="(connected ? direction : mode) === 'send'" @click="navigate('send')">Send</button>
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'receive' }" :aria-pressed="(connected ? direction : mode) === 'receive'" @click="navigate('receive')">Receive</button>
</div>
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :connection="connection" :load-trust="() => loadTrust(connection.id)"
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" :connection="connection" :load-trust="() => loadTrust(connection.id)" :save-reconnect="reconnect => saveReconnect(connection.id, reconnect)"
@session-change="sessionActive = $event; status()" @connected-change="connected = $event; direction = mode; status()"
@update="emit('update', connection.id, $event)" />
</div>
+6 -1
View File
@@ -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>
-110
View File
@@ -1,110 +0,0 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import AppDialog from './AppDialog.vue';
import { decodeCode, type Signal } from '../lib/codes.ts';
import { deliverAnswer, type Delivery } from '../lib/invitations.ts';
import { hasRelay } from '../lib/webrtc.ts';
import { asError } from '../lib/validation.ts';
import type { SavedConnection } from '../lib/connections.ts';
// A link opened in this tab. Offers are previewed and handed to a chosen slot;
// they never create an answer here, because answering reveals this device's
// addresses to whoever made the link.
const invitation = defineModel<{ code: string } | null>({ required: true });
const props = defineProps<{ connections: SavedConnection[]; states: Record<string, 'ready' | 'connecting' | 'connected'>; current: string; canAdd: boolean }>();
const emit = defineEmits<{ open: [target: string, code: string] }>();
const signal = ref<Signal | null>(null), failure = ref('');
const delivery = ref<Delivery | 'pending' | 'manual'>('pending');
const target = ref(''), copied = ref(false), copyError = ref('');
const open = computed({ get: () => !!invitation.value, set: value => { if (!value) invitation.value = null; } });
const idle = (id: string) => (props.states[id] ?? 'ready') === 'ready';
const paired = computed(() => signal.value?.identity && props.connections.find(item => item.peerKey === signal.value!.identity!.key));
const relay = computed(() => !!signal.value && hasRelay(signal.value.sdp));
const available = computed(() => target.value === 'new' ? props.canAdd : !!target.value && idle(target.value));
const title = computed(() => failure.value ? 'Link could not be opened'
: !signal.value ? 'Opening link'
: signal.value.type === 'offer' ? 'Invitation to receive files'
: { pending: 'Delivering answer', delivered: 'Answer delivered', used: 'Answer already used', manual: 'Paste this answer in the sender’s tab' }[delivery.value]);
let token = 0;
// Prefer the slot paired with the sender's device, then the open slot, then a new one.
function suggest() {
const match = paired.value;
if (match && idle(match.id)) return match.id;
if (idle(props.current)) return props.current;
return props.canAdd ? 'new' : props.connections.find(item => idle(item.id))?.id ?? '';
}
watch(invitation, async value => {
const run = ++token;
signal.value = null; failure.value = ''; delivery.value = 'pending'; copied.value = false; copyError.value = '';
if (!value) return;
try {
// TURN consent is checked again when the slot uses the code.
const decoded = await decodeCode(value.code, { allowTurn: true });
if (run !== token) return;
signal.value = decoded;
if (decoded.type === 'offer') { target.value = suggest(); return; }
const result = await deliverAnswer(decoded.ref, value.code);
if (run === token) delivery.value = result ?? 'manual';
} catch (err) { if (run === token) failure.value = asError(err).message; }
}, { immediate: true });
function accept() {
if (!invitation.value || !available.value) return;
emit('open', target.value, invitation.value.code);
invitation.value = null;
}
async function copy() {
try { await navigator.clipboard.writeText(invitation.value?.code ?? ''); copied.value = true; copyError.value = ''; }
catch { copyError.value = 'Clipboard unavailable. Select and copy the answer manually.'; }
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement) event.target.select();
}
</script>
<template>
<AppDialog v-model="open" :title="title">
<template v-if="failure">
<p class="error" role="alert">{{ failure }}</p>
<p>Ask your peer for a new link or code.</p>
</template>
<p v-else-if="!signal">Reading the link…</p>
<template v-else-if="signal.type === 'offer'">
<p>Someone invited you to receive files. The invitation only works while the sender’s HellCon page stays open, for up to 5 minutes after they created it.</p>
<p v-if="!signal.identity">The sender uses a temporary identity. Compare fingerprints after connecting.</p>
<p v-else-if="paired">The sender’s device matches the paired device of {{ paired.name }}. Its fresh device proof is still checked when connecting.</p>
<p v-else>The sender’s device is not paired with any of your connections. Compare fingerprints after connecting.</p>
<p v-if="relay">This invitation uses a TURN relay. Enable TURN in Network settings before accepting it.</p>
<label class="step" for="invitation-target">Receive on</label>
<select id="invitation-target" v-model="target" class="stun-select">
<option v-for="item in connections" :key="item.id" :value="item.id" :disabled="!idle(item.id)">
{{ item.name }}{{ item.id === paired?.id ? ' · paired device' : '' }}{{ idle(item.id) ? '' : ' · in use' }}
</option>
<option value="new" :disabled="!canAdd">New connection</option>
</select>
<p v-if="!available" class="error">Choose a connection that is not in use.</p>
<p>Nothing is sent until you press <strong>Accept &amp; create answer</strong>. The answer contains your IP address.</p>
</template>
<template v-else>
<p v-if="delivery === 'pending'">Looking for the sender’s HellCon tab in this browser…</p>
<p v-else-if="delivery === 'delivered'">The sender’s HellCon tab received this answer. Switch back to it to finish connecting; you can close this tab.</p>
<p v-else-if="delivery === 'used'">The sender’s tab already used this answer. Switch back to it, or ask for a new answer if connecting failed.</p>
<template v-else>
<p>No HellCon tab in this browser is waiting for this answer. Copy it and paste it into the sender’s tab, for example in your usual browser if the link opened inside a messenger. It only works for up to 5 minutes after the code was created.</p>
<label class="step" for="invitation-answer">Answer</label>
<textarea id="invitation-answer" :value="invitation?.code" readonly @focus="selectCode" />
<p v-if="copyError" class="error" role="alert">{{ copyError }}</p>
</template>
</template>
<template #actions="{ close }">
<template v-if="signal?.type === 'offer'">
<button @click="close">Cancel</button>
<button class="primary" :disabled="!available" @click="accept">Open</button>
</template>
<template v-else-if="signal?.type === 'answer' && delivery === 'manual'">
<button @click="close">Close</button>
<button class="primary" @click="copy">{{ copied ? 'Copied!' : 'Copy answer' }}</button>
</template>
<button v-else @click="close">Close</button>
</template>
</AppDialog>
</template>
+16 -1
View File
@@ -1,9 +1,13 @@
<script setup lang="ts">
import type { IceOptions, NetworkSettings } from '../lib/webrtc.ts';
import { STUN_PROVIDERS } from '../lib/webrtc.ts';
import type { DiscoverySettings } from '../lib/reconnect.ts';
const settings = defineModel<NetworkSettings>({ required: true });
defineProps<{ disabled?: boolean; managedCredentials?: IceOptions | null }>();
// Discovery stays editable while connected: reconnect is set up over a live session.
const discovery = defineModel<DiscoverySettings>('discovery', { required: true });
defineProps<{ disabled?: boolean; managedCredentials?: IceOptions | null; defaultTracker: string }>();
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
const host = (url: string) => { try { return new URL(url).host; } catch { return url; } };
</script>
<template>
@@ -33,4 +37,15 @@ const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
</template>
</template>
</fieldset>
<fieldset class="network-settings">
<legend>Connection discovery</legend>
<label for="discovery">Find paired devices with</label>
<select id="discovery" v-model="discovery.choice" class="stun-select">
<option value="manual">Manual codes only</option>
<option v-if="defaultTracker" value="default">Default tracker ({{ host(defaultTracker) }})</option>
<option value="custom">Custom tracker…</option>
</select>
<input v-if="discovery.choice === 'custom'" id="tracker-url" v-model="discovery.custom" class="stun-input" aria-label="Custom tracker address" placeholder="wss://tracker.example" autocomplete="off" spellcheck="false" />
<p class="status">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.</p>
</fieldset>
</template>
+338 -79
View File
@@ -2,22 +2,27 @@
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, nextTick, 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';
import { acceptAnswer, createAnswer, createOffer, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { codeLink, createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.ts';
import { listenForAnswers } from '../lib/invitations.ts';
import { createRef, decodeCode, encodeCode, MAX_INPUT_LENGTH } from '../lib/codes.ts';
import { MEMORY_LIMIT, validateMetadata } from '../lib/transfer.ts';
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, 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';
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;
@@ -29,12 +34,10 @@ interface Session {
expected?: string;
// Shared by this session's offer and answer codes.
ref?: string;
// Stops accepting answer links from other tabs.
stopAnswers?: () => void;
timer?: ReturnType<typeof setTimeout>;
}
const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise<SavedConnection> }>();
const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise<SavedConnection>; saveReconnect: (reconnect: ReconnectPairing | null) => Promise<void> }>();
const devices = ref<InstanceType<typeof DeviceSettings> | null>(null);
const identityStatus = ref('');
// Offered on the verification step whenever the verified peer would change
@@ -53,7 +56,7 @@ const inputCode = ref('');
const outputCode = ref('');
const step = ref<Step>('idle');
const error = ref('');
const copied = ref<'' | 'link' | 'code'>('');
const copied = ref(false);
const fps = ref<Fingerprints | null>(null);
const verified = ref(false);
const progress = ref(0);
@@ -63,22 +66,13 @@ const downloadName = ref('');
const connected = ref(false);
const sendSection = ref<HTMLElement | null>(null);
const receiveSection = ref<HTMLElement | null>(null);
const acceptButton = ref<HTMLButtonElement | null>(null);
watch(connected, value => emit('connectedChange', value));
function focusDirection(direction: 'send' | 'receive') {
const section = direction === 'send' ? sendSection.value : receiveSection.value;
section?.focus({ preventScroll: true });
section?.scrollIntoView({ block: 'start', behavior: 'auto' });
}
// Fills an invitation's code without creating the answer, which would reveal
// this device's addresses before the user chose to.
function importCode(code: string) {
if (busy.value || connected.value || props.sending) return;
if (step.value !== 'idle') reset();
inputCode.value = code;
void nextTick(() => acceptButton.value?.focus());
}
defineExpose({ focusDirection, importCode });
defineExpose({ focusDirection });
const choosing = ref(false);
const dragover = ref(false);
@@ -88,9 +82,12 @@ const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
const defaultStun = import.meta.env.VITE_STUN_URL || '';
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
const managedCredentials = ref<IceOptions | null>(null);
// Links keep this page's own path and query, so any self-hosted location works.
const outputLink = computed(() => outputCode.value ? codeLink(outputCode.value, location.href) : '');
const canShare = typeof navigator.share === 'function' && (navigator.canShare?.({ url: location.href }) ?? true);
// 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(() => {
@@ -101,14 +98,34 @@ 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' | '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<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 the link privately, then paste the answer or open the answer link in this browser.',
'answer-ready': 'Send the answer link back, then compare both full fingerprints.',
'offer-ready': 'Send your code through an authenticated channel, then paste the answer.',
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
verification: verified.value ? 'Waiting for the connection and your peer’s verification…' : 'Compare both full fingerprints before confirming.',
'waiting-accept': 'Waiting for the receiver to accept the file…',
'choose-storage': 'Accept or decline this file.',
@@ -136,10 +153,10 @@ 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; pairingConfirmed.value = false;
managedCredentials.value = null; settings.value.allowTurn = false;
if (!old) return;
clearTimeout(old.timer);
old.stopAnswers?.();
// Start the snapshot before aborting/closing anything; close the peer after
// stats resolve (bounded to 300 ms), so failure evidence remains available.
void old.diagnostics.finish(() => old.pc.close());
@@ -147,9 +164,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;
@@ -157,14 +179,14 @@ function reset(keepNetwork = false) {
inputCode.value = outputCode.value = error.value = '';
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
fps.value = incoming.value = null;
verified.value = choosing.value = false; copied.value = '';
verified.value = copied.value = choosing.value = false;
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; savedToDisk.value = false;
sendState.value = receiveState.value = null; outgoing.value = null;
}
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;
@@ -192,7 +214,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;
@@ -203,17 +225,26 @@ 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.';
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.
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;
@@ -246,11 +277,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,
@@ -264,7 +294,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);
@@ -289,7 +319,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) {
@@ -318,12 +348,6 @@ async function createCode() {
void session.diagnostics.capture();
if (!props.sending) { fps.value = getFingerprints(session.pc, options); offerPairing(session); configureIdentity(session); }
step.value = props.sending ? 'offer-ready' : 'answer-ready';
// An answer link opened in another tab of this browser arrives here.
if (props.sending) session.stopAnswers = listenForAnswers(session.ref, answer => {
if (active !== session || step.value !== 'offer-ready') return false;
inputCode.value = answer; void useAnswer();
return true;
});
} catch (err) {
if (session) fail(session, err);
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
@@ -368,7 +392,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,
@@ -393,6 +417,232 @@ 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,
});
}
async function storePairing(session: Session, setup: NonNullable<typeof pairingSetup>, 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,
// 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 || pairingBusy()) return;
try {
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; }
}
async function acceptPairing() {
const session = active, setup = pairingSetup;
if (!session?.transfer || pairingState.value !== 'incoming' || !setup) return;
// Claim this proposal before key derivation yields; a second click must not
// replace its nonce or send a second acceptance while Vue is rerendering.
pairingState.value = 'accepted';
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 });
} catch (err) {
if (active !== session || pairingSetup !== setup) return;
try { session.transfer.sendPairing({ step: 'error' }); } catch { /* the session ended */ }
pairingState.value = ''; pairingSetup = null; 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 (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.');
}
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;
pairingState.value = 'saving';
await storePairing(session, setup, key);
if (active !== session || pairingSetup !== setup) return;
session.transfer?.sendPairing({ step: 'done' });
pairingState.value = 'awaiting-stored';
} else if (message.step === 'done' && pairingState.value === 'accepted' && pairingSetup?.key) {
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) {
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;
if (!session?.transfer || !incoming.value || !destination || choosing.value || receiveState.value !== 'choose-storage') return;
@@ -418,19 +668,14 @@ async function acceptFile() {
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
} finally { if (active === session) choosing.value = false; }
}
async function copy(kind: 'link' | 'code') {
async function copy() {
const session = active;
try {
await navigator.clipboard.writeText(kind === 'link' ? outputLink.value : outputCode.value);
await navigator.clipboard.writeText(outputCode.value);
if (active !== session) return;
copied.value = kind; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = ''; }, 1500);
} catch { if (active === session) error.value = `Clipboard unavailable. Select and copy the ${kind} manually.`; }
}
async function share() {
const session = active;
try { await navigator.share({ url: outputLink.value }); }
catch (err) { if (active === session && asError(err).name !== 'AbortError') error.value = 'Sharing failed. Copy the link instead.'; }
copied.value = true; clearTimeout(copyTimer);
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
}
function stateLabel(state: TransferState | null) {
return state ? ({ verification: 'Connecting', 'waiting-accept': 'Waiting for acceptance', 'choose-storage': 'Awaiting acceptance', sending: 'Sending', receiving: 'Receiving', saving: 'Saving', 'awaiting-receipt': 'Waiting for receipt', done: 'Complete', closed: 'Cancelled' })[state] : 'Declined';
@@ -441,9 +686,9 @@ function formatBytes(bytes: number) {
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
}
function selectCode(event: FocusEvent) {
if (event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLInputElement) event.target.select();
if (event.target instanceof HTMLTextAreaElement) event.target.select();
}
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
onBeforeUnmount(() => { stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer); });
</script>
<template>
@@ -461,40 +706,30 @@ 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" />
<NetworkSettings v-model="settings" v-model:discovery="discovery" :disabled="busy || connected" :managed-credentials="managedCredentials" :default-tracker="defaultTracker" />
</details>
<p v-if="!connected" class="status">Exchange links or codes privately. They contain your IP address and connection details.</p>
<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 link or code</label>
<label class="step" for="offer-input">Paste the sender’s connection code</label>
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
</template>
<button ref="acceptButton" class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<button class="primary" :disabled="busy || connected || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
<template v-if="outputCode">
<label class="step" for="output-link">{{ sending ? 'Send this link to the receiver' : 'Send this answer link back to the sender' }}</label>
<input id="output-link" class="stun-input" :value="outputLink" readonly @focus="selectCode" />
<div class="share-actions">
<button v-if="canShare" class="primary" @click="share">Share link</button>
<button @click="copy('link')">{{ copied === 'link' ? 'Copied!' : 'Copy link' }}</button>
</div>
<p class="status">A link is as sensitive as a code: send it privately. It may stay in browser history and only works while this page stays open, for up to 5 minutes.</p>
<details class="code-details">
<summary>Show code instead</summary>
<div class="code-entry">
<label class="step" for="output-code">{{ sending ? 'Connection code' : 'Answer code' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy('code')">{{ copied === 'code' ? 'Copied!' : 'Copy code' }}</button>
</div>
</details>
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
</template>
<template v-if="sending && outputCode">
<div class="code-entry">
<label class="step" for="answer-input">Paste the receiver’s answer or answer link</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</div>
<label class="step" for="answer-input">Paste the receiver’s answer</label>
<textarea id="answer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="step !== 'offer-ready'" />
<button class="primary" :disabled="step !== 'offer-ready' || !inputCode.trim()" @click="useAnswer">Connect</button>
</template>
<p v-if="identityStatus" class="status" role="status">{{ identityStatus }}</p>
<div v-if="fps" class="fingerprint">
@@ -531,6 +766,30 @@ 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 === 'saving'" class="status" role="status">Saving reconnect settings…</p>
<p v-else-if="pairingState === 'awaiting-stored'" class="status" role="status">Waiting for your peer to save reconnect settings…</p>
<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 on both devices. Next time, both people open {{ connection.name }} and press Reconnect.</p>
<template v-else>
<p v-if="connection.reconnect" class="status">Reconnect through <strong>{{ trackerHost(connection.reconnect.trackers[0]!) }}</strong> is set up{{ pairingConfirmed ? ' on both devices' : '' }}.</p>
<template v-if="selectedTracker.url">
<p class="status">Next time, both people press Reconnect instead of exchanging codes. <strong>{{ trackerHost(selectedTracker.url) }}</strong> introduces your browsers: it sees IP addresses and timing, not files or codes. Your peer confirms the tracker first.</p>
<button @click="proposePairing">{{ connection.reconnect ? 'Set up reconnect again' : 'Set up reconnect' }}</button>
</template>
<p v-else-if="selectedTracker.error" class="error">{{ selectedTracker.error }} Fix the tracker under Network settings → Connection discovery.</p>
<p v-else-if="!connection.reconnect" class="status">To reconnect without exchanging codes next time, choose a tracker under Network settings → Connection discovery.</p>
</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>
+1
View File
@@ -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 {
+7 -19
View File
@@ -2,15 +2,14 @@ import { parseHello, type IdentityHello } from './identity.ts';
import { asError, isRecord } from './validation.ts';
import { MAX_SIGNAL_LENGTH, validateDescription, type IceOptions } from './webrtc.ts';
// Connection codes: "HC1." + base64url(deflate-raw(JSON)). The same text works
// pasted or as a link fragment, which browsers never send to the app host.
// Connection codes: "HC1." + base64url(deflate-raw(JSON)).
// Codes carry connection details, not secrets; fingerprints authenticate peers.
export const CODE_PREFIX = 'HC1.';
export const MAX_CODE_LENGTH = MAX_SIGNAL_LENGTH;
// Pasted text may be a full link around the code.
// Pasted text may contain line breaks or other whitespace around the code.
export const MAX_INPUT_LENGTH = MAX_CODE_LENGTH * 2;
const MAX_PAYLOAD = MAX_SIGNAL_LENGTH + 1024;
const INVALID = 'Invalid connection code. Paste the complete code or link.';
const INVALID = 'Invalid connection code. Paste the complete code.';
export interface Signal {
type: 'offer' | 'answer';
@@ -21,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) {
@@ -55,17 +54,6 @@ async function inflate(bytes: Uint8Array<ArrayBuffer>) {
export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); }
// Accepts a bare code or a full link and returns the code text.
export function codeFromText(text: string) {
return text.slice(text.lastIndexOf('#') + 1).replace(/\s+/g, '');
}
export function codeLink(code: string, base: string) {
const url = new URL(base);
url.hash = code;
return url.href;
}
export async function encodeCode({ type, ref, sdp, identity }: Signal) {
const payload = identity ? { version: 4, type, ref, sdp, identity: parseHello(identity) } : { version: 3, type, ref, sdp };
const code = CODE_PREFIX + toBase64Url(await deflate(JSON.stringify(payload)));
@@ -75,7 +63,7 @@ export async function encodeCode({ type, ref, sdp, identity }: Signal) {
export async function decodeCode(text: unknown, { type, ref, ...options }: DecodeOptions = {}): Promise<Signal> {
if (typeof text !== 'string' || text.length > MAX_INPUT_LENGTH) throw new Error('Connection code is too large.');
const code = codeFromText(text);
const code = text.replace(/\s+/g, '');
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large.');
if (!code.startsWith(CODE_PREFIX)) {
let legacy = false;
+14 -4
View File
@@ -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) => {
-43
View File
@@ -1,43 +0,0 @@
import { CODE_PREFIX } from './codes.ts';
import { isRecord } from './validation.ts';
// Invitation links carry a code in the fragment, which browsers never send to
// the host. Answers opened in another tab reach the waiting sender over a
// same-origin BroadcastChannel; pasting stays the fallback.
const CHANNEL = 'hellcon-answers';
export type Delivery = 'delivered' | 'used';
// Returns a code from the URL fragment and removes it from the address bar.
// Other fragments, such as the skip link's, are left alone.
export function takeFragment() {
const code = location.hash.slice(1);
if (!code.startsWith(CODE_PREFIX)) return '';
history.replaceState(history.state, '', location.href.split('#')[0]);
return code;
}
// Resolves null when no waiting tab answers in time, for example in a
// messenger's in-app browser or another browser.
export function deliverAnswer(ref: string, code: string, timeout = 1000): Promise<Delivery | null> {
if (typeof BroadcastChannel === 'undefined') return Promise.resolve(null);
const channel = new BroadcastChannel(CHANNEL), id = crypto.randomUUID();
return new Promise(resolve => {
const done = (result: Delivery | null) => { clearTimeout(timer); channel.close(); resolve(result); };
const timer = setTimeout(() => done(null), timeout);
channel.onmessage = ({ data }: MessageEvent) => {
if (isRecord(data) && data.kind === 'ack' && data.id === id && (data.status === 'delivered' || data.status === 'used')) done(data.status);
};
channel.postMessage({ kind: 'answer', id, ref, code });
});
}
// `receive` returns false when the offer no longer waits for an answer.
export function listenForAnswers(ref: string, receive: (code: string) => boolean) {
if (typeof BroadcastChannel === 'undefined') return () => {};
const channel = new BroadcastChannel(CHANNEL);
channel.onmessage = ({ data }: MessageEvent) => {
if (!isRecord(data) || data.kind !== 'answer' || data.ref !== ref || typeof data.id !== 'string' || typeof data.code !== 'string') return;
channel.postMessage({ kind: 'ack', id: data.id, status: receive(data.code) ? 'delivered' : 'used' });
};
return () => channel.close();
}
+156
View File
@@ -0,0 +1,156 @@
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;
}
// 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;
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; }
}
+7
View File
@@ -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.');
+232
View File
@@ -0,0 +1,232 @@
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 connectTimer?: ReturnType<typeof setTimeout>;
private rejectConnect?: (error: Error) => void;
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() {
if (this.closed) return Promise.reject(new Error('The tracker connection is closed.'));
if (this.socket) return Promise.reject(new Error('The tracker connection has already started.'));
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;
this.rejectConnect = reject;
this.connectTimer = setTimeout(() => this.fail(new Error('The tracker did not respond.')), 15_000);
socket.onopen = () => {
clearTimeout(this.connectTimer);
this.announce('started');
this.rejectConnect = undefined;
resolve();
};
socket.onclose = () => {
if (this.closed) return;
const error = new Error('Could not reach the tracker, or it closed the connection.');
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); clearTimeout(this.connectTimer);
this.rejectConnect?.(new Error('Tracker connection cancelled.'));
this.rejectConnect = undefined;
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;
try { this.socket.send(JSON.stringify({ action: 'announce', info_hash: this.infoHash, peer_id: this.peerId, ...data })); }
catch { this.fail(new Error('Could not send to the tracker.')); }
}
private fail(error: Error) {
if (this.closed) return;
this.rejectConnect?.(error);
this.rejectConnect = undefined;
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();
// createOffer replaces the local peer immediately. Its previous answer
// must stop being eligible before gathering or encryption yields.
if (initiator) this.offerId = '';
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.seen.has(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; }
// Only authenticated messages consume replay slots. Invalid tracker
// traffic must not suppress a valid offer or evict previously seen ones.
if (this.closed || this.working || !this.fresh(offerId)) 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; }
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); }
}
}
+1 -5
View File
@@ -104,10 +104,6 @@ export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: Wai
});
}
export function hasRelay(sdp: string) {
return sdp.split(/\r?\n/).some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line));
}
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) {
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
throw new Error('Invalid connection description.');
@@ -122,7 +118,7 @@ export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<Ic
if (fingerprints.length !== 1 || !/^a=fingerprint:sha-256 (?:[\da-f]{2}:){31}[\da-f]{2}$/i.test(fingerprints[0])) {
throw new Error('A single full SHA-256 fingerprint is required.');
}
if (!allowTurn && hasRelay(sdp)) {
if (!allowTurn && lines.some(line => /^a=candidate:.*\styp\s+relay(?:\s|$)/i.test(line))) {
throw new Error('This code contains a TURN relay. Both people must explicitly enable TURN and create new codes to use a relay.');
}
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
+1 -3
View File
@@ -1,7 +1,5 @@
import { createApp } from 'vue';
import App from './App.vue';
import { takeFragment } from './lib/invitations.ts';
import './style.css';
// Read and clear an invitation fragment before anything else can see the URL.
createApp(App, { initialCode: takeFragment() }).mount('#app');
createApp(App).mount('#app');
+4 -6
View File
@@ -329,12 +329,10 @@ summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.dropzone p { font-size: 0.85rem; line-height: 1.65; margin: 0 0 1rem; }
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; }
.share-actions, .session-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
.share-actions button, .session-actions button { font-size: 0.88rem; }
.code-details { width: 100%; min-width: 0; }
.code-details > .code-entry { margin-top: var(--space-md); }
.code-entry { display: flex; flex-direction: column; gap: var(--space-md); min-width: 0; }
.code-entry > button { align-self: start; font-size: 0.88rem; }
.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; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
+2 -7
View File
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto';
import { CODE_PREFIX, MAX_CODE_LENGTH, MAX_INPUT_LENGTH, codeFromText, codeLink, createRef, decodeCode, encodeCode, type Signal } from '../src/lib/codes.ts';
import { CODE_PREFIX, MAX_CODE_LENGTH, MAX_INPUT_LENGTH, createRef, decodeCode, encodeCode, type Signal } from '../src/lib/codes.ts';
const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':');
const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`;
const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
@@ -24,14 +24,9 @@ test('codes round-trip both types, with and without identity', async () => {
}
});
test('links, wrapped text and bare codes decode the same', async () => {
test('wrapped text and bare codes decode the same', async () => {
const code = await encodeCode(offer);
const link = codeLink(code, 'https://example.com/apps/hellcon/?x=1#old');
assert.equal(link, `https://example.com/apps/hellcon/?x=1#${code}`);
assert.equal(codeFromText(link), code);
assert.deepEqual(await decodeCode(link), offer);
assert.deepEqual(await decodeCode(` ${code.slice(0, 20)}\n${code.slice(20)} `), offer);
assert.deepEqual(await decodeCode('#' + code), offer);
});
test('expected type and ref are enforced', async () => {
-39
View File
@@ -1,39 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { deliverAnswer, listenForAnswers, takeFragment } from '../src/lib/invitations.ts';
test('answers reach the waiting offer once and report later deliveries as used', async () => {
let waiting = true;
const received: string[] = [];
const stop = listenForAnswers('ref-a', code => {
if (!waiting) return false;
waiting = false; received.push(code);
return true;
});
const other = listenForAnswers('ref-b', () => assert.fail('another offer must ignore this answer'));
try {
assert.equal(await deliverAnswer('ref-a', 'HC1.answer'), 'delivered');
assert.equal(await deliverAnswer('ref-a', 'HC1.answer'), 'used');
assert.deepEqual(received, ['HC1.answer']);
} finally { stop(); other(); }
});
test('answers without a waiting tab fall back to manual pasting', async () => {
assert.equal(await deliverAnswer('nobody', 'HC1.answer', 50), null);
const stop = listenForAnswers('ref-a', () => true);
stop();
assert.equal(await deliverAnswer('ref-a', 'HC1.answer', 50), null);
});
test('only code fragments are taken from the URL', () => {
const replaced: string[] = [];
const url = { href: 'https://example.test/app/?x=1#HC1.abc', hash: '#HC1.abc' };
Object.assign(globalThis, { location: url, history: { state: null, replaceState: (_: unknown, __: string, next: string) => replaced.push(next) } });
try {
assert.equal(takeFragment(), 'HC1.abc');
assert.deepEqual(replaced, ['https://example.test/app/?x=1']);
Object.assign(url, { href: 'https://example.test/app/#main-content', hash: '#main-content' });
assert.equal(takeFragment(), '');
assert.equal(replaced.length, 1);
} finally { Reflect.deleteProperty(globalThis, 'location'); Reflect.deleteProperty(globalThis, 'history'); }
});
+119
View File
@@ -0,0 +1,119 @@
import test from 'node:test';
import assert from 'node:assert/strict';
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(' ');
const id = (char: string) => char.repeat(20);
const context: PairingContext = {
proposerNonce: pairingNonce(), acceptorNonce: pairingNonce(),
proposerKey: '04' + 'a'.repeat(128), acceptorKey: '04' + 'b'.repeat(128),
offerFingerprint: fingerprint('AA'), answerFingerprint: fingerprint('BB'),
tracker: 'wss://tracker.example/announce',
};
const route: SignalRoute = { role: 'offer', infoHash: id('h'), offerId: id('o'), from: id('f'), to: '' };
test('both peers derive the same pairing; every input separates it', async () => {
const [first, second] = await Promise.all([derivePairing(context), derivePairing({ ...context })]);
assert.equal(first.extractable, false);
assert.equal(await discoveryId(first, 100), await discoveryId(second, 100));
const sealed = await sealSignal(await signalingKey(first), route, 'HC1.code');
assert.equal(await openSignal(await signalingKey(second), route, sealed), 'HC1.code');
for (const changed of [
{ proposerNonce: pairingNonce() }, { acceptorNonce: pairingNonce() },
{ proposerKey: context.acceptorKey, acceptorKey: context.proposerKey },
{ offerFingerprint: fingerprint('CC') }, { answerFingerprint: fingerprint('CC') },
{ tracker: 'wss://other.example/announce' },
]) {
const other = await derivePairing({ ...context, ...changed });
assert.notEqual(await discoveryId(other, 100), await discoveryId(first, 100));
await assert.rejects(openSignal(await signalingKey(other), route, sealed));
}
await assert.rejects(derivePairing({ ...context, acceptorKey: context.proposerKey }), /two different devices/);
await assert.rejects(derivePairing({ ...context, proposerNonce: 'short' }));
});
test('discovery identifiers are 20 binary bytes and change daily', async () => {
const key = await derivePairing(context);
const today = await discoveryId(key, 20000);
assert.equal(today.length, 20);
assert.ok([...today].every(char => char.charCodeAt(0) < 256));
assert.notEqual(await discoveryId(key, 20001), today);
});
test('envelopes bind role and every routing field, and expire', async () => {
const key = await signalingKey(await derivePairing(context));
const now = 1_000_000_000_000;
const sealed = await sealSignal(key, route, 'HC1.code', now);
assert.equal(signalRole(sealed), 'offer');
assert.equal(await openSignal(key, route, sealed, now), 'HC1.code');
for (const changed of [{ infoHash: id('x') }, { offerId: id('x') }, { from: id('x') }, { to: id('x') }]) {
await assert.rejects(openSignal(key, { ...route, ...changed }, sealed, now));
}
await assert.rejects(openSignal(key, { ...route, role: 'answer' }, sealed, now));
const tampered = sealed.slice(0, -2) + (sealed.endsWith('A') ? 'B' : 'A') + sealed.slice(-1);
await assert.rejects(openSignal(key, route, tampered, now));
await assert.rejects(openSignal(key, route, sealed, now + SIGNAL_LIFETIME + CLOCK_TOLERANCE + 1), /expired/);
await assert.rejects(openSignal(key, route, 'x'.repeat(200_000), now));
const wake = await sealSignal(key, { ...route, role: 'wake' }, '', now);
assert.equal(await openSignal(key, { ...route, role: 'wake' }, wake, now), '');
// A wake never carries a code, and offers always do.
await assert.rejects(openSignal(key, route, await sealSignal(key, route, '', now), now));
});
test('tracker addresses must be secure WebSocket URLs', () => {
assert.equal(trackerUrl(' wss://tracker.example '), 'wss://tracker.example/');
assert.equal(trackerUrl('ws://localhost:8000'), 'ws://localhost:8000/');
for (const bad of ['https://tracker.example', 'ws://tracker.example', 'wss://user:pass@tracker.example', 'wss://tracker.example/#x', 'nonsense', 42]) {
assert.throws(() => trackerUrl(bad));
}
});
test('stored pairings are dropped when the paired device changes', async () => {
const peerKey = context.acceptorKey;
const pairing = { version: 1 as const, trackers: ['wss://tracker.example/'], key: await derivePairing(context), localKey: context.proposerKey, peerKey };
const paired = updateConnection(emptyConnection(), { peerKey });
const reconnecting = updateConnection(paired, { reconnect: pairing });
assert.equal(reconnecting.reconnect?.trackers[0], 'wss://tracker.example/');
assert.equal(updateConnection(reconnecting, { name: 'Laptop' }).reconnect, reconnecting.reconnect);
assert.equal(updateConnection(reconnecting, { peerKey }).reconnect, reconnecting.reconnect);
assert.equal(updateConnection(reconnecting, { peerKey: '' }).reconnect, null);
assert.equal(updateConnection(reconnecting, { peerKey: context.proposerKey }).reconnect, null);
assert.equal(updateConnection(reconnecting, { reconnect: null }).reconnect, null);
assert.throws(() => updateConnection(emptyConnection(), { reconnect: pairing }));
assert.equal(parsePairing(structuredClone(pairing), peerKey)?.key.algorithm.name, 'HKDF');
assert.equal(parsePairing({ ...pairing, trackers: ['http://x'] }, peerKey), null);
assert.equal(parsePairing({ ...pairing, key: 'secret' }, peerKey), null);
});
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<string, string>();
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'); }
});
+27 -1
View File
@@ -21,13 +21,14 @@ const tick = () => new Promise<void>(resolve => setImmediate(resolve));
async function until(check: () => boolean) { for (let n = 0; n < 500; n++) { if (check()) return; await tick(); } assert.fail('Condition did not become true'); }
const file = (name: string, size = 3) => new File([new Uint8Array(size).fill(42)], name);
function side(channel: Channel, initiator: boolean) {
const state = { ready: false, queue: [] as QueueItem[], send: '' as TransferState | '', receive: '' as TransferState | '', results: [] as { direction: string; result: TransferResult }[], declined: [] as string[], errors: [] as string[], closed: false };
const state = { ready: false, queue: [] as QueueItem[], send: '' as TransferState | '', receive: '' as TransferState | '', results: [] as { direction: string; result: TransferResult }[], declined: [] as string[], errors: [] as string[], closed: false, pairings: [] as Record<string, unknown>[] };
const callbacks: SessionCallbacks = {
onReady() { state.ready = true; }, onQueue(items) { state.queue = items; },
onState(direction, value) { state[direction] = value; }, onProgress() {},
onComplete(direction, result) { state.results.push({ direction, result }); },
onDecline(direction, meta) { state.declined.push(meta.name); state[direction] = ''; },
onError(error) { state.errors.push(error.message); }, onClose() { state.closed = true; },
onPairing(message) { state.pairings.push(message); },
};
return { session: new FileSession(channel, initiator, callbacks), state, channel };
}
@@ -144,3 +145,28 @@ test('invalid or missing identity proof closes the session without releasing fil
assert.match(first.state.errors.join(''), /Device proof failed/);
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
});
test('pairing messages wait for mutual verification and device proofs', async t => {
const { first, second } = pair(t);
let release!: () => void;
const proof = new Promise<void>(resolve => { release = resolve; });
t.after(() => release());
for (const side of [first, second]) side.session.authenticate({ sign: async () => 'proof', verify: () => proof });
first.session.verify(); second.session.verify(); await tick();
assert.throws(() => first.session.sendPairing({ step: 'propose' }));
assert.deepEqual(second.state.pairings, []);
release(); await until(() => first.state.ready && second.state.ready);
first.session.sendPairing({ step: 'check', value: '' });
await until(() => second.state.pairings.length === 1);
assert.deepEqual(second.state.pairings, [{ v: 3, type: 'pairing', step: 'check', value: '' }]);
first.session.close();
assert.throws(() => first.session.sendPairing({ step: 'propose' }));
});
test('unsolicited pairing messages before verification never reach the setup handler', async t => {
const { first } = pair(t);
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'pairing', step: 'propose' }) }));
await until(() => first.state.closed);
assert.deepEqual(first.state.pairings, []);
assert.match(first.state.errors[0]!, /before verification/);
});
+245
View File
@@ -0,0 +1,245 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { ReconnectAttempt, TrackerClient, RETRY_INTERVAL, MAX_SIGNALS, type AttemptHooks } from '../src/lib/tracker.ts';
import { derivePairing, discoveryId, pairingNonce, sealSignal, signalingKey } from '../src/lib/reconnect.ts';
// An in-memory tracker with the routing of webtorrent/bittorrent-tracker:
// counts include the announcing peer, offers go to other registered peers,
// answers go to to_peer_id. Messages are delivered asynchronously.
class FakeTracker {
peers = new Map<string, FakeSocket>();
frames: Record<string, unknown>[] = [];
refuse = '';
holdAnswers = false;
answers: (() => void)[] = [];
connect = (_url: string) => new FakeSocket(this) as unknown as WebSocket;
handle(socket: FakeSocket, data: Record<string, unknown>) {
this.frames.push(data);
const reply = (target: FakeSocket, message: object) => target.deliver({ action: 'announce', info_hash: data.info_hash, ...message });
if (this.refuse) { reply(socket, { 'failure reason': this.refuse }); return; }
const peerId = data.peer_id as string;
if (data.event === 'stopped') { this.peers.delete(peerId); return; }
this.peers.set(peerId, socket);
if (data.answer) {
const target = this.peers.get(data.to_peer_id as string);
if (target) {
const deliver = () => reply(target, { peer_id: peerId, offer_id: data.offer_id, answer: data.answer });
if (this.holdAnswers) this.answers.push(deliver); else deliver();
}
return;
}
reply(socket, { interval: 120, complete: 0, incomplete: this.peers.size });
const others = [...this.peers].filter(([id]) => id !== peerId).map(([, peer]) => peer);
for (const [index, item] of ((data.offers ?? []) as { offer_id: string; offer: unknown }[]).entries()) {
const target = others[index];
if (target) reply(target, { peer_id: peerId, offer_id: item.offer_id, offer: item.offer });
}
}
}
class FakeSocket {
readyState = 0;
onopen: (() => void) | null = null;
onclose: (() => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
tracker: FakeTracker;
constructor(tracker: FakeTracker) { this.tracker = tracker; setTimeout(() => { if (this.readyState !== 0) return; this.readyState = 1; this.onopen?.(); }); }
send(text: string) { const data = JSON.parse(text); setTimeout(() => this.tracker.handle(this, data)); }
deliver(message: object) { setTimeout(() => { if (this.readyState === 1) this.onmessage?.({ data: JSON.stringify(message) }); }); }
close() { this.readyState = 3; }
}
async function pairing() {
const key = await derivePairing({
proposerNonce: pairingNonce(), acceptorNonce: pairingNonce(), proposerKey: '04' + 'a'.repeat(128), acceptorKey: '04' + 'b'.repeat(128),
offerFingerprint: Array(32).fill('AA').join(' '), answerFingerprint: Array(32).fill('BB').join(' '), tracker: 'wss://tracker.test/',
});
return { infoHash: await discoveryId(key), key: await signalingKey(key) };
}
function peer(tracker: FakeTracker, shared: { infoHash: string; key: CryptoKey }, initiator: boolean, overrides: Partial<AttemptHooks> = {}) {
const log = { offers: 0, answered: [] as string[], accepted: [] as string[], errors: [] as string[] };
let done: () => void;
const finished = new Promise<void>(resolve => { done = resolve; });
const hooks: AttemptHooks = {
createOffer: async () => `HC1.offer-${++log.offers}`,
createAnswer: async offer => { log.answered.push(offer); return `HC1.answer-to-${offer}`; },
acceptAnswer: async answer => { log.accepted.push(answer); done(); },
onPeers: () => {},
onError: error => { log.errors.push(error.message); done(); },
...overrides,
};
const attempt = new ReconnectAttempt({ url: 'wss://tracker.test/', ...shared, initiator, hooks, connectSocket: tracker.connect });
return { attempt, log, finished };
}
const settle = () => new Promise(resolve => setTimeout(resolve, 20));
async function until(check: () => boolean) {
for (let n = 0; n < 100; n++) { if (check()) return; await settle(); }
assert.fail('Expected tracker activity did not arrive');
}
for (const initiatorFirst of [true, false]) {
test(`peers connect when the ${initiatorFirst ? 'initiator' : 'responder'} arrives first`, { timeout: 5000 }, async t => {
const tracker = new FakeTracker(), shared = await pairing();
const initiator = peer(tracker, shared, true), responder = peer(tracker, shared, false);
t.after(() => { initiator.attempt.close(); responder.attempt.close(); });
const [first, second] = initiatorFirst ? [initiator, responder] : [responder, initiator];
await first.attempt.start(); await settle();
await second.attempt.start();
await initiator.finished;
assert.equal(initiator.log.offers, 1, 'One offer without waiting for a retry');
assert.deepEqual(responder.log.answered, ['HC1.offer-1']);
assert.deepEqual(initiator.log.accepted, ['HC1.answer-to-HC1.offer-1']);
// Routing data only: no codes in clear on the tracker.
assert.ok(tracker.frames.every(frame => !JSON.stringify(frame).includes('HC1.')));
initiator.attempt.close(); responder.attempt.close();
await settle();
assert.equal(tracker.peers.size, 0, 'Both peers send stopped on close');
});
}
test('a client with another key in the swarm is ignored', async t => {
const tracker = new FakeTracker(), shared = await pairing(), other = await pairing();
const stranger = peer(tracker, { ...other, infoHash: shared.infoHash }, false);
const initiator = peer(tracker, shared, true);
t.after(() => { initiator.attempt.close(); stranger.attempt.close(); });
await stranger.attempt.start(); await settle();
await initiator.attempt.start(); await settle(); await settle();
// The stranger's wake does not open, so it never prompts an offer by itself;
// the count alone does, and the stranger cannot open that offer.
assert.equal(initiator.log.offers, 1);
assert.deepEqual(stranger.log.answered, []);
assert.deepEqual(initiator.log.errors, []);
initiator.attempt.close(); stranger.attempt.close();
});
test('tracker refusals and invalid frames end the attempt', { timeout: 5000 }, async t => {
const tracker = new FakeTracker(), shared = await pairing();
tracker.refuse = 'swarm limit';
const refused = peer(tracker, shared, true);
t.after(() => refused.attempt.close());
await refused.attempt.start();
await refused.finished;
assert.match(refused.log.errors[0]!, /refused the request: swarm limit/);
const errors: string[] = [];
let socket: FakeSocket | undefined;
const client = new TrackerClient('wss://tracker.test/', shared.infoHash, { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: error => errors.push(error.message) },
() => (socket = new FakeSocket(new FakeTracker())) as unknown as WebSocket);
t.after(() => client.close());
await client.connect();
socket!.onmessage?.({ data: 'not json' });
assert.deepEqual(errors, ['The tracker sent an invalid message.']);
assert.throws(() => new TrackerClient('wss://tracker.test/', 'short', { onPeers: () => {}, onOffer: () => {}, onAnswer: () => {}, onError: () => {} }));
});
test('cancelling a connecting socket settles immediately and clears its timeout', async t => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const socket = new FakeSocket(new FakeTracker());
const errors: string[] = [];
const client = new TrackerClient('wss://tracker.test/', 'h'.repeat(20), {
onPeers() {}, onOffer() {}, onAnswer() {}, onError: error => errors.push(error.message),
}, () => socket as unknown as WebSocket);
const outcome = client.connect().then(() => 'opened', error => error.message);
let settled = false;
void outcome.then(() => { settled = true; });
client.close();
await Promise.resolve(); await Promise.resolve();
assert.equal(settled, true, 'Cancel must settle the pending connect without waiting 15 seconds');
assert.match(await outcome, /cancelled/i);
t.mock.timers.tick(30000);
assert.equal(socket.readyState, 3);
assert.deepEqual(errors, []);
await assert.rejects(client.connect(), /closed/i);
});
for (const failure of ['timeout', 'close', 'send'] as const) {
test(`tracker ${failure} failure rejects the handshake and reports one error`, async t => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const socket = new FakeSocket(new FakeTracker()), errors: string[] = [];
const client = new TrackerClient('wss://tracker.test/', 'h'.repeat(20), {
onPeers() {}, onOffer() {}, onAnswer() {}, onError: error => errors.push(error.message),
}, () => socket as unknown as WebSocket);
t.after(() => client.close());
const connecting = client.connect();
const expected = failure === 'timeout' ? /did not respond/ : failure === 'close' ? /closed the connection/ : /Could not send/;
const rejected = assert.rejects(connecting, expected);
if (failure === 'timeout') {
// Keep the fake handshake pending rather than letting its open timer fire.
socket.readyState = 2;
t.mock.timers.tick(15000);
} else if (failure === 'close') socket.onclose?.();
else {
socket.send = () => { throw new Error('Socket send failed'); };
t.mock.timers.tick(0);
}
await rejected;
t.mock.timers.tick(30000);
assert.equal(errors.length, 1);
assert.match(errors[0]!, expected);
assert.equal(socket.readyState, 3);
});
}
test('a late answer cannot be applied while a replacement offer is gathering', { timeout: 5000 }, async t => {
t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
const tracker = new FakeTracker(), shared = await pairing();
tracker.holdAnswers = true;
let offers = 0, release!: () => void;
const gathering = new Promise<void>(resolve => { release = resolve; });
const initiator = peer(tracker, shared, true, { createOffer: async () => {
offers++;
if (offers === 2) await gathering;
return `HC1.offer-${offers}`;
} });
const responder = peer(tracker, shared, false);
t.after(() => { release(); initiator.attempt.close(); responder.attempt.close(); });
await responder.attempt.start(); await settle(); await initiator.attempt.start();
await until(() => tracker.answers.length === 1);
const offer = tracker.frames.find(frame => (frame.offers as unknown[])?.length)!;
const socket = tracker.peers.get(offer.peer_id as string)!;
t.mock.timers.tick(RETRY_INTERVAL);
socket.deliver({ action: 'announce', info_hash: shared.infoHash, complete: 0, incomplete: 2 });
await until(() => offers === 2);
tracker.answers.shift()!(); await settle();
assert.deepEqual(initiator.log.accepted, [], 'The old peer connection has already been disposed');
tracker.holdAnswers = false; release();
await until(() => initiator.log.accepted.length === 1);
assert.deepEqual(initiator.log.accepted, ['HC1.answer-to-HC1.offer-2']);
assert.deepEqual(initiator.log.errors, []);
});
test('unauthenticated frames cannot poison or evict the offer replay cache', async t => {
const tracker = new FakeTracker(), shared = await pairing();
const responder = peer(tracker, shared, false);
t.after(() => responder.attempt.close());
await responder.attempt.start(); await until(() => tracker.peers.size === 1);
const socket = [...tracker.peers.values()][0]!;
const route = { role: 'offer' as const, infoHash: shared.infoHash, offerId: 'o'.repeat(20), from: 'p'.repeat(20), to: '' };
const sdp = await sealSignal(shared.key, route, 'HC1.valid');
const deliver = (id: string, text: string) => socket.deliver({ action: 'announce', info_hash: shared.infoHash, peer_id: route.from, offer_id: id, offer: { type: 'offer', sdp: text } });
deliver(route.offerId, 'HCR1.o.invalid'); await settle();
deliver(route.offerId, sdp);
await until(() => responder.log.answered.length === 1);
for (let n = 0; n < 70; n++) deliver(String(n).padStart(20, 'x'), 'HCR1.o.invalid');
await settle(); deliver(route.offerId, sdp); await settle();
assert.deepEqual(responder.log.answered, ['HC1.valid']);
assert.deepEqual(responder.log.errors, []);
});
test('unanswered offers stop at the retry limit and closing stops further work', async t => {
t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
const tracker = new FakeTracker(), shared = await pairing();
const initiator = peer(tracker, shared, true);
t.after(() => initiator.attempt.close());
await initiator.attempt.start(); await until(() => tracker.peers.size === 1);
const socket = [...tracker.peers.values()][0]!;
const count = () => socket.deliver({ action: 'announce', info_hash: shared.infoHash, complete: 0, incomplete: 2 });
for (let n = 1; n <= MAX_SIGNALS; n++) {
count(); await until(() => tracker.frames.filter(frame => (frame.offers as unknown[])?.length).length === n);
t.mock.timers.tick(RETRY_INTERVAL);
}
count(); await until(() => initiator.log.errors.length === 1);
assert.match(initiator.log.errors[0]!, /did not respond/);
count(); await settle();
assert.equal(initiator.log.offers, MAX_SIGNALS);
assert.equal(socket.readyState, 3);
});
+1 -1
View File
@@ -10,7 +10,7 @@ RUN npm ci --omit=dev --omit=optional --ignore-scripts --no-audit --no-fund \
FROM dependencies AS test
COPY server.mjs healthcheck.mjs test.mjs ./
USER node
RUN node --test test.mjs
CMD ["node", "--test", "test.mjs"]
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS runtime
ENV NODE_ENV=production PORT=8000 DEBUG=""
+3 -2
View File
@@ -26,8 +26,9 @@ its health check; it does not start coturn or require `.env.development`. Vite
continues to run on the host. No service is enabled at boot and the development
container has no automatic restart policy.
`test:tracker` builds the Dockerfile's test target and runs native Node WebSocket
clients against the actual tracker server. It tests both arrival orders, counts
`test:tracker` builds the Dockerfile's test target, then runs it in a fresh
container so Docker's build cache cannot skip the tests. Native Node WebSocket
clients exercise the actual tracker server. Coverage includes both arrival orders, counts
in announce replies, a 64 KiB code after AES-GCM/base64 encoding, answer routing,
disconnect cleanup, graceful termination, disabled HTTP and WebSocket scrape,
malformed/oversized messages, swarm/rate limits, per-socket swarm and peer ID