Compare commits
43
Commits
9f3f21884f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c47047ddd | ||
|
|
1b2696b6b4 | ||
|
|
ac4d496a48 | ||
|
|
44a8a72261 | ||
|
|
870d55b44f | ||
|
|
af0a8c9fee | ||
|
|
7f4811485a | ||
|
|
b102e55495 | ||
|
|
ae1e3bef9b | ||
|
|
ae871a2647 | ||
|
|
8f82700736 | ||
|
|
f53d39ae69 | ||
|
|
aa61efcc10 | ||
|
|
2e47b55901 | ||
|
|
e3a2b348d6 | ||
|
|
d92c4b50cf | ||
|
|
f7e8999439 | ||
|
|
02668de602 | ||
|
|
3c4e706e1f | ||
|
|
bd0154db68 | ||
|
|
21ea9a7e02 | ||
|
|
840bc3572b | ||
|
|
5729ed62f7 | ||
|
|
8b36e51b56 | ||
|
|
4725b14a40 | ||
|
|
22d794965e | ||
|
|
bb69569b51 | ||
|
|
338d4d2532 | ||
|
|
c6145b8919 | ||
|
|
707248f36b | ||
|
|
b6b6e7c29b | ||
|
|
2167b528b2 | ||
|
|
a35bd71ca7 | ||
|
|
0df1dd4f70 | ||
|
|
2abd0b504d | ||
|
|
bacc15baaf | ||
|
|
85ccdbfc03 | ||
|
|
08b9f659c2 | ||
|
|
9282865a8c | ||
|
|
1bfeb9843a | ||
|
|
ff7b84af02 | ||
|
|
aea75fff92 | ||
|
|
24307eb96a |
No files matched your search
@@ -1,8 +0,0 @@
|
||||
# Run bun run dev:setup to create .env.development with a random secret.
|
||||
TURN_SECRET=replace-with-a-random-secret
|
||||
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
|
||||
@@ -3,3 +3,4 @@ dist
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
test-results
|
||||
-175
@@ -1,175 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
|
||||
- A connections sidebar with up to 100 named slots. Each row shows its session
|
||||
status and lets you rename or remove that connection. Switching slots keeps
|
||||
live sessions and selected files; names and paired devices are saved locally.
|
||||
On mobile the sidebar collapses and a bar shows the open connection and its
|
||||
status.
|
||||
- Remembered devices. Each browser can create an opt-in device identity with a
|
||||
non-extractable private key. After one manual fingerprint comparison, a
|
||||
connection pairs with the verified peer; later sessions check fresh mutual
|
||||
signatures bound to both connection fingerprints. A changed key is replaced
|
||||
only on explicit choice. Forget a device or delete the identity at any time.
|
||||
Identity-enabled signaling uses v4; temporary v3 sessions remain available.
|
||||
- Verified sessions stay open for more files: bounded queues (32 files per
|
||||
side), sending in both directions, per-file acceptance, progress, and
|
||||
receipts, queue removal, and incoming-file decline.
|
||||
- **Disconnect**, which aborts unfinished writes, and Send/Receive navigation
|
||||
within a live session. The initial receiver can send files without
|
||||
reconnecting.
|
||||
- Experimental tracker reconnect for paired devices. 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
|
||||
|
||||
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers
|
||||
must update; v2 codes are rejected before connection setup.
|
||||
- Connection codes are compressed to roughly half their length (`HC1.` plus
|
||||
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 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
|
||||
to Downloads automatically on completion.
|
||||
- A completed memory download stays available via **Save again** until the next
|
||||
file is accepted, including after Disconnect.
|
||||
|
||||
### Removed
|
||||
|
||||
- The downloadable single-file HTML app (`hellcon-local.html`), its
|
||||
**Download app for local use** link, and `file://` support. Serve the `dist/`
|
||||
build over HTTPS or open it on localhost instead.
|
||||
|
||||
## [0.0.4] - 2026-10-16
|
||||
|
||||
### Added
|
||||
|
||||
- Added streaming downloads for the hosted app using a same-origin service
|
||||
worker with bounded buffering. Verified real 120 MiB downloads in Chromium
|
||||
and Brave without the native file picker.
|
||||
- Worker tests for byte counts, backpressure, cancellation, and single-use URLs,
|
||||
plus a browser check that verifies actual downloaded file contents.
|
||||
- Guidance to use desktop Chrome for large files in the downloaded local version.
|
||||
|
||||
### Changed
|
||||
|
||||
- Removed the app-defined 64 GiB file-size cap for streamed and native disk
|
||||
transfers. Browser, filesystem, available storage, and exact byte-count limits
|
||||
still apply. The 64 MiB in-memory safety cap remains in place.
|
||||
- Download receive buttons now show the incoming file size instead of a size cap.
|
||||
- Streaming completion reports that bytes were handed to the browser; users
|
||||
should check Downloads for the final save result.
|
||||
- Local `file://` copies remain independent of hosted helpers and use the native
|
||||
save picker or the in-memory option. Service-worker downloads are hosted-only.
|
||||
|
||||
## [0.0.3] - 2026-10-09
|
||||
|
||||
### Added
|
||||
|
||||
- A downloadable single-file HTML app that can be opened directly from disk,
|
||||
without the website host. Local copies can transfer files through WebRTC.
|
||||
- A browser check that transfers a file between two `file://` copies.
|
||||
|
||||
### Changed
|
||||
|
||||
- Labeled the download "for local use" and documented that peers may still need
|
||||
internet access and reachable STUN or TURN servers.
|
||||
- Disabled the host's managed TURN credential endpoint when running from a local
|
||||
file; manual TURN settings remain available.
|
||||
|
||||
## [0.0.2] - 2026-10-09
|
||||
|
||||
### Added
|
||||
|
||||
- Local coturn setup with temporary relay credentials issued per connection and
|
||||
browser checks for UDP and TCP relay paths.
|
||||
- Automated axe accessibility checks in both transfer modes and during and
|
||||
after a file transfer.
|
||||
|
||||
### Changed
|
||||
|
||||
- Migrated the app, development scripts, and tests to TypeScript. TypeScript 6
|
||||
keeps Vue type checking and production builds working.
|
||||
- Show managed relay details in read-only fields while a connection is active.
|
||||
- Improved button contrast and focus visibility with an orange accent and
|
||||
slightly larger button text.
|
||||
- Added a main landmark, skip link, accessible transfer-mode state, and a
|
||||
heading for fingerprint verification.
|
||||
|
||||
## [0.0.1] - 2026-10-09
|
||||
|
||||
### Added
|
||||
|
||||
- Mandatory full SHA-256 fingerprint confirmation by both peers before sharing
|
||||
file metadata or contents.
|
||||
- Receiver acceptance and direct-to-disk saving in supported browsers.
|
||||
- Optional TURN relaying, requiring explicit opt-in from both peers. Consent
|
||||
clears after a connection completes, fails, or is reset or cancelled.
|
||||
- Protocol regression tests and Chromium, Brave, and Firefox integration checks.
|
||||
|
||||
### Changed
|
||||
|
||||
- Enforced message validation, exact file sizes, and bounded buffering.
|
||||
- Limited memory downloads to 64 MiB and direct-to-disk transfers to 64 GiB.
|
||||
- Report transfer completion only after receiver acknowledgment.
|
||||
- Updated dependencies, including the fix for the `source-map-js` advisory.
|
||||
- Clarified encryption, hosting trust, connection-code privacy, and deployment
|
||||
requirements.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Reset failing to restore the ready state.
|
||||
- Invalid answers unnecessarily destroying valid connection offers.
|
||||
- Connections and unfinished disk writes surviving cancellation or tab changes.
|
||||
- Completed Firefox downloads disappearing when Brave disconnected.
|
||||
- Excess data, duplicate metadata, and malformed messages corrupting transfers
|
||||
or causing unbounded memory growth.
|
||||
- ICE gathering silently returning incomplete connection information, and
|
||||
stalled transfers waiting indefinitely.
|
||||
|
||||
### Compatibility
|
||||
|
||||
- Introduced signaling and transfer protocol v2. Both peers must use the updated
|
||||
app; connection codes from earlier versions are no longer accepted.
|
||||
- Files larger than 64 MiB require a receiving browser with direct-to-disk
|
||||
saving support.
|
||||
@@ -1,364 +1,176 @@
|
||||
# HellCon
|
||||
|
||||
Current version: **0.0.6**. See the [changelog](CHANGELOG.md) for release
|
||||
notes and compatibility changes.
|
||||
Send a file straight from one browser to another. No account, no upload, no app to install, and no
|
||||
size limit: the file goes directly to the other person and is never stored on a server.
|
||||
|
||||
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.
|
||||
## How to send a file
|
||||
|
||||
This is experimental software, not independently audited or battle-tested.
|
||||
Browser compatibility, network connectivity, and storage availability vary.
|
||||
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
|
||||
an 11 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
|
||||
get the file, or pretend to be you, so give it to nobody else.
|
||||
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
|
||||
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
|
||||
|
||||
## Connections
|
||||
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
|
||||
tab was doing.
|
||||
|
||||
The sidebar lists your connections, starting with **Con 1**, up to 100. Each one
|
||||
has its own setup and live session.
|
||||
Both sides need the same protocol, shown at the bottom of the page. A HellCon hosted elsewhere may
|
||||
run another one, the receiver then finds no sender, or with **Manual** says the sender runs another
|
||||
protocol.
|
||||
|
||||
- **Open** a connection by clicking its row. The row shows its name and this
|
||||
tab's session status (not whether the remote device is online).
|
||||
- **Rename** with the pen. Enter or leaving the field saves; Escape cancels.
|
||||
An empty name keeps the previous one.
|
||||
- **Remove** with ✕, then confirm. This ends the connection's sessions in all
|
||||
open tabs and forgets its remembered device. Downloaded files and your device
|
||||
identity remain. Removing the last connection leaves a fresh **Con 1**.
|
||||
- **Add connection** creates another empty slot.
|
||||
### Without a tracker
|
||||
|
||||
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 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.
|
||||
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
|
||||
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
|
||||
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
|
||||
**Connect**. The offer and answer contain your network addresses, so only share them with the person
|
||||
you're sending to. Both sides then compare the security check (see below) and click **Codes match**.
|
||||
|
||||
Names and remembered devices are saved in this browser. Transfer history, file
|
||||
contents, connection codes, and relay credentials are not. Clearing site data
|
||||
removes saved connections, identities, and trust. If storage fails, the app says
|
||||
so and temporary sessions still work.
|
||||
## The security check
|
||||
|
||||
## Sharing files
|
||||
Before anything is transferred, both sides make sure they are connected directly to each other and
|
||||
not to someone who placed themselves in between.
|
||||
|
||||
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 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
|
||||
every byte and cancel on any mismatch. Nothing about the files is sent until
|
||||
both people confirm. A [remembered device](#remembered-devices) can replace
|
||||
this step on later connections.
|
||||
4. **Accept the file.** The receiver sees the filename and size and clicks
|
||||
**Accept file**. Files stream into the browser's download manager through a
|
||||
same-origin service worker (HTTPS or localhost; Chromium and Brave are tested
|
||||
with 120 MiB files). Without streaming support, the native save picker is
|
||||
used. Without either, files up to 64 MiB are buffered in memory and handed to
|
||||
Downloads on completion (**Save again** repeats this); larger files cannot be
|
||||
received. Keep the receiving tab open.
|
||||
5. **Receipt.** The sender waits for the receiver's acknowledgment, sent after
|
||||
the disk write closes, after all bytes reach the browser's download manager,
|
||||
or after the memory download is built. A receipt does not prove the download
|
||||
manager saved the file (check Downloads), nor that a malicious receiver told
|
||||
the truth.
|
||||
With the code this happens by itself: each side proves to the other that it knows the code, tied
|
||||
to the encryption keys of this very connection. Someone in between, or anyone else who doesn't
|
||||
know the code, can't do that, and HellCon drops the connection and waits for the right one.
|
||||
|
||||
Streamed transfers have no app-defined size cap; browser, filesystem, and storage
|
||||
limits apply, and byte counts must stay below 2^53. Files above 120 MiB have not
|
||||
been tested end to end.
|
||||
The manual exchange has no code, so there you compare yourselves. Once connected, both sides see two
|
||||
codes: **You** and **Peer**. Compare them with the other person over a channel you already trust,
|
||||
ideally a call or in person:
|
||||
|
||||
### During a session
|
||||
- your **You** must be their **Peer**, and
|
||||
- your **Peer** must be their **You**.
|
||||
|
||||
Once verified, either person can add files without new codes. Each side queues
|
||||
up to 32 files, including its active one. Each direction sends one file at a
|
||||
time, and both directions can run at once. Every file has its own acceptance,
|
||||
progress, and receipt. **Remove** drops a waiting file from your queue;
|
||||
**Decline file** rejects an incoming one and lets the sender's queue continue.
|
||||
Send/Receive chooses who starts before connecting; afterwards it switches between
|
||||
the sending and receiving sections without reconnecting.
|
||||
If both match, you are connected directly to each other. If they don't, someone has placed
|
||||
themselves in between: click **Codes don't match** and nothing is sent. Nothing is transferred before
|
||||
both sides confirmed, so take the time to compare every character, not just the start and end.
|
||||
|
||||
**Disconnect** ends the session, drops waiting files, and aborts unfinished disk
|
||||
writes; cancelling a single active file is not supported. A completed memory
|
||||
download stays available via **Save again** until the next accepted file
|
||||
replaces it. **Reset** discards it and returns to setup; the connection stays.
|
||||
The codes are taken from the encryption keys of the connection. Someone in between would need their
|
||||
own keys, which show up as different codes.
|
||||
|
||||
Switching tabs or apps does not end the session, but browsers and mobile systems
|
||||
may suspend pages. Pending verification or acceptance expires after five
|
||||
minutes, stalled transfers after one minute; idle verified sessions stay open.
|
||||
## How it works
|
||||
|
||||
### Troubleshooting
|
||||
The file travels over a direct, encrypted WebRTC connection between the two browsers. To set that up,
|
||||
the browsers need two things:
|
||||
|
||||
- A pasted answer that is invalid, an offer in the answer field, or an answer for
|
||||
a different code is reported without discarding the live offer. Fix it and
|
||||
click **Connect** again.
|
||||
- After a connection closes or fails, use **Reset** and exchange a new offer and
|
||||
answer. Old codes cannot reopen it.
|
||||
- If a configured STUN server is unreachable, try None for a local test. For a
|
||||
local test, use two tabs or windows, and Disconnect before changing roles.
|
||||
- Expand **Connection diagnostics** to copy the last 80 timed events: candidate
|
||||
type counts, candidate-pair and DTLS states, selected route types, and ICE
|
||||
check counters, with snapshots taken before failed pairs disappear. A `?` means
|
||||
the browser supplied no value, not zero. Addresses, SDP, candidate IDs,
|
||||
credentials, server URLs, and filenames are excluded.
|
||||
- **Finding each other.** The code puts both browsers into the same group on a public
|
||||
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
|
||||
forth. They are encrypted with the code, so the tracker can't read them, and neither can anyone
|
||||
else in the group without the code. It never sees the file. With the manual exchange you play the
|
||||
tracker yourself.
|
||||
- **Reaching each other.** Most devices sit behind a router and don't know their public address.
|
||||
A STUN server tells them. With **Use STUN** turned off no STUN server is contacted, which works
|
||||
only on the same network or over a VPN.
|
||||
|
||||
Same-machine success does not show cross-device connectivity, and error 701
|
||||
alone does not identify a cause. See [the investigation
|
||||
notes](docs/connection-investigation.md) for the comparison with the first
|
||||
version. `node scripts/compare-ice.mjs firefox` (or `chromium`) runs a local ICE
|
||||
experiment with deliberately unusable offer ports and a 20-second answer delay;
|
||||
add `--normal-candidates` to keep real ports. It is **not a cross-device test**.
|
||||
On the receiving side, HellCon hands the incoming data to the browser's own download manager while
|
||||
it arrives. That's why files larger than your memory work too, and why the download shows up in
|
||||
your browser's download list.
|
||||
|
||||
## Remembered devices
|
||||
HellCon uses no relay server. If both sides are behind very strict networks, e.g. some company or
|
||||
mobile networks, a direct connection may not be possible. And a connection that works isn't
|
||||
necessarily direct: the other side may name a relay of its own, and a STUN server that reports a
|
||||
wrong address can put itself in between. Either only passes on encrypted data. The security check
|
||||
makes sure the connection ends at the two of you.
|
||||
|
||||
Each connection can remember one device, so later sessions skip the manual
|
||||
fingerprint comparison.
|
||||
## Privacy
|
||||
|
||||
1. On both browsers, expand **Remembered device** and choose **Create device
|
||||
identity**. This also turns on **Use my device identity on this connection**;
|
||||
each connection has its own opt-in, and new connections start without it.
|
||||
2. Connect and compare full fingerprints once. Leave **Remember this device for
|
||||
…** ticked when confirming, and the verified peer is paired with this
|
||||
connection. The connection's name is the device's name and never leaves
|
||||
this browser.
|
||||
- The file only goes to the person you connected with.
|
||||
- That person learns your IP address, as with any direct connection. One STUN server and one or a
|
||||
few trackers see it too, from the request itself. HellCon tries the STUN servers in order and
|
||||
sticks with the first that answers. The sender stays on the first tracker that accepts it. The
|
||||
receiver goes down the list until it finds the sender, and the trackers it passes keep its
|
||||
encrypted offer. Nobody without the code learns your address through a tracker. The tracker the
|
||||
two of you meet on does see which addresses share with each other, and when. If that matters,
|
||||
use your own tracker and STUN server, or the manual exchange.
|
||||
- Nothing is kept: every reload starts with the default settings.
|
||||
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
|
||||
host your own (below).
|
||||
|
||||
Later sessions check fresh signed proofs bound to both device keys and both
|
||||
connection fingerprints; file acceptance is still required. A changed or missing
|
||||
identity falls back to manual comparison and only replaces the paired device if
|
||||
you tick **Replace the paired device**. **Forget device** unpairs it. One device
|
||||
can be paired with several connections.
|
||||
## Settings
|
||||
|
||||
Identity-enabled codes use signaling **v4**; temporary codes use **v3**. If only
|
||||
one peer enables identity, the session uses manual comparison without
|
||||
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).
|
||||
Under **Servers** you can change which STUN servers and trackers your browser uses, one address per
|
||||
line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults**
|
||||
brings back the original lists. The order matters: the sender stays on the first tracker that
|
||||
works, the receiver tries them in order until it finds the sender. Both lists must contain that
|
||||
tracker.
|
||||
|
||||
### Experimental reconnect without codes
|
||||
The code goes to the tracker mixed with a salt, which changes with the clock every 6 minutes (by UTC):
|
||||
guessing codes ahead of time pays off for 6 minutes at most. The code's last character tells the
|
||||
receiver which 6 minutes it was made in, so the two clocks may be up to 3 hours apart. Someone could
|
||||
still guess ahead for a particular 6 minutes. If that worries you, turn on **Use own salt** on both
|
||||
sides and enter the same salt, agreed on any way you like. **Generate** makes a random one. Nobody
|
||||
can guess ahead for a salt they don't know.
|
||||
|
||||
Once both browsers have remembered each other in a verified session:
|
||||
Nothing of this is kept, a reload brings back the defaults.
|
||||
|
||||
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.
|
||||
## Host your own
|
||||
|
||||
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
|
||||
|
||||
### Connection codes
|
||||
|
||||
Connection codes are **compressed and Base64url-encoded, not encrypted** (`HC1.`
|
||||
followed by deflated JSON). They contain SDP: candidate addresses, temporary ICE
|
||||
credentials, and certificate fingerprints. Anyone who sees a code, including the
|
||||
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.
|
||||
|
||||
File transfers use protocol **v3**; codes from older builds are rejected before
|
||||
connecting.
|
||||
|
||||
### STUN and optional TURN
|
||||
|
||||
STUN discovers externally reachable addresses. Its operator sees your public IP
|
||||
and request metadata but never file contents. Choosing None avoids contacting a
|
||||
STUN provider; direct connectivity then depends on addresses, routing, browser
|
||||
policy, and firewalls. A VPN does not guarantee against address disclosure.
|
||||
|
||||
Restrictive NATs or firewalls can block direct connections, and there is no
|
||||
silent TURN fallback. To permit a relay, both people check **Allow a TURN
|
||||
relay**, enter their authorized TURN URL, username, and password, and create new
|
||||
codes. Otherwise TURN URLs and codes with relay candidates are rejected. Enabling
|
||||
TURN lets the browser use a relay route when needed; it does not force relay-only
|
||||
routing or hide your IP from the peer, and it cannot control software the other
|
||||
person runs.
|
||||
|
||||
When a credential endpoint is configured, **Use the configured relay with
|
||||
temporary credentials** fetches fresh credentials for each connection after
|
||||
opt-in and shows them read-only. Uncheck it to enter a relay manually. TURN
|
||||
credentials stay in memory and never enter codes. The relay sees its
|
||||
authentication exchange, addresses, timing, and traffic volume, but file traffic
|
||||
remains DTLS-encrypted. Reset, cancel, or a closed connection clears TURN
|
||||
consent; opt in again for the next relayed connection.
|
||||
|
||||
### Security model and limits
|
||||
|
||||
Data channels use **SCTP over DTLS** for transport confidentiality and integrity.
|
||||
DTLS authenticates the certificate in the connection description; comparing full
|
||||
fingerprints over an independently authenticated channel binds that certificate
|
||||
to the intended peer. Comparing over a channel an attacker can rewrite proves
|
||||
nothing.
|
||||
|
||||
You must trust your browser, device, and **the JavaScript you load**. A
|
||||
compromised host or build can steal plaintext or falsify the verification
|
||||
display. HTTPS protects delivery, not against a malicious host. This code does
|
||||
not upload files to its host, but that is no guarantee against a host serving
|
||||
different code. The web host, DNS resolver, and code-exchange service are also
|
||||
relevant third parties.
|
||||
|
||||
The protocol accepts one ordered, reliable data channel with bounded metadata
|
||||
and messages, exact declared byte counts, and at most one accepted file per
|
||||
direction. Monotonic per-direction file IDs bind offers, data, and receipts to
|
||||
their files; unexpected states, excess data, and duplicate metadata are rejected.
|
||||
A 1 MiB acknowledged send window and a bounded receive queue limit buffering.
|
||||
Files are opaque downloads and metadata is never rendered as HTML. Encryption
|
||||
does not make a file safe to open. These limits reduce, but do not eliminate,
|
||||
denial-of-service and malicious-peer risks.
|
||||
|
||||
## Self-hosting
|
||||
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
|
||||
|
||||
```sh
|
||||
bun install --frozen-lockfile
|
||||
bun run build
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Serve the whole `dist/` directory over HTTPS as static files, including
|
||||
`assets/` and `download/worker.js` (with a JavaScript MIME type). No backend or
|
||||
third-party helper is needed. Do not expose the Vite dev or preview server;
|
||||
`bun run preview` is for local inspection only.
|
||||
Then serve the `dist/` folder, with these requirements:
|
||||
|
||||
Configure `Content-Security-Policy`, `X-Content-Type-Options: nosniff`, and
|
||||
`Referrer-Policy: no-referrer`. A baseline CSP for this build:
|
||||
- **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for
|
||||
trying it out).
|
||||
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
|
||||
HellCon must reach it unchanged, so don't rewrite them to `index.html`. Any path works, e.g.
|
||||
`https://example.org/hellcon/`, with the trailing slash: the page links its files relative to it,
|
||||
so redirect `/hellcon` there.
|
||||
|
||||
```text
|
||||
default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';
|
||||
img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none';
|
||||
frame-ancestors 'none'
|
||||
Recommended, as response headers, a `<meta>` can't set them (`index.html` sets
|
||||
`Referrer-Policy: no-referrer` and the rest of its Content-Security-Policy itself, which keeps out
|
||||
scripts and styles from elsewhere but allows connections to any tracker):
|
||||
|
||||
```
|
||||
Content-Security-Policy: frame-ancestors 'none'
|
||||
X-Frame-Options: DENY
|
||||
X-Content-Type-Options: nosniff
|
||||
```
|
||||
|
||||
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
|
||||
control.
|
||||
The first two keep other sites from framing HellCon and laying their own page over its buttons,
|
||||
`X-Frame-Options` for older browsers.
|
||||
|
||||
The download worker's scope is `download/` only: it does not control the app
|
||||
page, cache the app, or proxy other requests. It serves single-use, randomly
|
||||
named URLs from incoming streams with bounded buffering. Closing or resetting an
|
||||
unfinished transfer aborts it; interrupted transfers must restart.
|
||||
Your own tracker and STUN server are optional, any public ones work. `backend/` has both as Docker
|
||||
Compose services: a tracker that only does what HellCon needs, with an Origin allowlist and limits,
|
||||
and coturn as STUN server. `backend/compose.yaml` says how to set them up.
|
||||
|
||||
## Development
|
||||
If you change how HellCon talks to the other side, e.g. the code, the encryption or the messages,
|
||||
give `PROTOCOL` in `src/core.ts` a name of your own, e.g. `yourname/1`, and count up from there.
|
||||
|
||||
Use Bun to install dependencies and Node.js 22.18+ to run scripts and tests. All
|
||||
code is strict TypeScript; `vue-tsc` checks scripts and templates and runs before
|
||||
every production build. TypeScript stays on 6.0 until Vue's checker supports
|
||||
TypeScript 7. Vite 8 supplies the Rolldown bundler and Oxc transforms. Node runs
|
||||
the TypeScript tests directly, with no test framework or loader. The lockfile
|
||||
pins dependencies; review updates and advisories before publishing a build.
|
||||
## Not planned
|
||||
|
||||
```sh
|
||||
bun install --frozen-lockfile
|
||||
bun run dev
|
||||
bun run typecheck
|
||||
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
|
||||
```
|
||||
These were considered and decided against, please don't ask for them without a new reason. HellCon
|
||||
is copy and paste a code, with public trackers and STUN servers. Anything that puts state in the URL,
|
||||
needs infrastructure of its own or only helps small files doesn't pay off.
|
||||
|
||||
Browser checks run against `dist/`, so build first. They use isolated temporary
|
||||
profiles and a loopback server, and never touch your normal browser settings.
|
||||
- **The code in a share link:** the code would end up in the browser history and wherever links get
|
||||
handled, for one click less.
|
||||
- **Another code alphabet,** e.g. one that ignores case or uses words: most people copy and paste
|
||||
the code anyway.
|
||||
- **Saving without the service worker,** holding the file in memory instead: useless for files of
|
||||
several GB.
|
||||
- **TURN servers or a relay-only mode:** too much infrastructure to host and test.
|
||||
- **A longer or extendable share,** **several files as a zip,** and **resuming in Chromium:** not
|
||||
for now.
|
||||
- **Keeping a phone sending in the background,** e.g. with a silent audio loop: the sender's page
|
||||
has to stay in front.
|
||||
|
||||
- `test:browser` and `test:download` need Chromium at `/usr/bin/chromium`
|
||||
(override with `CHROMIUM_PATH`, e.g. `/usr/bin/brave`). They verify the actual
|
||||
saved bytes; worker tests cover byte counts, backpressure, single-use URLs, and
|
||||
cancellation.
|
||||
- `test:cross-browser` needs `/usr/bin/brave` and `/usr/bin/firefox` (override
|
||||
with `BRAVE_PATH` and `FIREFOX_PATH`) and checks the received file stays
|
||||
downloadable after the sender disconnects. Pass `--reverse` for Firefox →
|
||||
Brave, or `--default-network` for PageQuit STUN instead of None.
|
||||
## Known limitations
|
||||
|
||||
### Local STUN/TURN (Linux)
|
||||
|
||||
Vite stays on the host for hot reload; only coturn runs in Docker. Both bind to
|
||||
loopback, so test with two tabs on this machine. Nothing starts at boot and the
|
||||
container has no restart policy.
|
||||
|
||||
```sh
|
||||
sudo systemctl start docker.service # if not already running
|
||||
# After joining the docker group, log in again or run: newgrp docker
|
||||
bun install --frozen-lockfile
|
||||
bun run dev:setup # creates .env.development without overwriting it
|
||||
bun run turn:up
|
||||
bun run dev # open the printed URL in two tabs
|
||||
```
|
||||
|
||||
Pick a file in one tab and choose Receive in the other. Check **Allow a TURN
|
||||
relay** in both, leave **Use the configured relay with temporary credentials**
|
||||
checked, then exchange codes as usual. Consent clears after each connection.
|
||||
|
||||
```sh
|
||||
bun run test:turn # real file transfer over forced TURN/UDP
|
||||
bun run test:turn --tcp # browser-to-TURN over TCP only
|
||||
docker compose --env-file .env.development logs --tail=50 coturn
|
||||
bun run turn:down
|
||||
sudo systemctl stop docker.service docker.socket containerd.service # optional
|
||||
```
|
||||
|
||||
The TURN checks start their own Vite server and browsers but need coturn
|
||||
running. They force relay-only routing, assert relay candidates on both ends,
|
||||
verify received bytes and receipts, and exercise cancellation and reconnection.
|
||||
They do not test Internet NATs or a remote firewall.
|
||||
|
||||
`.env.development` holds the private `TURN_SECRET`, server-side
|
||||
`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` (see
|
||||
[.env.example](.env.example)). The secret never enters the client bundle. When
|
||||
changing the port, update `TURN_PORT` and `VITE_STUN_URL`, rerun `turn:up`, and
|
||||
restart Vite. Listeners, relay ports 49160–49200, and the pinned image are in
|
||||
[compose.yaml](compose.yaml).
|
||||
|
||||
The credential endpoint is **development-only** Vite middleware and is not part
|
||||
of `dist/` or `vite preview`. To use it in production, set `VITE_ICE_ENDPOINT`
|
||||
and `VITE_STUN_URL` at build time and implement the same JSON endpoint behind
|
||||
your own access policy; [dev/ice-server.ts](dev/ice-server.ts) has the HMAC
|
||||
logic. Never expose the development endpoint or the loopback-permitting Compose
|
||||
setup as a public relay. Credentials expire after one hour and are not renewed
|
||||
during a transfer. See the [coturn Docker
|
||||
guide](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md) and
|
||||
[configuration
|
||||
reference](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf).
|
||||
|
||||
### Local WebTorrent tracker
|
||||
|
||||
[tracker/Dockerfile](tracker/Dockerfile) and
|
||||
[compose.tracker.yaml](compose.tracker.yaml) build a locked `bittorrent-tracker`
|
||||
release on the official Node image:
|
||||
|
||||
```sh
|
||||
bun run tracker:up # build and start ws://127.0.0.1:8000
|
||||
bun run test:tracker # integration checks inside the test image
|
||||
bun run tracker:down
|
||||
```
|
||||
|
||||
See [the tracker README](tracker/README.md) for configuration and VPS use.
|
||||
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
|
||||
|
||||
See [the hosted-first UX roadmap](docs/ux-roadmap.md).
|
||||
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
|
||||
but Firefox keeps showing the download as in progress until you cancel it.
|
||||
- **Chromium:** notices a vanished sender only after about 16 seconds.
|
||||
- An interrupted transfer can't be resumed, it starts over.
|
||||
- **Phones:** the sender's page has to stay in front, the connection is lost once it goes to the
|
||||
background. Receiving keeps going.
|
||||
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
|
||||
work, and HellCon tells you so.
|
||||
|
||||
## License
|
||||
|
||||
MIT — see [LICENSE](LICENSE).
|
||||
MIT, see [LICENSE](LICENSE).
|
||||
@@ -0,0 +1,47 @@
|
||||
# TODO
|
||||
|
||||
## Ideas
|
||||
|
||||
- Resume interrupted transfers: the receiver already reports how much the download manager has
|
||||
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
|
||||
finished or failed download though, so a resume would have to start a new one.
|
||||
|
||||
- Keep user settings again: for now every reload starts from the defaults, the server lists and the
|
||||
own salt too. Open which ones to keep, and how a kept one that differs from the other side's would
|
||||
show, instead of silently breaking a share.
|
||||
|
||||
- Revisit the screen wake lock: a browser that keeps refusing it (e.g. in a power saving mode) logs
|
||||
"screen may lock" each time the page is visible again, open whether once per session is enough.
|
||||
`awake: …` doesn't cover a session that ends in an error, nor one that ends while a request is
|
||||
still pending, the case the `wakeLock === request` checks in `holdWakeLock` are for.
|
||||
|
||||
## Open observations
|
||||
|
||||
- A phone can't send in the background: with Brave on Android (Pixel), the connection is lost as
|
||||
soon as the sender's page goes to the background. Receiving survives it, likely because the
|
||||
browser's download manager runs as a foreground service while the file streams into it. The wake
|
||||
lock only keeps the screen from timing out, the sender's page has to stay in front.
|
||||
|
||||
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
|
||||
logs "download failed: connection lost", but the download stays "in progress" until the user
|
||||
cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
|
||||
complete despite `Content-Length`. Chromium fails the download, but only once the connection
|
||||
counts as failed (~16 s), because its data channel never fires `close` for a vanished peer.
|
||||
|
||||
- Firefox also saves a truncated file as complete when it stops the service worker in the middle of
|
||||
a download (after 30 s without events). The receiver's pings (`KEEPALIVE`) prevent that, covered by
|
||||
`large: firefox survives a 40 s stall`. A browser that stops it anyway would still never show
|
||||
"download complete" or "delivered", only its download manager would be wrong.
|
||||
|
||||
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite),
|
||||
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
|
||||
happens again.
|
||||
|
||||
- Small downloads (empty, one byte) were sometimes never saved, though the worker reported them
|
||||
finished and both sides logged success: the browser can read the whole response before it hands
|
||||
the navigation to its download manager, and removing the frame before that cancels it. Without a
|
||||
delay `boundary: … sends an empty file` failed 8 of 10 runs, the one byte file 4 of 10. The
|
||||
workaround `DOWNLOAD_GRACE` keeps the download's frame 1 s after finished. No event tells when the
|
||||
browser took the download, so the 1 s is empirical: `boundary: … keeps a finished download's frame
|
||||
for DOWNLOAD_GRACE` covers the retention, not the browser's timing. A small download that goes
|
||||
missing again means it's too short.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Copy to .env next to compose.yaml and adjust.
|
||||
|
||||
# Where HellCon is served from, as browsers send it in the Origin header: scheme, host and port if not
|
||||
# the default, no path and no trailing slash. Several separated by commas or spaces. The tracker refuses
|
||||
# every other origin.
|
||||
ORIGINS=https://hellcon.example.org
|
||||
|
||||
# The external network Caddy is on, "caddy" if unset.
|
||||
#CADDY_NETWORK=caddy
|
||||
|
||||
# Whose X-Forwarded-For the tracker believes, addresses or CIDRs separated by commas or spaces. Every
|
||||
# private range if unset, see compose.yaml. Narrow it to Caddy's address in CADDY_NETWORK, but keep it
|
||||
# covered: otherwise all clients count as Caddy's and share its limits, nearly all are refused.
|
||||
#PROXIES=172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 fd00::/8
|
||||
@@ -0,0 +1,6 @@
|
||||
FROM node:26.13.1-alpine3.23
|
||||
WORKDIR /app
|
||||
RUN npm install --no-save --omit=dev ws@8.23.0
|
||||
COPY tracker.mjs .
|
||||
USER node
|
||||
CMD ["node", "--max-old-space-size=48", "tracker.mjs"]
|
||||
@@ -0,0 +1,79 @@
|
||||
# HellCon's own servers: a tracker behind Caddy and a STUN server. Neither is needed, the client works
|
||||
# with any WebTorrent tracker and STUN server. Copy .env.example to .env and set ORIGINS there, then
|
||||
# `docker compose up -d --build`. Caddy, in its own compose
|
||||
# project, proxies to the tracker over its network (CADDY_NETWORK, "caddy" unless set):
|
||||
#
|
||||
# tracker.example.org {
|
||||
# reverse_proxy hellcon-tracker:8000
|
||||
# }
|
||||
|
||||
name: hellcon
|
||||
|
||||
x-logging: &logging
|
||||
driver: json-file
|
||||
options: { max-size: 10m, max-file: '2' }
|
||||
|
||||
services:
|
||||
tracker:
|
||||
build: .
|
||||
environment:
|
||||
ORIGINS: ${ORIGINS:?set ORIGINS in .env to where HellCon is served from}
|
||||
# Whose X-Forwarded-For the tracker believes, addresses or CIDRs, see clientIp in tracker.mjs.
|
||||
# Caddy reaches it over the shared network, whose subnet is Docker's choice, so the default
|
||||
# trusts every private range: nothing public should reach the tracker besides Caddy. Set
|
||||
# PROXIES in .env to narrow it, e.g. to your Caddy's address in that network. If it doesn't
|
||||
# cover Caddy's address, all clients count as Caddy's and share its limits, nearly all are refused.
|
||||
PROXIES: ${PROXIES:-172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 fd00::/8}
|
||||
networks:
|
||||
caddy:
|
||||
aliases: [hellcon-tracker]
|
||||
init: true
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
cpus: 0.5
|
||||
mem_limit: 96m
|
||||
memswap_limit: 96m
|
||||
pids_limit: 32
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
# On the host network, so Docker's NAT can't change the source address clients get back. UDP 3478
|
||||
# on IPv4 and IPv6, stun.example.org needs an A and an AAAA record. Browsers hide their own addresses,
|
||||
# only STUN reports an IPv6 one, and mobile networks behind carrier NAT often only connect over IPv6.
|
||||
coturn:
|
||||
image: coturn/coturn:4.18.0
|
||||
network_mode: host
|
||||
# Off by default since 4.18, their --no- options are gone: DTLS, the admin CLI, the software
|
||||
# attribute, the RFC 3489 MAPPED-ADDRESS and logging each binding request. The image has no config
|
||||
# file, -n would only fail with "Unknown argument".
|
||||
command:
|
||||
- --log-file=stdout
|
||||
- --listening-ip=0.0.0.0
|
||||
- --listening-ip=::
|
||||
- --listening-port=3478
|
||||
- --stun-only
|
||||
- --no-tcp
|
||||
- --no-tls
|
||||
# One per CPU core otherwise, more than cpus allows.
|
||||
- --relay-threads=1
|
||||
# The pid file lands in /var/tmp, coturn can't write /var/run. The image declares /var/lib/coturn
|
||||
# a volume, the tmpfs keeps an anonymous one from piling up.
|
||||
tmpfs: [/var/lib/coturn, /var/tmp]
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
# turnserver has it as file capability, without it the kernel refuses to run it. 3478 doesn't need
|
||||
# it, no-new-privileges keeps it from being granted.
|
||||
cap_add: [NET_BIND_SERVICE]
|
||||
security_opt: [no-new-privileges:true]
|
||||
cpus: 1
|
||||
mem_limit: 128m
|
||||
memswap_limit: 128m
|
||||
pids_limit: 64
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
caddy:
|
||||
external: true
|
||||
name: ${CADDY_NETWORK:-caddy}
|
||||
@@ -0,0 +1,351 @@
|
||||
// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
|
||||
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
|
||||
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
|
||||
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged
|
||||
// but one warning about PROXIES, without any address.
|
||||
import { createServer } from 'node:http';
|
||||
import { BlockList, isIP } from 'node:net';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
// Read on import, 0 picks a free one, see server.address().
|
||||
const PORT = Number(process.env.PORT ?? 8000);
|
||||
// Where HellCon is served from, separated by commas or spaces. Anything else is refused. Read on every
|
||||
// connection, so test files sharing one process can each allow their own.
|
||||
const allowed = (origin) =>
|
||||
(process.env.ORIGINS ?? '')
|
||||
.split(/[\s,]+/)
|
||||
.filter(Boolean)
|
||||
.includes(origin);
|
||||
// Seconds. Peers last as long as their connection, announcing again only resends a receiver's offer,
|
||||
// e.g. to a sender that was busy with another receiver.
|
||||
const INTERVAL = 60;
|
||||
// A sealed SDP is a few KiB.
|
||||
const MAX_MESSAGE = 16 * 1024;
|
||||
// Per connection: messages within RATE_WINDOW, bytes of SDP it gets forwarded and its lifetime. HellCon
|
||||
// gives up a share or a search after 6 minutes.
|
||||
const MAX_MESSAGES = 10;
|
||||
const RATE_WINDOW = 10_000;
|
||||
const MAX_FORWARDED = 64 * 1024;
|
||||
// A positive number from the environment, read on every use like ORIGINS, so the spec can lower it
|
||||
// to a testable moment. 0 or a typo would cut every connection short, the default stands then.
|
||||
const fromEnv = (name, fallback) => {
|
||||
const value = Number(process.env[name]);
|
||||
return value > 0 ? value : fallback;
|
||||
};
|
||||
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
|
||||
// a peer that reads never gets near it.
|
||||
const MAX_QUEUED = 32 * 1024;
|
||||
// The same for all peers together: MAX_QUEUED for each of MAX_CONNECTIONS would be 32 MiB against
|
||||
// mem_limit. A quarter of them can still fill theirs.
|
||||
const maxQueuedAll = () => fromEnv('MAX_QUEUED_ALL', 8 * 1024 * 1024);
|
||||
const MAX_AGE = 7 * 60_000;
|
||||
// A connection that announced nothing by then only holds a slot: 1024 of them would serve nobody
|
||||
// for MAX_AGE.
|
||||
const maxSilent = () => fromEnv('MAX_SILENT', 30_000);
|
||||
const MAX_CONNECTIONS = 1024;
|
||||
const MAX_PER_IP = 16;
|
||||
// Per address and window, across its connections: MAX_PER_IP is only at once, MAX_FORWARDED only one
|
||||
// connection, so a client that reconnects would otherwise get a fresh allowance for each. The window
|
||||
// is long enough for a search to walk the trackers and to reannounce, short enough to cap a relay.
|
||||
// Relaying through many addresses, e.g. the /64s of one /48, is accepted: other WebTorrent trackers
|
||||
// relay anything anyway, the caps only keep one address from using this one's bandwidth.
|
||||
const maxConnectsPerIp = () => fromEnv('MAX_CONNECTS_PER_IP', 120);
|
||||
const maxForwardedPerIp = () => fromEnv('MAX_FORWARDED_PER_IP', 1024 * 1024);
|
||||
const IP_WINDOW = 60_000;
|
||||
// A record without open connections lives until its window is over, a churning client could pile up
|
||||
// many: past a few thousand, the oldest closed ones go. An address dropping out only forgets its
|
||||
// rate, the concurrent limit still holds.
|
||||
const maxIps = () => fromEnv('MAX_IPS', 4 * MAX_CONNECTIONS);
|
||||
// A share has one sender, receivers keep one connection per tracker.
|
||||
const MAX_SWARM = 8;
|
||||
// Offers a sender got and may still answer, the oldest go first.
|
||||
const MAX_PENDING = 32;
|
||||
|
||||
// info_hash → peer_id → peer.
|
||||
const swarms = new Map();
|
||||
// address → { open, connects, forwarded, since }, see usage.
|
||||
const perIp = new Map();
|
||||
let connections = 0;
|
||||
// Peers that were sent something and may still have it queued, see fits.
|
||||
const queued = new Set();
|
||||
|
||||
// info_hash, peer_id and offer_id are 20 byte binary strings.
|
||||
const isId = (value) => typeof value === 'string' && value.length === 20;
|
||||
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
|
||||
|
||||
// Whose X-Forwarded-For to believe, PROXIES' addresses or CIDRs. Read on every connection, like
|
||||
// ORIGINS. An entry that is none is left out, as is an empty prefix: it would be 0, all of IPv4.
|
||||
function proxies() {
|
||||
const list = new BlockList();
|
||||
for (const entry of (process.env.PROXIES ?? '').split(/[\s,]+/).filter(Boolean)) {
|
||||
const [base, prefix] = entry.split('/');
|
||||
const type = { 4: 'ipv4', 6: 'ipv6' }[isIP(base)];
|
||||
if (!type) continue;
|
||||
if (prefix === undefined) list.addAddress(base, type);
|
||||
else if (/^\d+$/.test(prefix) && prefix <= (type === 'ipv4' ? 32 : 128)) list.addSubnet(base, Number(prefix), type);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// Once: behind a proxy PROXIES doesn't cover, every client counts as the proxy and shares its limits.
|
||||
let warned = false;
|
||||
|
||||
// The client's address for the per-IP limits. A client that reaches the tracker directly names any
|
||||
// address it likes in X-Forwarded-For, so without a listed proxy only the socket's own counts. Behind
|
||||
// a listed proxy, like Caddy on the compose file's network, the last entry is the client's, whatever
|
||||
// the client put before it. IPv6 counts by /64: a single host usually has a whole one, every address
|
||||
// in it would get an allowance of its own. IPv4, also mapped to IPv6, counts as it is.
|
||||
function clientIp(req) {
|
||||
const peer = req.socket.remoteAddress;
|
||||
const header = req.headers['x-forwarded-for'];
|
||||
// BlockList matches IPv4 rules against IPv4-mapped addresses too.
|
||||
const trusted = isIP(peer) && proxies().check(peer, isIP(peer) === 4 ? 'ipv4' : 'ipv6');
|
||||
if (header && !trusted && !warned) {
|
||||
warned = true;
|
||||
console.warn('X-Forwarded-For from an address PROXIES does not cover, ignored. Behind a proxy, add it.');
|
||||
}
|
||||
const forwarded = trusted ? header?.split(',').at(-1).trim() : undefined;
|
||||
const ip = isIP(forwarded) ? forwarded : peer;
|
||||
if (!isIP(ip)) return 'unknown';
|
||||
if (ip.includes('.')) return ip.replace(/^::ffff:/i, '');
|
||||
const [head, tail] = ip.split('::');
|
||||
const groups = head ? head.split(':') : [];
|
||||
if (tail !== undefined) {
|
||||
const rest = tail ? tail.split(':') : [];
|
||||
groups.push(...Array(Math.max(0, 8 - groups.length - rest.length)).fill('0'), ...rest);
|
||||
}
|
||||
return `${groups
|
||||
.slice(0, 4)
|
||||
.map((group) => parseInt(group, 16).toString(16))
|
||||
.join(':')}::/64`;
|
||||
}
|
||||
|
||||
// The address's record for the current window. Open connections stay counted across a reset, what it
|
||||
// used starts over. A record without open connections is dropped by the sweep once its window is over.
|
||||
function usage(ip) {
|
||||
const now = Date.now();
|
||||
let record = perIp.get(ip);
|
||||
if (!record) {
|
||||
// Room for the new one. At most MAX_CONNECTIONS records have an open connection, so with room to
|
||||
// spare above that there is always a closed one to drop.
|
||||
const limit = maxIps();
|
||||
for (const [old, other] of perIp) {
|
||||
if (perIp.size < limit) break;
|
||||
if (!other.open) perIp.delete(old);
|
||||
}
|
||||
record = { open: 0, connects: 0, forwarded: 0, since: now };
|
||||
perIp.set(ip, record);
|
||||
} else if (now - record.since >= IP_WINDOW) {
|
||||
record.connects = 0;
|
||||
record.forwarded = 0;
|
||||
record.since = now;
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
function refuse(socket, status) {
|
||||
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
|
||||
}
|
||||
|
||||
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
|
||||
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
|
||||
// wait for its close frame. Past maxQueuedAll() for all of them, the largest queues go first: a peer
|
||||
// that reads has next to nothing queued, so one without a queue never goes for the others'.
|
||||
function fits(peer, bytes) {
|
||||
if (peer.ws.readyState !== peer.ws.OPEN) return false;
|
||||
if (peer.ws.bufferedAmount + bytes > MAX_QUEUED) return drop(peer);
|
||||
let total = bytes;
|
||||
for (const other of queued) {
|
||||
if (other.ws.bufferedAmount) total += other.ws.bufferedAmount;
|
||||
else queued.delete(other);
|
||||
}
|
||||
queued.add(peer);
|
||||
if (total > maxQueuedAll()) {
|
||||
for (const other of [...queued].sort((a, b) => b.ws.bufferedAmount - a.ws.bufferedAmount)) {
|
||||
if (total <= maxQueuedAll() || !other.ws.bufferedAmount) break;
|
||||
total -= other.ws.bufferedAmount;
|
||||
drop(other);
|
||||
}
|
||||
}
|
||||
return peer.ws.readyState === peer.ws.OPEN;
|
||||
}
|
||||
|
||||
// Its queue goes with the socket.
|
||||
function drop(peer) {
|
||||
peer.ws.terminate();
|
||||
queued.delete(peer);
|
||||
return false;
|
||||
}
|
||||
|
||||
function send(peer, message) {
|
||||
const data = JSON.stringify(message);
|
||||
if (fits(peer, Buffer.byteLength(data))) peer.ws.send(data);
|
||||
}
|
||||
|
||||
// HellCon shows the reason, the connection closes.
|
||||
function reject(peer, reason) {
|
||||
send(peer, { 'failure reason': reason });
|
||||
peer.ws.close();
|
||||
}
|
||||
|
||||
function forward(from, to, message, sdp) {
|
||||
from.forwarded += sdp.length;
|
||||
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
|
||||
const used = usage(from.ip);
|
||||
used.forwarded += sdp.length;
|
||||
if (used.forwarded > maxForwardedPerIp()) return reject(from, 'too much signaling');
|
||||
send(to, message);
|
||||
}
|
||||
|
||||
function announce(peer, msg) {
|
||||
const { info_hash: hash, peer_id: id } = msg;
|
||||
if (msg.action !== 'announce' || !isId(hash) || !isId(id)) return reject(peer, 'invalid announce');
|
||||
if (!peer.id) {
|
||||
const swarm = swarms.get(hash) ?? new Map();
|
||||
if (swarm.has(id)) return reject(peer, 'peer_id taken');
|
||||
if (swarm.size >= MAX_SWARM) return reject(peer, 'swarm full');
|
||||
swarms.set(hash, swarm.set(id, peer));
|
||||
peer.id = id;
|
||||
peer.hash = hash;
|
||||
clearTimeout(peer.silent);
|
||||
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
|
||||
if (msg.event === 'stopped') return peer.ws.close();
|
||||
peer.seeder = msg.left === 0;
|
||||
const swarm = swarms.get(hash);
|
||||
|
||||
if (msg.offers !== undefined) {
|
||||
const [offer, ...more] = Array.isArray(msg.offers) ? msg.offers : [];
|
||||
if (more.length || (offer && (!isId(offer.offer_id) || !isSdp(offer.offer, 'offer')))) {
|
||||
return reject(peer, 'invalid offer');
|
||||
}
|
||||
const senders = [...swarm.values()].filter((other) => other.seeder && other !== peer);
|
||||
const sender = senders[Math.floor(Math.random() * senders.length)];
|
||||
if (offer && sender) {
|
||||
sender.pending.delete(offer.offer_id);
|
||||
sender.pending.set(offer.offer_id, peer);
|
||||
if (sender.pending.size > MAX_PENDING) sender.pending.delete(sender.pending.keys().next().value);
|
||||
const { sdp } = offer.offer;
|
||||
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: offer.offer_id };
|
||||
forward(peer, sender, { ...message, offer: { type: 'offer', sdp } }, sdp);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.answer !== undefined) {
|
||||
if (!isId(msg.to_peer_id) || !isId(msg.offer_id) || !isSdp(msg.answer, 'answer')) {
|
||||
return reject(peer, 'invalid answer');
|
||||
}
|
||||
const receiver = peer.pending.get(msg.offer_id);
|
||||
// An offer it never got, answered already or whose receiver left: dropped, a stray answer doesn't
|
||||
// cost the share.
|
||||
if (receiver?.id === msg.to_peer_id) {
|
||||
peer.pending.delete(msg.offer_id);
|
||||
const { sdp } = msg.answer;
|
||||
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: msg.offer_id };
|
||||
forward(peer, receiver, { ...message, answer: { type: 'answer', sdp } }, sdp);
|
||||
}
|
||||
}
|
||||
|
||||
// complete counts the seeders, HellCon's receiver moves on to its next tracker without one.
|
||||
if (peer.ws.readyState === peer.ws.OPEN) {
|
||||
const complete = [...swarm.values()].filter((other) => other.seeder).length;
|
||||
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash, complete });
|
||||
}
|
||||
}
|
||||
|
||||
function open(ws, ip) {
|
||||
const peer = {
|
||||
ws,
|
||||
ip,
|
||||
id: undefined,
|
||||
hash: undefined,
|
||||
seeder: false,
|
||||
pending: new Map(),
|
||||
forwarded: 0,
|
||||
messages: 0,
|
||||
// Terminated, close would keep the slot for ws's 30 s more if the client ignores the close
|
||||
// frame. A peer that never announced has nothing to say goodbye to.
|
||||
silent: setTimeout(() => ws.terminate(), maxSilent()),
|
||||
};
|
||||
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
|
||||
const age = setTimeout(() => ws.close(), MAX_AGE);
|
||||
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
|
||||
ws.on('error', () => {});
|
||||
// Pings and pongs count as messages. ws would answer every ping on its own, past the limits.
|
||||
const counted = () => ++peer.messages <= MAX_MESSAGES || reject(peer, 'too many messages');
|
||||
ws.on('ping', (data) => counted() && fits(peer, data.length) && ws.pong(data));
|
||||
ws.on('pong', counted);
|
||||
ws.on('message', (data, binary) => {
|
||||
if (!counted()) return;
|
||||
let msg;
|
||||
try {
|
||||
msg = binary ? undefined : JSON.parse(data);
|
||||
} catch {}
|
||||
if (!msg || typeof msg !== 'object') return reject(peer, 'invalid message');
|
||||
announce(peer, msg);
|
||||
});
|
||||
ws.on('close', () => {
|
||||
clearInterval(rate);
|
||||
clearTimeout(age);
|
||||
clearTimeout(peer.silent);
|
||||
queued.delete(peer);
|
||||
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
|
||||
peer.pending.clear();
|
||||
const swarm = swarms.get(peer.hash);
|
||||
if (swarm?.get(peer.id) !== peer) return;
|
||||
swarm.delete(peer.id);
|
||||
if (!swarm.size) swarms.delete(peer.hash);
|
||||
// Its offers go only to peers of its swarm.
|
||||
for (const other of swarm.values()) {
|
||||
for (const [offerId, receiver] of other.pending) if (receiver === peer) other.pending.delete(offerId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
|
||||
// Plain requests aren't counted below, only upgraded ones are, so Node's own limits keep them from
|
||||
// piling up, each one's kernel buffers against mem_limit. Node checks headersTimeout and
|
||||
// requestTimeout every connectionsCheckingInterval, 30 s unless set. headersTimeout starts only once
|
||||
// something arrived, the idle timeout on every connection covers one that sends nothing, cleared
|
||||
// for an accepted upgrade: HellCon's peers sit out their announce interval. The 404 closes the
|
||||
// socket, nothing of it stays for a keep-alive. maxConnections caps all sockets, plain ones
|
||||
// included: beyond it Node drops new ones without a response, the one place a client gets a bare
|
||||
// connection error instead of a 503.
|
||||
export const server = createServer({ connectionsCheckingInterval: 5_000 }, (_, res) =>
|
||||
res.writeHead(404, { Connection: 'close' }).end(),
|
||||
);
|
||||
server.on('connection', (socket) => socket.setTimeout(10_000, () => socket.destroy()));
|
||||
server.headersTimeout = 10_000;
|
||||
server.requestTimeout = 30_000;
|
||||
server.maxHeadersCount = 100;
|
||||
server.maxConnections = 2 * MAX_CONNECTIONS;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
|
||||
// client resetting a refused connection would end the process.
|
||||
socket.on('error', () => {});
|
||||
const ip = clientIp(req);
|
||||
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
|
||||
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
|
||||
const used = usage(ip);
|
||||
if (used.open >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
|
||||
// Closing a connection doesn't give the address its allowance back.
|
||||
if (used.connects >= maxConnectsPerIp()) return refuse(socket, '429 Too Many Requests');
|
||||
// Counted on the socket, so an upgrade that fails is released too.
|
||||
connections++;
|
||||
used.open++;
|
||||
used.connects++;
|
||||
socket.once('close', () => {
|
||||
connections--;
|
||||
used.open--;
|
||||
});
|
||||
// A peer sits out its announce interval, the idle timeout is over for it.
|
||||
socket.setTimeout(0);
|
||||
wss.handleUpgrade(req, socket, head, (ws) => open(ws, ip));
|
||||
});
|
||||
// An address's window only matters while something of it is open or recent. Once its last connection
|
||||
// is gone and its window over, the record goes: nothing else would ever delete it.
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [ip, record] of perIp) if (!record.open && now - record.since >= IP_WINDOW) perIp.delete(ip);
|
||||
}, IP_WINDOW);
|
||||
sweep.unref();
|
||||
server.listen(PORT);
|
||||
@@ -0,0 +1,540 @@
|
||||
// The tracker on its own, without browsers: what it forwards, what it refuses and what it keeps.
|
||||
// tracker.mjs runs in the worker on a free port. e2e.spec.ts sends a real file through it.
|
||||
import { once } from 'node:events';
|
||||
import { connect as connectTcp } from 'node:net';
|
||||
import { queryObjects } from 'node:v8';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { WebSocket as ServerSocket } from 'ws';
|
||||
|
||||
const ORIGIN = 'https://hellcon.test';
|
||||
let server;
|
||||
let url;
|
||||
// Every connection a test opened, closed after it.
|
||||
let clients = [];
|
||||
// Each test connects from its own address, the tracker takes it from X-Forwarded-For. Otherwise
|
||||
// connections of the previous test, still closing, would count against the per-IP limit.
|
||||
let ip;
|
||||
let tests = 0;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
process.env.PORT = '0';
|
||||
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`;
|
||||
// The tracker believes this test's X-Forwarded-For like Caddy's.
|
||||
process.env.PROXIES = '127.0.0.1';
|
||||
// Reconnecting tests pass the per-address limits on purpose, the ones about them lower them.
|
||||
process.env.MAX_CONNECTS_PER_IP = '100000';
|
||||
process.env.MAX_FORWARDED_PER_IP = String(64 * 1024 * 1024);
|
||||
({ server } = await import('./tracker.mjs'));
|
||||
if (!server.listening) await once(server, 'listening');
|
||||
url = `ws://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
|
||||
// e2e.spec.ts may run next in this worker, with the tracker as it is deployed.
|
||||
test.afterAll(() => {
|
||||
delete process.env.PROXIES;
|
||||
delete process.env.MAX_CONNECTS_PER_IP;
|
||||
delete process.env.MAX_FORWARDED_PER_IP;
|
||||
});
|
||||
|
||||
test.beforeEach(() => {
|
||||
ip = `198.51.100.${++tests}`;
|
||||
});
|
||||
|
||||
test.afterEach(async () => {
|
||||
for (const client of clients) client.ws.close();
|
||||
await Promise.all(clients.map((client) => client.closed));
|
||||
clients = [];
|
||||
});
|
||||
|
||||
// fn with the environment variables in vars, undefined for unset, as they were again after it.
|
||||
async function withEnv(vars, fn) {
|
||||
const set = (name, value) => {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
};
|
||||
const was = Object.keys(vars).map((name) => [name, process.env[name]]);
|
||||
for (const [name, value] of Object.entries(vars)) set(name, value);
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
for (const [name, value] of was) set(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
const id = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(20)));
|
||||
const sdp = (type, text = type) => ({ type, sdp: text });
|
||||
|
||||
// A connection like HellCon's, without one if the tracker refused it. Its messages queue up in
|
||||
// messages, closed resolves with the close code.
|
||||
function open({ origin = ORIGIN, xff = ip } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': xff } });
|
||||
const client = { ws, messages: [], closed: once(ws, 'close').then(([event]) => event.code) };
|
||||
ws.addEventListener('message', ({ data }) => client.messages.push(JSON.parse(data)));
|
||||
ws.addEventListener('open', () => {
|
||||
clients.push(client);
|
||||
resolve(client);
|
||||
});
|
||||
ws.addEventListener('error', () => resolve(undefined));
|
||||
});
|
||||
}
|
||||
|
||||
// Takes the first message that matches, once one came. open queues each before this sees it.
|
||||
async function take(client, match) {
|
||||
while (!client.messages.some(match)) await once(client.ws, 'message');
|
||||
return client.messages.splice(client.messages.findIndex(match), 1)[0];
|
||||
}
|
||||
|
||||
// Announces and waits for the tracker's reply. Whatever it forwarded to this peer before is in
|
||||
// messages by then, so a test can tell that something was not forwarded.
|
||||
async function announce(client, fields) {
|
||||
client.ws.send(JSON.stringify({ action: 'announce', numwant: 0, uploaded: 0, downloaded: 0, ...fields }));
|
||||
return take(client, (msg) => 'interval' in msg);
|
||||
}
|
||||
|
||||
// Sends raw and expects the tracker to reject it with reason, then close.
|
||||
async function rejected(client, data, reason) {
|
||||
client.ws.send(typeof data === 'string' || data instanceof Uint8Array ? data : JSON.stringify(data));
|
||||
expect((await take(client, (msg) => 'failure reason' in msg))['failure reason']).toBe(reason);
|
||||
await client.closed;
|
||||
}
|
||||
|
||||
// A swarm with a sender, a receiver and their peer ids.
|
||||
async function swarm() {
|
||||
const hash = id();
|
||||
const sender = { ...(await open()), id: id() };
|
||||
const receiver = { ...(await open()), id: id() };
|
||||
await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0, event: 'started' });
|
||||
await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, event: 'started' });
|
||||
return { hash, sender, receiver };
|
||||
}
|
||||
|
||||
// The receiver's offer, as the sender got it.
|
||||
async function offer({ hash, sender, receiver }, offerId = id()) {
|
||||
await announce(receiver, {
|
||||
info_hash: hash,
|
||||
peer_id: receiver.id,
|
||||
left: 1,
|
||||
offers: [{ offer_id: offerId, offer: sdp('offer') }],
|
||||
});
|
||||
return take(sender, (msg) => msg.offer);
|
||||
}
|
||||
|
||||
const answer = ({ hash, sender }, to, offerId, text = 'answer') =>
|
||||
announce(sender, {
|
||||
info_hash: hash,
|
||||
peer_id: sender.id,
|
||||
left: 0,
|
||||
to_peer_id: to,
|
||||
offer_id: offerId,
|
||||
answer: sdp('answer', text),
|
||||
});
|
||||
|
||||
test('refuses connections from other origins', async () => {
|
||||
expect(await open({ origin: 'https://evil.test' })).toBeUndefined();
|
||||
expect(await open({ origin: '' })).toBeUndefined();
|
||||
});
|
||||
|
||||
test('acknowledges an announce with the interval and the seeders only', async () => {
|
||||
const client = await open();
|
||||
const hash = id();
|
||||
expect(await announce(client, { info_hash: hash, peer_id: id(), left: 0 })).toEqual({
|
||||
action: 'announce',
|
||||
interval: 60,
|
||||
info_hash: hash,
|
||||
complete: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test('counts the seeders of the swarm in complete', async () => {
|
||||
const hash = id();
|
||||
const receiver = { ...(await open()), id: id() };
|
||||
const seeders = async () => (await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1 })).complete;
|
||||
expect(await seeders()).toBe(0);
|
||||
// Another swarm's sender doesn't count.
|
||||
await announce(await open(), { info_hash: id(), peer_id: id(), left: 0 });
|
||||
const sender = { ...(await open()), id: id() };
|
||||
await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0 });
|
||||
expect(await seeders()).toBe(1);
|
||||
// Gone once the tracker saw the connection close, which may be after the client did.
|
||||
sender.ws.close();
|
||||
await expect.poll(seeders).toBe(0);
|
||||
});
|
||||
|
||||
test('forwards an offer to the sender only, rebuilt from its checked fields', async () => {
|
||||
const peers = await swarm();
|
||||
const other = { ...(await open()), id: id() };
|
||||
await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 });
|
||||
const offerId = id();
|
||||
await announce(peers.receiver, {
|
||||
info_hash: peers.hash,
|
||||
peer_id: peers.receiver.id,
|
||||
left: 1,
|
||||
offers: [{ offer_id: offerId, offer: { ...sdp('offer'), extra: 1 } }],
|
||||
extra: 1,
|
||||
});
|
||||
expect(await take(peers.sender, (msg) => msg.offer)).toEqual({
|
||||
action: 'announce',
|
||||
info_hash: peers.hash,
|
||||
peer_id: peers.receiver.id,
|
||||
offer_id: offerId,
|
||||
offer: sdp('offer'),
|
||||
});
|
||||
await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 });
|
||||
expect(other.messages).toEqual([]);
|
||||
});
|
||||
|
||||
test('forwards an answer once, only to whoever sent the offer', async () => {
|
||||
const peers = await swarm();
|
||||
const { offer_id } = await offer(peers);
|
||||
// Unknown offer, wrong receiver: dropped, and the sender stays connected.
|
||||
await answer(peers, peers.receiver.id, id());
|
||||
await answer(peers, id(), offer_id);
|
||||
await answer(peers, peers.receiver.id, offer_id, 'sealed');
|
||||
expect(await take(peers.receiver, (msg) => msg.answer)).toEqual({
|
||||
action: 'announce',
|
||||
info_hash: peers.hash,
|
||||
peer_id: peers.sender.id,
|
||||
offer_id,
|
||||
answer: sdp('answer', 'sealed'),
|
||||
});
|
||||
await answer(peers, peers.receiver.id, offer_id, 'again');
|
||||
await announce(peers.receiver, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
|
||||
expect(peers.receiver.messages).toEqual([]);
|
||||
});
|
||||
|
||||
test('drops an answer to a receiver that left', async () => {
|
||||
const peers = await swarm();
|
||||
const { offer_id } = await offer(peers);
|
||||
peers.receiver.ws.close();
|
||||
await peers.receiver.closed;
|
||||
// Its peer_id comes back with a new connection, the old offer stays gone.
|
||||
const again = await open();
|
||||
await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
|
||||
await answer(peers, peers.receiver.id, offer_id);
|
||||
await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
|
||||
expect(again.messages).toEqual([]);
|
||||
});
|
||||
|
||||
for (const [name, data, reason] of [
|
||||
['text that is no JSON', 'nope', 'invalid message'],
|
||||
['binary messages', new Uint8Array([1]), 'invalid message'],
|
||||
['scrape', { action: 'scrape', info_hash: id() }, 'invalid announce'],
|
||||
['a short info_hash', { action: 'announce', info_hash: 'x', peer_id: id() }, 'invalid announce'],
|
||||
[
|
||||
'two offers in one announce',
|
||||
{
|
||||
action: 'announce',
|
||||
info_hash: id(),
|
||||
peer_id: id(),
|
||||
left: 1,
|
||||
offers: [1, 2].map(() => ({ offer_id: id(), offer: sdp('offer') })),
|
||||
},
|
||||
'invalid offer',
|
||||
],
|
||||
[
|
||||
'an offer that is an answer',
|
||||
{ action: 'announce', info_hash: id(), peer_id: id(), left: 1, offers: [{ offer_id: id(), offer: sdp('answer') }] },
|
||||
'invalid offer',
|
||||
],
|
||||
[
|
||||
'an answer without to_peer_id',
|
||||
{ action: 'announce', info_hash: id(), peer_id: id(), left: 0, offer_id: id(), answer: sdp('answer') },
|
||||
'invalid answer',
|
||||
],
|
||||
]) {
|
||||
test(`rejects ${name}`, async () => {
|
||||
await rejected(await open(), data, reason);
|
||||
});
|
||||
}
|
||||
|
||||
test('rejects a taken peer_id and a second swarm', async () => {
|
||||
const { hash, sender } = await swarm();
|
||||
await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: sender.id, left: 0 }, 'peer_id taken');
|
||||
await rejected(
|
||||
sender,
|
||||
{ action: 'announce', info_hash: id(), peer_id: sender.id, left: 0 },
|
||||
'one swarm per connection',
|
||||
);
|
||||
});
|
||||
|
||||
test('frees a peer_id once its connection closed', async () => {
|
||||
const { hash, sender } = await swarm();
|
||||
sender.ws.close();
|
||||
await sender.closed;
|
||||
expect(await announce(await open(), { info_hash: hash, peer_id: sender.id, left: 0 })).toBeTruthy();
|
||||
});
|
||||
|
||||
test('closes on a message beyond 16 KiB', async () => {
|
||||
const client = await open();
|
||||
client.ws.send('x'.repeat(16 * 1024 + 1));
|
||||
expect(await client.closed).toBe(1009);
|
||||
});
|
||||
|
||||
test('limits the message rate', async () => {
|
||||
const client = await open();
|
||||
const fields = { action: 'announce', info_hash: id(), peer_id: id(), left: 0 };
|
||||
for (let i = 0; i < 10; i++) client.ws.send(JSON.stringify(fields));
|
||||
await rejected(client, fields, 'too many messages');
|
||||
});
|
||||
|
||||
test('limits pings like messages, also from a peer that stops reading', async () => {
|
||||
// ws's client, browsers send no pings. ws used to answer every one, its pongs piled up in the tracker.
|
||||
const client = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
|
||||
const closed = once(client, 'close');
|
||||
const reasons = [];
|
||||
client.on('message', (data) => reasons.push(JSON.parse(data)['failure reason']));
|
||||
await once(client, 'open');
|
||||
client.ping('x');
|
||||
expect(String((await once(client, 'pong'))[0])).toBe('x');
|
||||
client._socket.pause();
|
||||
for (let i = 0; i < 1000; i++) client.ping('x'.repeat(125));
|
||||
client._socket.resume();
|
||||
await closed;
|
||||
expect(reasons).toEqual(['too many messages']);
|
||||
});
|
||||
|
||||
test('limits the signaling forwarded per connection', async () => {
|
||||
const { hash, receiver } = await swarm();
|
||||
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
|
||||
for (let i = 0; i < 4; i++)
|
||||
await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] });
|
||||
await rejected(
|
||||
receiver,
|
||||
{ action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] },
|
||||
'too much signaling',
|
||||
);
|
||||
});
|
||||
|
||||
test('limits the signaling from one address across connections', () =>
|
||||
withEnv({ MAX_FORWARDED_PER_IP: '20' }, async () => {
|
||||
const { hash, receiver } = await swarm();
|
||||
const fields = { action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1 };
|
||||
// Five bytes each, four fit, the fifth is past the limit though the connection's own is far off.
|
||||
const offer = { offer_id: id(), offer: sdp('offer') };
|
||||
for (let i = 0; i < 4; i++) await announce(receiver, { ...fields, offers: [offer] });
|
||||
await rejected(receiver, { ...fields, offers: [offer] }, 'too much signaling');
|
||||
// A new connection from the same address doesn't get a fresh allowance.
|
||||
const again = await open();
|
||||
const second = { action: 'announce', info_hash: hash, peer_id: id(), left: 1 };
|
||||
await announce(again, second);
|
||||
await rejected(again, { ...second, offers: [offer] }, 'too much signaling');
|
||||
}));
|
||||
|
||||
test('limits connections from one address over time, not only at once', () =>
|
||||
withEnv({ MAX_CONNECTS_PER_IP: '3' }, async () => {
|
||||
for (let i = 0; i < 3; i++) expect(await open()).toBeTruthy();
|
||||
// Below MAX_PER_IP, and closing them doesn't reset the rate.
|
||||
const opened = clients.splice(0);
|
||||
for (const client of opened) client.ws.close();
|
||||
await Promise.all(opened.map((client) => client.closed));
|
||||
expect(await open()).toBeUndefined();
|
||||
}));
|
||||
|
||||
test('forgets the oldest address once too many records pile up', () =>
|
||||
withEnv({ MAX_IPS: '2', MAX_CONNECTS_PER_IP: '1' }, async () => {
|
||||
const close = async (address) => {
|
||||
ip = address;
|
||||
const client = await open();
|
||||
client.ws.close();
|
||||
await client.closed;
|
||||
// The tracker only evicts closed records, let it see the close first.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
};
|
||||
await close('192.0.2.1');
|
||||
await close('192.0.2.2');
|
||||
// The third record pushes the first out, which may connect again; the second stays limited.
|
||||
await close('192.0.2.3');
|
||||
ip = '192.0.2.2';
|
||||
expect(await open()).toBeUndefined();
|
||||
ip = '192.0.2.1';
|
||||
expect(await open()).toBeTruthy();
|
||||
}));
|
||||
|
||||
test('drops a peer that stops reading', async () => {
|
||||
const hash = id();
|
||||
const slowId = id();
|
||||
// ws's client, its socket can stop reading. What the tracker sends then piles up in the kernel's
|
||||
// buffers first, then in the tracker.
|
||||
const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
|
||||
const closed = once(slow, 'close').then(([code]) => code);
|
||||
await once(slow, 'open');
|
||||
slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0, numwant: 0 }));
|
||||
await once(slow, 'message');
|
||||
slow._socket.pause();
|
||||
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
|
||||
// Receivers that reconnect over and over, each within its own limit. The slow sender's peer_id is
|
||||
// free again once the tracker dropped it.
|
||||
let dropped = false;
|
||||
for (let i = 0; i < 1000 && !dropped; i++) {
|
||||
const receiver = await open();
|
||||
const fields = { info_hash: hash, peer_id: id(), left: 1 };
|
||||
for (let j = 0; j < 4; j++) await announce(receiver, { ...fields, offers: [big()] });
|
||||
receiver.ws.close();
|
||||
await receiver.closed;
|
||||
const probe = await open();
|
||||
probe.ws.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0 }));
|
||||
dropped = 'interval' in (await take(probe, (msg) => 'interval' in msg || 'failure reason' in msg));
|
||||
if (!dropped) await probe.closed;
|
||||
}
|
||||
expect(dropped).toBe(true);
|
||||
slow._socket.resume();
|
||||
// Terminated, without a close frame.
|
||||
expect(await closed).toBe(1006);
|
||||
});
|
||||
|
||||
test('drops the largest queues once all of them together pass MAX_QUEUED_ALL', async () => {
|
||||
// The tracker's side of the slow sender's connection: what its socket holds is queued, the kernel's
|
||||
// buffers are full by then.
|
||||
let queue;
|
||||
const track = (_, socket) => (queue = socket);
|
||||
server.on('upgrade', track);
|
||||
const hash = id();
|
||||
const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
|
||||
const closed = once(slow, 'close').then(([code]) => code);
|
||||
await once(slow, 'open');
|
||||
server.off('upgrade', track);
|
||||
slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: id(), left: 0, numwant: 0 }));
|
||||
await once(slow, 'message');
|
||||
slow._socket.pause();
|
||||
// Budget lowered first: once the kernel's buffers are full, the next offer leaves a queue, and
|
||||
// the reply to the receiver right after it is past the budget. Checked later, the kernel could
|
||||
// have taken the queue in by then. The slow sender's queue goes, the receiver's reply arrives.
|
||||
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
|
||||
await withEnv({ MAX_QUEUED_ALL: '1' }, async () => {
|
||||
for (let i = 0; i < 1000 && !queue.destroyed; i++) {
|
||||
const receiver = await open();
|
||||
const fields = { info_hash: hash, peer_id: id(), left: 1 };
|
||||
for (let j = 0; j < 4 && !queue.destroyed; j++) {
|
||||
await announce(receiver, { ...fields, offers: [big()] });
|
||||
// Gone with its first queue, not once it grew to MAX_QUEUED.
|
||||
expect(queue.destroyed || !queue.writableLength).toBe(true);
|
||||
}
|
||||
receiver.ws.close();
|
||||
await receiver.closed;
|
||||
}
|
||||
});
|
||||
expect(queue.destroyed).toBe(true);
|
||||
slow._socket.resume();
|
||||
expect(await closed).toBe(1006);
|
||||
});
|
||||
|
||||
test('limits a swarm to 8 peers', async () => {
|
||||
const hash = id();
|
||||
for (let i = 0; i < 8; i++) await announce(await open(), { info_hash: hash, peer_id: id(), left: 1 });
|
||||
await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: id(), left: 1 }, 'swarm full');
|
||||
});
|
||||
|
||||
test('limits connections per IP to 16', async () => {
|
||||
for (let i = 0; i < 16; i++) expect(await open()).toBeTruthy();
|
||||
expect(await open()).toBeUndefined();
|
||||
ip = '198.51.100.250';
|
||||
expect(await open()).toBeTruthy();
|
||||
});
|
||||
|
||||
test('counts IPv6 by /64, however it is written', async () => {
|
||||
for (let i = 1; i <= 16; i++) {
|
||||
ip = [`2001:db8:${tests}::${i.toString(16)}`, `2001:0DB8:${tests}:0:${i}::`][i % 2];
|
||||
expect(await open()).toBeTruthy();
|
||||
}
|
||||
ip = `2001:db8:${tests}:0:ffff:ffff:ffff:ffff`;
|
||||
expect(await open()).toBeUndefined();
|
||||
ip = `2001:db8:${tests}:1::1`;
|
||||
expect(await open()).toBeTruthy();
|
||||
});
|
||||
|
||||
test('ignores X-Forwarded-For without a trusted proxy', () =>
|
||||
// Without PROXIES the socket's address counts, a client can't hand-pick a fresh one per
|
||||
// connection. All these come from 127.0.0.1.
|
||||
withEnv({ PROXIES: undefined }, async () => {
|
||||
for (let i = 0; i < 16; i++) expect(await open({ xff: `203.0.113.${i + 1}` })).toBeTruthy();
|
||||
expect(await open({ xff: '203.0.113.250' })).toBeUndefined();
|
||||
// With the peer trusted again, the forwarded address counts once more. One that is no address
|
||||
// counts as the peer's, full by now.
|
||||
process.env.PROXIES = '127.0.0.1';
|
||||
for (const xff of ['203.0.113.250:1234', '2001:db8::1::1']) expect(await open({ xff })).toBeUndefined();
|
||||
expect(await open({ xff: '203.0.113.250' })).toBeTruthy();
|
||||
// Also as a CIDR, however the proxy's address is written. An IPv4 prefix counts in IPv4's 32
|
||||
// bits, an empty one is no range at all.
|
||||
for (const proxies of ['10.0.0.0/8', '10.0.0.0/']) {
|
||||
process.env.PROXIES = proxies;
|
||||
expect(await open({ xff: '203.0.113.251' })).toBeUndefined();
|
||||
}
|
||||
for (const [i, proxies] of ['127.0.0.0/8', '::ffff:127.0.0.0/120'].entries()) {
|
||||
process.env.PROXIES = proxies;
|
||||
expect(await open({ xff: `203.0.113.${251 + i}` })).toBeTruthy();
|
||||
}
|
||||
}));
|
||||
|
||||
// MAX_SILENT lowered only here: the tests holding 16 silent connections would lose the first ones
|
||||
// on a busy machine.
|
||||
test('closes a connection that announces nothing', () =>
|
||||
// One that only holds a slot goes. Terminated, without a close frame it could ignore.
|
||||
withEnv({ MAX_SILENT: '500' }, async () => {
|
||||
const client = await open();
|
||||
expect(await client.closed).toBe(1006);
|
||||
}));
|
||||
|
||||
test('keeps a connection that announced', () =>
|
||||
// Also past MAX_SILENT, announcing is the first thing a peer does.
|
||||
withEnv({ MAX_SILENT: '500' }, async () => {
|
||||
const client = await open();
|
||||
const fields = { info_hash: id(), peer_id: id(), left: 0 };
|
||||
await announce(client, fields);
|
||||
await new Promise((resolve) => setTimeout(resolve, 750));
|
||||
await announce(client, fields);
|
||||
}));
|
||||
|
||||
test('answers plain HTTP with a 404 and closes the socket', async () => {
|
||||
const socket = connectTcp(new URL(url).port, '127.0.0.1');
|
||||
await once(socket, 'connect');
|
||||
socket.write('GET / HTTP/1.1\r\nHost: x\r\n\r\n');
|
||||
const [data] = await once(socket, 'data');
|
||||
expect(String(data)).toContain('404');
|
||||
// Connection: close, so unlimited sequential 404s on one connection are over.
|
||||
expect(String(data).toLowerCase()).toContain('connection: close');
|
||||
await once(socket, 'close');
|
||||
});
|
||||
|
||||
test('survives clients resetting refused connections', async () => {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const socket = connectTcp(new URL(url).port, '127.0.0.1');
|
||||
await once(socket, 'connect');
|
||||
socket.write(
|
||||
'GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\n' +
|
||||
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: https://evil.test\r\n\r\n',
|
||||
);
|
||||
socket.resetAndDestroy();
|
||||
}
|
||||
// An unhandled error would have ended this worker.
|
||||
expect(await open()).toBeTruthy();
|
||||
});
|
||||
|
||||
test('keeps no peer that left', async () => {
|
||||
// The root stays and gets the first offer, then every peer gets the next one's offer and leaves.
|
||||
// Held offers used to keep all of them alive, through the root.
|
||||
const hash = id();
|
||||
const root = { ...(await open()), id: id() };
|
||||
await announce(root, { info_hash: hash, peer_id: root.id, left: 0 });
|
||||
let holder = root;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const peer = { ...(await open()), id: id() };
|
||||
await announce(peer, {
|
||||
info_hash: hash,
|
||||
peer_id: peer.id,
|
||||
left: 1,
|
||||
offers: [{ offer_id: id(), offer: sdp('offer') }],
|
||||
});
|
||||
await take(holder, (msg) => msg.offer);
|
||||
// The only sender for the next offer.
|
||||
await announce(peer, { info_hash: hash, peer_id: peer.id, left: 0 });
|
||||
if (holder === root) await announce(root, { info_hash: hash, peer_id: root.id, left: 1 });
|
||||
else {
|
||||
holder.ws.close();
|
||||
await holder.closed;
|
||||
}
|
||||
holder = peer;
|
||||
}
|
||||
// queryObjects collects garbage first.
|
||||
await expect.poll(() => queryObjects(ServerSocket, { format: 'count' })).toBeLessThanOrEqual(2);
|
||||
});
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
|
||||
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||
"files": {
|
||||
"includes": ["**", "!**/node_modules", "!**/dist", "!**/test-results", "!**/*.svg", "!**/pnpm-lock.yaml"]
|
||||
},
|
||||
"formatter": { "indentStyle": "space", "lineWidth": 120 },
|
||||
"javascript": { "formatter": { "quoteStyle": "single" } },
|
||||
"css": { "formatter": { "quoteStyle": "single" } },
|
||||
"yaml": { "formatter": { "quoteStyle": "single" } },
|
||||
"html": {
|
||||
"experimentalFullSupportEnabled": true,
|
||||
"formatter": { "enabled": true, "selfCloseVoidElements": "always" }
|
||||
},
|
||||
"linter": {
|
||||
"rules": {
|
||||
"preset": "recommended",
|
||||
"nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" },
|
||||
"style": {
|
||||
"noNonNullAssertion": "off",
|
||||
"noDescendingSpecificity": "off",
|
||||
"noRestrictedImports": {
|
||||
"level": "error",
|
||||
"options": {
|
||||
"paths": {
|
||||
"./core": {
|
||||
"message": "only src/core.test.ts imports this export of src/core.ts",
|
||||
"importNames": [
|
||||
"CHUNK_SIZE",
|
||||
"MAX_BUFFERED",
|
||||
"WINDOW",
|
||||
"TRACKER_TIMEOUT",
|
||||
"MAX_TRACKER_MESSAGE",
|
||||
"MAX_TRACKER_MESSAGES",
|
||||
"MESSAGE_WINDOW",
|
||||
"TRACKER_NOTES",
|
||||
"CONNECT_TIMEOUT",
|
||||
"MIN_INTERVAL",
|
||||
"PBKDF2_ITERATIONS",
|
||||
"PROOF_TIMEOUT",
|
||||
"MAX_NAME",
|
||||
"own",
|
||||
"live",
|
||||
"deadline",
|
||||
"stunChoice",
|
||||
"parse",
|
||||
"decode",
|
||||
"CODE_CHARS",
|
||||
"SALT_WINDOW",
|
||||
"CODE_LENGTH",
|
||||
"trackerSalt",
|
||||
"newCode",
|
||||
"codeSalt",
|
||||
"secrets",
|
||||
"seal",
|
||||
"unseal",
|
||||
"stunHint",
|
||||
"securityCheck",
|
||||
"fingerprints",
|
||||
"prove",
|
||||
"Handshake",
|
||||
"sendFile",
|
||||
"receiveFile",
|
||||
"trackerSocket",
|
||||
"noTracker"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"a11y": { "useSemanticElements": "off" }
|
||||
}
|
||||
},
|
||||
"overrides": [
|
||||
{ "includes": ["src/core.test.ts"], "linter": { "rules": { "style": { "noRestrictedImports": "off" } } } }
|
||||
]
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
{
|
||||
"lockfileVersion": 2,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "hellcon",
|
||||
"dependencies": {
|
||||
"vue": "^3.5.44",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^26.6.5",
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"axe-core": "^4.14.0",
|
||||
"typescript": "~6.0.3",
|
||||
"vite": "^8.3.4",
|
||||
"vue-tsc": "^3.3.13",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
|
||||
|
||||
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
|
||||
|
||||
"@babel/parser": ["@babel/parser@7.29.9", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA=="],
|
||||
|
||||
"@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],
|
||||
|
||||
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="],
|
||||
|
||||
"@oxc-project/types": ["@oxc-project/types@0.154.0", "", {}, "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA=="],
|
||||
|
||||
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.14", "", { "os": "android", "cpu": "arm" }, "sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg=="],
|
||||
|
||||
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.14", "", { "os": "android", "cpu": "arm64" }, "sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ=="],
|
||||
|
||||
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw=="],
|
||||
|
||||
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA=="],
|
||||
|
||||
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.14", "", { "os": "freebsd", "cpu": "x64" }, "sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA=="],
|
||||
|
||||
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.14", "", { "os": "linux", "cpu": "arm" }, "sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg=="],
|
||||
|
||||
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ=="],
|
||||
|
||||
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg=="],
|
||||
|
||||
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.14", "", { "os": "linux", "cpu": "ppc64" }, "sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q=="],
|
||||
|
||||
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.14", "", { "os": "linux", "cpu": "s390x" }, "sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A=="],
|
||||
|
||||
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.14", "", { "os": "linux", "cpu": "x64" }, "sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg=="],
|
||||
|
||||
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.14", "", { "os": "linux", "cpu": "x64" }, "sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg=="],
|
||||
|
||||
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.14", "", { "os": "none", "cpu": "arm64" }, "sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q=="],
|
||||
|
||||
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA=="],
|
||||
|
||||
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.14", "", { "os": "win32", "cpu": "x64" }, "sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ=="],
|
||||
|
||||
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
|
||||
|
||||
"@types/node": ["@types/node@26.6.5", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg=="],
|
||||
|
||||
"@vitejs/plugin-vue": ["@vitejs/plugin-vue@6.0.10", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25 || ^3.6.0-rc.10" } }, "sha512-b80aUQh3n+qEzzZm5oQp3rT2QImeCx58K6eFl/RkJ3d65KW0kTuv5lNsLRVAjbW9YRUpo/wzmvzMgV34bTAItA=="],
|
||||
|
||||
"@volar/language-core": ["@volar/language-core@2.4.28", "", { "dependencies": { "@volar/source-map": "2.4.28" } }, "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ=="],
|
||||
|
||||
"@volar/source-map": ["@volar/source-map@2.4.28", "", {}, "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ=="],
|
||||
|
||||
"@volar/typescript": ["@volar/typescript@2.4.28", "", { "dependencies": { "@volar/language-core": "2.4.28", "path-browserify": "^1.0.1", "vscode-uri": "^3.0.8" } }, "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw=="],
|
||||
|
||||
"@vue/compiler-core": ["@vue/compiler-core@3.5.44", "", { "dependencies": { "@babel/parser": "^7.29.9", "@vue/shared": "3.5.44", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.2" } }, "sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ=="],
|
||||
|
||||
"@vue/compiler-dom": ["@vue/compiler-dom@3.5.44", "", { "dependencies": { "@vue/compiler-core": "3.5.44", "@vue/shared": "3.5.44" } }, "sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg=="],
|
||||
|
||||
"@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.44", "", { "dependencies": { "@babel/parser": "^7.29.9", "@vue/compiler-core": "3.5.44", "@vue/compiler-dom": "3.5.44", "@vue/compiler-ssr": "3.5.44", "@vue/shared": "3.5.44", "estree-walker": "^2.0.2", "magic-string": "^0.30.21", "postcss": "^8.5.29", "source-map-js": "^1.2.2" } }, "sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw=="],
|
||||
|
||||
"@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.44", "", { "dependencies": { "@vue/compiler-dom": "3.5.44", "@vue/shared": "3.5.44" } }, "sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA=="],
|
||||
|
||||
"@vue/language-core": ["@vue/language-core@3.3.13", "", { "dependencies": { "@volar/language-core": "2.4.28", "@vue/compiler-dom": "^3.5.0", "@vue/shared": "^3.5.0", "alien-signals": "^3.2.1", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1", "picomatch": "^4.0.4" } }, "sha512-axA0Xemn5LuUKuKWob0/kVq7xQ2mJJM6VqA9Exvt35nM9yRC31goWVve/G/Zb2ZCLsXC8FHYjjfXlnshknSCew=="],
|
||||
|
||||
"@vue/reactivity": ["@vue/reactivity@3.5.44", "", { "dependencies": { "@vue/shared": "3.5.44" } }, "sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw=="],
|
||||
|
||||
"@vue/runtime-core": ["@vue/runtime-core@3.5.44", "", { "dependencies": { "@vue/reactivity": "3.5.44", "@vue/shared": "3.5.44" } }, "sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ=="],
|
||||
|
||||
"@vue/runtime-dom": ["@vue/runtime-dom@3.5.44", "", { "dependencies": { "@vue/reactivity": "3.5.44", "@vue/runtime-core": "3.5.44", "@vue/shared": "3.5.44", "csstype": "^3.2.3" } }, "sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg=="],
|
||||
|
||||
"@vue/server-renderer": ["@vue/server-renderer@3.5.44", "", { "dependencies": { "@vue/compiler-ssr": "3.5.44", "@vue/runtime-dom": "3.5.44", "@vue/shared": "3.5.44" } }, "sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ=="],
|
||||
|
||||
"@vue/shared": ["@vue/shared@3.5.44", "", {}, "sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg=="],
|
||||
|
||||
"alien-signals": ["alien-signals@3.2.1", "", {}, "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g=="],
|
||||
|
||||
"axe-core": ["axe-core@4.14.0", "", {}, "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ=="],
|
||||
|
||||
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
|
||||
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
|
||||
|
||||
"entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
|
||||
|
||||
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
|
||||
|
||||
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
|
||||
|
||||
"lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
|
||||
|
||||
"lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
|
||||
|
||||
"lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
|
||||
|
||||
"lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
|
||||
|
||||
"lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
|
||||
|
||||
"lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
|
||||
|
||||
"lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
|
||||
|
||||
"lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
|
||||
|
||||
"lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
|
||||
|
||||
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"muggle-string": ["muggle-string@0.4.1", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
|
||||
|
||||
"path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
|
||||
|
||||
"postcss": ["postcss@8.5.30", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA=="],
|
||||
|
||||
"rolldown": ["rolldown@1.2.14", "", { "dependencies": { "@oxc-project/types": "=0.154.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.14", "@rolldown/binding-android-arm64": "1.2.14", "@rolldown/binding-darwin-arm64": "1.2.14", "@rolldown/binding-darwin-x64": "1.2.14", "@rolldown/binding-freebsd-x64": "1.2.14", "@rolldown/binding-linux-arm-gnueabihf": "1.2.14", "@rolldown/binding-linux-arm64-gnu": "1.2.14", "@rolldown/binding-linux-arm64-musl": "1.2.14", "@rolldown/binding-linux-ppc64-gnu": "1.2.14", "@rolldown/binding-linux-s390x-gnu": "1.2.14", "@rolldown/binding-linux-x64-gnu": "1.2.14", "@rolldown/binding-linux-x64-musl": "1.2.14", "@rolldown/binding-openharmony-arm64": "1.2.14", "@rolldown/binding-win32-arm64-msvc": "1.2.14", "@rolldown/binding-win32-x64-msvc": "1.2.14" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
|
||||
|
||||
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
|
||||
|
||||
"typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="],
|
||||
|
||||
"undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
|
||||
"vite": ["vite@8.3.4", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.29", "rolldown": "~1.2.12", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ=="],
|
||||
|
||||
"vscode-uri": ["vscode-uri@3.2.0", "", {}, "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg=="],
|
||||
|
||||
"vue": ["vue@3.5.44", "", { "dependencies": { "@vue/compiler-dom": "3.5.44", "@vue/compiler-sfc": "3.5.44", "@vue/runtime-dom": "3.5.44", "@vue/server-renderer": "3.5.44", "@vue/shared": "3.5.44" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-dvvmaOCG7lAMkJTPqPwWeGMsPS6DIsFsfZDUgBp9V6mHf9b3+/wyVwYR4Es+WV6uJC0FKRxp81Obcq0ZwUcGFQ=="],
|
||||
|
||||
"vue-tsc": ["vue-tsc@3.3.13", "", { "dependencies": { "@volar/typescript": "2.4.28", "@vue/language-core": "3.3.13" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "bin/vue-tsc.js" } }, "sha512-jE4/bXdOMSHVxEGgQCqNllJy+9N3Gx6tfSAsg0yhFK/MAN6eXqISihupnDEKSCt12VVnjN2gI3AqLYcqoh5x/A=="],
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
# Our tracker image, built from the official Node base and pinned upstream npm package.
|
||||
# Independent of coturn and its development secrets; usable alone on the VPS.
|
||||
name: hellcon-tracker
|
||||
services:
|
||||
tracker:
|
||||
build:
|
||||
context: ./tracker
|
||||
target: runtime
|
||||
image: hellcon-tracker:local
|
||||
init: true
|
||||
restart: "no"
|
||||
ports:
|
||||
- "127.0.0.1:${TRACKER_PORT:-8000}:8000"
|
||||
environment:
|
||||
ANNOUNCE_INTERVAL_SECONDS: "5"
|
||||
ALLOWED_ORIGINS: "${TRACKER_ALLOWED_ORIGINS:-}"
|
||||
TRUSTED_PROXY_IPS: "${TRACKER_TRUSTED_PROXY_IPS:-}"
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
pids_limit: 64
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "5m"
|
||||
max-file: "2"
|
||||
@@ -1,33 +0,0 @@
|
||||
# Linux development only. No boot startup or automatic container restart.
|
||||
services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.18.0-r0-alpine
|
||||
network_mode: host
|
||||
restart: "no"
|
||||
command:
|
||||
- -n
|
||||
- --listening-ip=127.0.0.1
|
||||
- --relay-ip=127.0.0.1
|
||||
- --listening-port=${TURN_PORT:-3478}
|
||||
- --realm=hellcon.local
|
||||
- --use-auth-secret
|
||||
- --static-auth-secret=${TURN_SECRET:?Run bun run dev:setup first}
|
||||
- --fingerprint
|
||||
- --min-port=49160
|
||||
- --max-port=49200
|
||||
- --no-tls
|
||||
# DTLS is opt-in in coturn 4.18; leave it disabled.
|
||||
- --no-tcp-relay
|
||||
- --no-multicast-peers
|
||||
# Needed for two browsers relaying to each other on this machine.
|
||||
- --allow-loopback-peers
|
||||
- --no-cli
|
||||
- --no-software-attribute
|
||||
- --log-file=stdout
|
||||
tmpfs:
|
||||
- /var/lib/coturn
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "5m"
|
||||
max-file: "2"
|
||||
@@ -1,35 +0,0 @@
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { createHmac, randomUUID } from 'node:crypto';
|
||||
|
||||
interface IceResponse {
|
||||
setHeader(name: string, value: string): unknown;
|
||||
writeHead(status: number, headers?: Record<string, string>): unknown;
|
||||
end(body?: string): unknown;
|
||||
}
|
||||
|
||||
// Shared by Vite and the browser integration checks. Never imported by the client.
|
||||
export function iceMiddleware(env: NodeJS.ProcessEnv) {
|
||||
const secret = env.TURN_SECRET;
|
||||
if (!secret) throw new Error('TURN_SECRET is required. Run bun run dev:setup first.');
|
||||
const host = env.TURN_HOST || '127.0.0.1';
|
||||
const port = env.TURN_PORT || '3478';
|
||||
return (req: Pick<IncomingMessage, 'url' | 'method' | 'headers'>, res: IceResponse, next: () => void) => {
|
||||
if (req.url?.split('?')[0] !== '/api/ice-servers') return next();
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
if (req.method !== 'GET') {
|
||||
res.writeHead(405, { Allow: 'GET' }); res.end(); return;
|
||||
}
|
||||
if (req.headers['sec-fetch-site'] === 'cross-site' ||
|
||||
(req.headers.origin && req.headers.origin !== `http://${req.headers.host}`)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + 3600;
|
||||
const username = `${expiresAt}:${randomUUID()}`;
|
||||
const credential = createHmac('sha1', secret).update(username).digest('base64');
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(JSON.stringify({ expiresAt, iceServers: [
|
||||
{ urls: `stun:${host}:${port}` },
|
||||
{ urls: [`turn:${host}:${port}?transport=udp`, `turn:${host}:${port}?transport=tcp`], username, credential },
|
||||
] }));
|
||||
};
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
# First-version comparison
|
||||
|
||||
Compared `d198332` (first commit) with `95e4a87` (current checkout), 2026-10-16.
|
||||
The checkout was clean and did not contain the diagnostics files mentioned in
|
||||
the handoff. The preview on port 4174 was not running.
|
||||
|
||||
The user reports the original version works between two physical machines on
|
||||
different networks. Earlier successful diagnostic logs were both same-machine
|
||||
tests. The physical-device regression remains **unexplained**; the experiments
|
||||
below do not reproduce it and do not establish a firewall, DNS or timing cause.
|
||||
|
||||
## Relevant differences
|
||||
|
||||
| Area | First version | Current checkout | Finding |
|
||||
| --- | --- | --- | --- |
|
||||
| STUN default | Google | PageQuit (introduced in `1d8e595`) | User also observed failure with Google; 701 is not a sufficient explanation. |
|
||||
| Gathering | Completes immediately when done, otherwise returns partial SDP after 5 s | Requires completion within 30 s (`752d0cf`) | A real behavior change, but reported failed sessions gathered in 0–0.1 s. No evidence this deadline caused those failures. |
|
||||
| Signaling | Base64 of SDP | Base64 of a versioned JSON envelope (`752d0cf`) | Both use the gathered `localDescription.sdp`, preserve candidates, and apply decoded SDP directly. Neither implements trickle signaling. |
|
||||
| Failed peer | UI marks closed; peer stays alive | Session disposes failed peer (`752d0cf`) | Tested keeping it alive; did not recover in the controlled Firefox case. No justification yet to treat this as the root cause. |
|
||||
| Transfer | Sends metadata/file on channel open | Requires fingerprint confirmation and receiver acceptance | These happen after ICE connects. The reported failures are at ICE setup. |
|
||||
| Lifecycle | Sender was not closed on component unmount | Both roles close when switching Send/Receive | Browser-tab/app switching has no explicit cancellation handler in either version. |
|
||||
| TURN | None | Explicit opt-in only | Default remains direct; do not assume another application's successful path was direct. |
|
||||
|
||||
## Controlled experiment
|
||||
|
||||
`scripts/compare-ice.mjs` loads the actual signaling helpers from the first
|
||||
commit using `git show`, and the current helpers using Node's TypeScript
|
||||
eraser. It creates independent local peer pairs for three modes: original,
|
||||
current with the current UI's immediate failed-peer cleanup, and current with
|
||||
that cleanup disabled. This isolates signaling/lifecycle behavior; it is not a
|
||||
test of either complete Vue UI and does not simulate a physical network fully.
|
||||
|
||||
All modes use identical ICE configuration. The experiment removes TCP offer
|
||||
candidates and changes advertised UDP ports to port 9, leaving the real sender
|
||||
socket alive. This deliberately prevents initial checks to the advertised
|
||||
sender endpoint; a subsequent sender-initiated check can potentially discover
|
||||
a usable peer-reflexive candidate. The answer is applied after 20 seconds.
|
||||
Only times/states and receipt of a fixed probe string are reported, never SDP.
|
||||
|
||||
Observed results on this host:
|
||||
|
||||
| Browser | Original | Current | Current, keep failed peer |
|
||||
| --- | --- | --- | --- |
|
||||
| Firefox | Receiver failed at ~5 s; no probe received | Receiver failed at ~5 s; no probe received | Receiver failed at ~5 s; no probe received |
|
||||
| Chromium | Probe received at ~20.3 s | Probe received at ~20.3 s | Probe received at ~20.3 s |
|
||||
|
||||
A further Firefox run configured a silent loopback UDP socket as STUN
|
||||
(`--slow-stun`). All modes still completed gathering in under 0.1 s and included
|
||||
the end-of-candidates marker, so this did **not** exercise the partial-gathering
|
||||
fallback. All failed alike. Do not claim this tested a genuinely slow STUN path.
|
||||
|
||||
These results rule out the claim that simply retaining a failed peer fixes this
|
||||
particular controlled case. They do not rule out a lifecycle regression in other
|
||||
conditions, nor prove that a 20-second answer delay is safe on physical devices.
|
||||
|
||||
## Next discriminating evidence
|
||||
|
||||
Use matching first/current versions on both physical devices, with the same
|
||||
sender direction, STUN provider and page origin/browser profile. Record whether
|
||||
the actual receiver obtains the full file. Compare local/remote candidate types,
|
||||
selected pairs and check counters; the current UI now retains these after
|
||||
failure. A missing public candidate, an absence of candidate pairs, and checks
|
||||
sent with no responses are distinct observations, not diagnoses by themselves.
|
||||
|
||||
Do not change firewall rules or shorten user copy/paste time based only on the
|
||||
same-machine tests. The original/current comparison has not yet identified a
|
||||
code change that demonstrably explains the user's physical-device failures.
|
||||
|
||||
## Two Brave peers on different networks, subsequent report
|
||||
|
||||
The reported setup is the same two devices/networks used for the first-version
|
||||
trial. In the new logs both peers gather two host candidates and one srflx
|
||||
candidate, with no relay. Neither reports a connected state or transfer activity.
|
||||
The sender's sole live snapshot is immediately after applying the answer: one
|
||||
in-progress pair, one request sent, and zero responses so far. This is not a
|
||||
snapshot of the whole failed attempt. Both final snapshots have no candidate
|
||||
pairs; the browser has already discarded the useful evidence.
|
||||
|
||||
Each log has its own time origin. Sender “answer applied at 25.8 s” cannot be
|
||||
compared directly with receiver “failed at 15.1 s” to establish whether the answer
|
||||
was applied before or after receiver failure. A 701 event with a gathered srflx
|
||||
candidate also does not identify the reason the peer connection failed.
|
||||
|
||||
The v3 UX work changed the signaling envelope version, not candidate gathering or
|
||||
the SDP applied to the browser. The original default STUN provider was Google;
|
||||
the current default is PageQuit. Matching that selection is necessary for an
|
||||
original/current comparison, even with unchanged devices and networks.
|
||||
|
||||
Diagnostics now sample candidate-pair counters at 3, 6, 9 and 12 seconds while ICE
|
||||
is checking, and include allowlisted DTLS transport states. Sampling stops when
|
||||
checking ends or the session is disposed. Receiver answer creation also takes a
|
||||
snapshot. These changes improve evidence collection; they are not a demonstrated
|
||||
fix for the physical-device connection failure.
|
||||
|
||||
The isolated comparison was also rerun with `/usr/bin/brave`: original, current,
|
||||
and current-without-immediate-cleanup all delivered the fixed probe at roughly
|
||||
20.25 seconds after a deliberate 20-second answer delay. In this local test the
|
||||
receiver did not report checking until the delayed answer was applied on the
|
||||
sender, unlike the reported physical-device attempt. It does not reproduce that
|
||||
attempt or establish that its answer-exchange timing is safe.
|
||||
|
||||
## Subsequent successful transfer report
|
||||
|
||||
The next supplied receiver/sender logs show a completed transfer. The receiver
|
||||
created its answer at 0.1 s, sampled two in-progress pairs with no incoming checks
|
||||
or responses through 12.0 s, then connected at 13.3 s. The sender applied the
|
||||
answer at 40.3 s on its own clock and connected by 40.4 s. These are independent
|
||||
time origins; the initial zero-response samples alone do not establish failure.
|
||||
|
||||
Both final snapshots show one selected, nominated, succeeded srflx/UDP to
|
||||
srflx/UDP pair, with DTLS connected and no relay candidates. The receiver reports
|
||||
download storage and transfer done at 36.9 s; the sender reports awaiting-receipt
|
||||
followed by done at 64.0 s. This establishes successful direct connectivity and
|
||||
application-level completion for this attempt. The user also confirmed that the downloaded file saved and opened correctly.
|
||||
|
||||
The supplied logs do not identify the browser, STUN provider, or whether any
|
||||
network/setup settings changed. This success does not identify the cause of the
|
||||
earlier failures or demonstrate a connectivity fix in the diagnostic changes.
|
||||
The user identified the accompanying console warnings as stale and unrelated;
|
||||
they are excluded from this result.
|
||||
@@ -1,88 +0,0 @@
|
||||
# Remembered-device protocol and storage
|
||||
|
||||
Phase 3 adds optional hosted-browser identities. Temporary sessions still use
|
||||
manual fingerprint comparison.
|
||||
This is an application protocol design and implementation review, not an
|
||||
independent cryptographic audit.
|
||||
|
||||
## Authentication transcript
|
||||
|
||||
A device has an ECDSA P-256 key pair. An identity-enabled connection code
|
||||
(see `src/lib/codes.ts` for the `HC1.` encoding) uses signaling envelope
|
||||
version 4 with a public key (65-byte uncompressed point, lowercase hex) and a
|
||||
fresh 32-byte cryptographically random nonce. Both local
|
||||
and remote SDP fingerprints continue to be validated as full SHA-256 values.
|
||||
Temporary codes use version 3. Old builds reject version 4 before connecting.
|
||||
Current builds accept both; if either participant uses a temporary identity,
|
||||
both must manually verify fingerprints and no device is remembered.
|
||||
|
||||
When both codes advertise identities, each FileSession ready frame includes an
|
||||
ECDSA/SHA-256 signature. The signed UTF-8 bytes are JSON.stringify of this ordered
|
||||
array, with no optional fields:
|
||||
|
||||
```
|
||||
["HellCon device proof", 1, 4, role,
|
||||
offerPublicKey, offerNonce, answerPublicKey, answerNonce,
|
||||
offerFingerprint, answerFingerprint]
|
||||
```
|
||||
|
||||
The role is `offerer` or `answerer`. Fingerprints are uppercase hex bytes separated
|
||||
by one space. Signatures use Web Crypto's 64-byte P1363 encoding, lowercase hex.
|
||||
The recipient verifies the other role with the other public key. Both keys,
|
||||
both fresh nonces, and both DTLS certificate fingerprints are bound to the proof.
|
||||
Roles and domain/version separation prevent reflection and cross-protocol use;
|
||||
fresh contributions from both peers prevent replay into a new connection.
|
||||
The signed fingerprints bind the identity to the encrypted transport. A proof
|
||||
from another connection cannot authenticate an attacker-controlled DTLS peer.
|
||||
|
||||
Each connection opts in separately and trusts at most one public key, its paired
|
||||
device. A local user either compares both full fingerprints or connects on a
|
||||
paired connection. A connection name has no protocol meaning. A matching paired
|
||||
key permits local verification to proceed automatically, but metadata and file
|
||||
data stay gated until the peer's fresh signature verifies. Unknown, changed,
|
||||
missing, or downgraded identities require manual fingerprint comparison.
|
||||
A changed key never replaces a paired device automatically: replacing it is an
|
||||
explicit, unticked choice on the verification step. An invalid or missing
|
||||
signature in a negotiated identity session closes the session. Each file still
|
||||
requires acceptance. The session receive queue is bounded to 2 MiB while signature
|
||||
verification is pending and throughout transfers; the existing 1 MiB send windows
|
||||
remain unchanged.
|
||||
|
||||
A peer key is only saved to a connection after both peers' ready frames pass
|
||||
verification, and only if the user left **Remember this device** ticked on the
|
||||
verification step. Manual first pairing therefore authenticates the keys through
|
||||
the compared transport fingerprints and proofs. Public identities in codes are
|
||||
linkable; the UI makes this explicit before opt-in. No identities or connection
|
||||
names are added to diagnostic logs, and connection names are not sent to peers.
|
||||
|
||||
## Storage and recovery
|
||||
|
||||
The `hellcon-devices` IndexedDB store holds one CryptoKey private key and its
|
||||
public key, shared by all connections. Each record in `hellcon-connections`
|
||||
holds its own opt-in flag and paired public key. New private keys are
|
||||
non-extractable; existing stored keys remain usable.
|
||||
Browser storage does not protect against compromised app code, a hostile host,
|
||||
or compromised browser: app code can still use a stored key to sign.
|
||||
New connections are not opted in. Creating an identity opts in the connection it
|
||||
was created from. Clearing site data loses the identity and pairings; an empty
|
||||
store never creates trust automatically. Storage errors leave temporary sessions
|
||||
available. Unreadable identity storage can be explicitly cleared before creating
|
||||
a new identity and pairing again. Atomic revision checks reject stale identity
|
||||
writes from other tabs; connection records are read and written in single
|
||||
transactions. Identity deletion requires explicit consent, keeps paired devices,
|
||||
and is disabled during a session. Removing a connection forgets its device.
|
||||
Before each identity-enabled connection, the connection record and identity are
|
||||
read again from storage. A device forgotten in another tab loses automatic
|
||||
verification on the next connection, and a replaced local identity is picked up.
|
||||
A failed refresh stops setup instead of using cached trust.
|
||||
|
||||
There is no central revocation service. Peers must forget a compromised key.
|
||||
|
||||
Review checks: both role directions, substitution of either identity, alteration
|
||||
of either nonce or fingerprint, forged signatures, replay into fresh contexts,
|
||||
metadata gating during asynchronous verification, non-extractable private keys,
|
||||
and persistence/reconnection with real browser CryptoKeys. These
|
||||
checks do not replace an independent protocol review.
|
||||
|
||||
Web Crypto algorithm and key-storage reference:
|
||||
https://www.w3.org/TR/WebCryptoAPI/
|
||||
@@ -1,147 +0,0 @@
|
||||
# Serverless UX roadmap
|
||||
|
||||
The app runs over HTTPS or on localhost. The current build uses manual signaling.
|
||||
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. An experimental
|
||||
concept of reconnect works; the sections below describe the rest of the app.
|
||||
|
||||
## Connection workspace — implemented
|
||||
|
||||
The app title and connection list live in a sidebar. The first slot is **Con 1**;
|
||||
users add subsequent slots explicitly and can rename them. Selecting a slot opens
|
||||
its setup and transfer controls. Cached workspaces
|
||||
keep live sessions and file selections intact while navigating between slots.
|
||||
The sidebar collapses on mobile; network configuration is expandable.
|
||||
|
||||
IndexedDB stores slot names and paired devices. Transfer history, file contents,
|
||||
and connection codes are not stored. Slot mutations are transactional, and other
|
||||
tabs refresh their lists after changes. Storage failures show an explicit warning.
|
||||
|
||||
Disconnect and Reset keep the slot. Reloading ends live sessions and requires
|
||||
fresh codes; a slot's paired device is authenticated by fresh signed proofs, and
|
||||
setup re-reads it from storage so a device forgotten elsewhere is not trusted.
|
||||
|
||||
## 1. Send another file on a verified connection — implemented first
|
||||
|
||||
Keep the reliable data channel open after a successful receipt. The sender can
|
||||
choose or drop another file without exchanging codes or confirming fingerprints
|
||||
again. Require explicit receiver acceptance for each file. Reset counters,
|
||||
metadata, and storage per file while retaining connection verification. Preserve
|
||||
a completed memory download until the receiver accepts its replacement or resets.
|
||||
Keep network settings fixed for the session; relay consent applies to that
|
||||
connection until disconnect. Reset, disconnect, errors, and tab closure end
|
||||
the session. Idle completed sessions remain open while both tabs remain available;
|
||||
a lost connection requires fresh codes.
|
||||
|
||||
The first implementation negotiated repeat support within v2. Phase 2 supersedes
|
||||
that compatibility path with protocol v3; both peers now need the current build.
|
||||
|
||||
## 2. Multiple files and transfers in either direction — implemented
|
||||
|
||||
Session ownership is independent of the initial Send/Receive setup choice. After
|
||||
verification, Send/Receive navigates between sections while preserving the session. Both people can select or drop multiple
|
||||
files and add more while transferring. Each local queue is capped at 32 including
|
||||
its active outgoing file.
|
||||
|
||||
The arbitration decision is one sequential queue per direction, permitting two
|
||||
active files total. Simultaneous offers therefore never compete for one global
|
||||
slot. Monotonic odd/even IDs identify files by originating peer; control frames
|
||||
and binary chunks carry these IDs. Each file uses the existing bounded window,
|
||||
receive queue, receipt validation, and storage limits. The receiver accepts or
|
||||
declines every file separately. Only one incoming memory file is retained.
|
||||
|
||||
Remove affects only a waiting local item. Decline rejects an incoming offer before
|
||||
acceptance and advances the peer's queue. Disconnect cancels the whole session,
|
||||
clears queues, and aborts unfinished writes in either direction. Cancellation of
|
||||
an individual active file is intentionally not provided. Completed memory downloads
|
||||
survive disconnect until Reset or the next acceptance.
|
||||
|
||||
Protocol v3 rejects old connection codes before setup. Tests cover simultaneous
|
||||
queues, empty files, separate acceptance, removal, decline, stale IDs/receipts,
|
||||
queue caps, storage cancellation, and verification gates. Browser checks exercise
|
||||
both directions, real bytes, accessibility, and streaming downloads.
|
||||
|
||||
## 3. Remember trusted devices — implemented
|
||||
|
||||
The hosted app offers an opt-in device identity, and each connection slot can
|
||||
remember one paired device. First pairing requires manual fingerprint comparison;
|
||||
a slot is paired only after successful mutual verification. Later sessions on a
|
||||
paired slot verify fresh signed proofs bound to both keys, both nonces, both DTLS
|
||||
fingerprints, and participant roles. Slot names and saved codes never
|
||||
authenticate a peer. Changed or missing identities require manual comparison and
|
||||
never replace a paired device automatically.
|
||||
|
||||
Temporary sessions remain the default, and every file still requires acceptance.
|
||||
Forgetting devices, identity deletion, storage failure
|
||||
fallback, unreadable-storage recovery, and conflicting-tab write protection are
|
||||
implemented. Identity-enabled signaling uses v4;
|
||||
temporary connections retain v3. Browser keys remain accessible to app code.
|
||||
|
||||
Tests cover proof forgery and replay, altered session bindings, metadata gating,
|
||||
persistence across reload, changed identities,
|
||||
storage denial/recovery, and protocol-version validation. Design and review notes
|
||||
are in [the device identity protocol](device-identities.md); this is not an
|
||||
independent cryptographic audit.
|
||||
|
||||
## 4. Compressed connection codes — implemented
|
||||
|
||||
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 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,
|
||||
and disconnected. Provide recovery actions tailored to the actual failure.
|
||||
|
||||
Prefer the hosted streaming-download path when supported, retain native disk and
|
||||
bounded memory fallbacks, and explain browser download completion accurately.
|
||||
Use accessible focus management, keyboard controls, live status announcements,
|
||||
and mobile layouts. Validate both first-time and remembered-peer paths, denied
|
||||
permissions, clipboard/share fallback, browser suspension, and reconnect guidance.
|
||||
|
||||
## Delivery order and gates
|
||||
|
||||
Deliver in the order above, with a build and relevant protocol/browser checks per
|
||||
phase. Small contextual UI improvements can accompany each phase. Treat identity
|
||||
authentication and bidirectional framing as explicit design/review milestones.
|
||||
No new persistent data or backend is needed for phase 1. Deployments are separate
|
||||
from implementation; this document is the plan for the remaining phases.
|
||||
|
||||
## Later: peer mesh (exploratory, unscheduled)
|
||||
|
||||
Open HellCon tabs could assist each other so the tracker becomes a bootstrap
|
||||
fallback rather than a requirement. This is an idea, not a commitment.
|
||||
|
||||
**Peer-relayed signaling.** WebRTC only needs a channel for offer, answer and ICE
|
||||
candidates. If A has verified sessions with B and C, and B and C are paired with
|
||||
each other, A can forward their reconnect exchange over its data channels. Seal
|
||||
and authenticate the payloads with the B–C pairing key and bind them to the DTLS
|
||||
fingerprints, so A acts only as a mailbox and cannot interpose. A relay does not
|
||||
create trust: introducing unpaired devices still requires manual verification.
|
||||
Fall back to the pairing's tracker or manual codes when no shared peer is open.
|
||||
|
||||
**Multi-source transfers.** Split a file into pieces hashed under a manifest
|
||||
signed by the original sender. Any verified peer that holds pieces can serve
|
||||
them; receivers check every piece against the manifest. Once one complete copy
|
||||
exists, the sender may leave. Requesting only missing pieces also allows resuming
|
||||
an interrupted transfer. This stays inside verified HellCon sessions: no public
|
||||
swarms, no BitTorrent interoperability, and acceptance is still required per file.
|
||||
|
||||
**Limits.** "Online" means an open tab; browsers cannot listen in the background
|
||||
and service workers cannot hold WebRTC connections, so there is still no presence
|
||||
or offline wake-up. Relayed signaling does not help NAT traversal; STUN and
|
||||
explicit TURN consent remain unchanged. The relay sees which of its peers connect
|
||||
to each other.
|
||||
|
||||
**Preparation.** Keep the tracker reconnect adapter's announce/offer/answer layer
|
||||
independent of the pairing logic and of its transport, so a data channel can carry
|
||||
the same sealed exchange later.
|
||||
@@ -1,348 +0,0 @@
|
||||
# WebTorrent tracker reconnect (experimental concept)
|
||||
|
||||
This replaces the custom rendezvous server proposal. HellCon will exchange fresh
|
||||
connection codes through a configurable WebTorrent-compatible WebSocket tracker,
|
||||
using a small client adapter built on native browser APIs. Deploy an existing
|
||||
tracker implementation; do not add Trystero or the WebTorrent file-transfer
|
||||
client to HellCon. Nostr is outside this plan.
|
||||
|
||||
The [repository-owned tracker container](../tracker/README.md) now provides the
|
||||
development/deployment foundation, using an official Node base and a locked
|
||||
upstream package. A first browser implementation exists to prove the concept;
|
||||
see [Concept status](#concept-status) for what it covers and what is still open.
|
||||
|
||||
Client independence takes priority: anyone can clone, fork, self-host or modify
|
||||
HellCon and choose their own tracker. The client must work with any compatible
|
||||
tracker and must not depend on a particular operator or on HellCon-specific
|
||||
server extensions. Vue remains the only runtime dependency.
|
||||
|
||||
## User experience and scope
|
||||
|
||||
A paired connection gets a **Reconnect** button. Both people open that connection
|
||||
and press Reconnect; the app negotiates a new WebRTC connection and authenticates
|
||||
the remembered device. Both pages must be open. Files still require acceptance.
|
||||
Manual code exchange remains available for initial pairing and recovery.
|
||||
|
||||
Network settings gain an independent **Connection discovery** section:
|
||||
|
||||
- **Manual codes**, **Default tracker**, or **Custom tracker**.
|
||||
- Custom tracker: one `wss://` URL, including any required path.
|
||||
- The default URL comes from `VITE_TRACKER_URL`; if unset, offer Manual and Custom.
|
||||
- Show the selected host and explain that it can observe which clients meet.
|
||||
- Leave STUN selection and explicit TURN consent as separate controls.
|
||||
- The selection applies to new pairings; existing pairings keep their stored
|
||||
trackers.
|
||||
|
||||
There is no public peer directory, background presence, offline wake-up, file
|
||||
storage, torrent file generation, DHT, or BitTorrent piece transfer. The tracker
|
||||
only handles discovery and signaling. Reconnecting establishes a new session;
|
||||
it does not resume an interrupted file transfer.
|
||||
|
||||
The first release contacts one agreed tracker per pairing, but pairings store
|
||||
and negotiate an ordered tracker list so fallback trackers can be added later
|
||||
without a storage migration or pairing protocol change. Contacting several
|
||||
trackers and automatic fallback between operators are deferred. Selecting an
|
||||
endpoint is not authorization to contact additional public trackers.
|
||||
|
||||
## Pairing and persistence
|
||||
|
||||
After mutual device verification on a manual connection, both users can enable
|
||||
**Reconnect using this tracker**. This opt-in is separate from remembering a
|
||||
device and starts unticked. The manual session's offerer proposes the selected
|
||||
tracker URL; the recipient sees and confirms it before the app stores or
|
||||
contacts it.
|
||||
|
||||
Add a versioned pairing exchange to the authenticated data channel. Both peers
|
||||
contribute 32 random bytes. Derive a shared HKDF-SHA-256 base key from the ordered
|
||||
contributions and a context binding both device keys and connection fingerprints.
|
||||
Use an unambiguous, versioned encoding and separate derivation labels for each
|
||||
purpose. Store the base key as a non-extractable CryptoKey.
|
||||
|
||||
The connection record stores the paired key, the local identity public key used
|
||||
for pairing, the shared key, the agreed ordered list of concrete tracker URLs (one
|
||||
entry in the first release), and the reconnect
|
||||
protocol version. Resolve Default to a concrete URL at pairing time: changing a
|
||||
build default must not silently move existing pairings to another operator.
|
||||
|
||||
Both peers acknowledge the pairing settings over the verified channel before
|
||||
showing reconnect as configured. An interrupted exchange or storage failure can
|
||||
leave only one peer configured; show the failure and allow manual setup to repair
|
||||
the pairing. Do not claim atomic persistence across two browsers.
|
||||
|
||||
Forget device, Remove connection, identity deletion/replacement, or replacement
|
||||
of the paired device invalidates reconnect credentials. Re-read identity and
|
||||
pairing state before each attempt and propagate local revocation across tabs.
|
||||
Clearing browser storage loses pairing. A non-extractable key remains usable by
|
||||
trusted application code; it does not protect against a compromised app host.
|
||||
|
||||
Changing a pairing's tracker requires coordination. While connected, propose and
|
||||
confirm the replacement over the authenticated channel. If the old tracker is
|
||||
unavailable, exchange manual codes to agree on a replacement. A local edit alone
|
||||
cannot inform an offline peer.
|
||||
|
||||
## Client architecture
|
||||
|
||||
Keep `src/lib/webrtc.ts`, device proofs, and the existing file session as the
|
||||
transport and authentication foundation. Separate setup lifecycle code from
|
||||
`TransferPanel.vue` so manual and tracker setup can feed the same session without
|
||||
duplicating verification, cancellation, TURN consent, or transfer behavior.
|
||||
|
||||
Introduce focused modules for pairing storage/derivation, encrypted signaling,
|
||||
and the WebSocket tracker adapter. The adapter handles tracker announcements,
|
||||
offer routing, answers, retries, and cleanup. It never receives file contents.
|
||||
|
||||
Use native `WebSocket`, `RTCPeerConnection`, and Web Crypto. Basic WebTorrent
|
||||
tracker signaling requires no Nostr-style Schnorr signature library. Preserve
|
||||
HellCon's P-256 identity proofs; tracker peer IDs are routing identifiers only.
|
||||
Server-side dependencies are maintained separately from the browser bundle.
|
||||
|
||||
Keep the encrypted signaling exchange independent of the WebSocket transport.
|
||||
The [peer mesh idea](ux-roadmap.md#later-peer-mesh-exploratory-unscheduled) may
|
||||
later let an open, verified peer forward the same sealed exchange over a data
|
||||
channel, leaving the tracker as a fallback. That idea is unscheduled and not part
|
||||
of this plan.
|
||||
|
||||
## Discovery and encrypted signaling
|
||||
|
||||
Derive a 20-byte discovery identifier from the pairing secret with a dedicated
|
||||
HKDF label and UTC day. Use it as the tracker's `info_hash`; it identifies a
|
||||
private pairing, not a file. Derive a separate AES-256-GCM signaling key with a
|
||||
different label. Near UTC midnight, temporarily join adjacent day identifiers,
|
||||
deduplicate attempts, and close the unused route. Estimate clock skew from the
|
||||
`Date` header of a same-origin response where available, and report skew beyond
|
||||
the expiry tolerance.
|
||||
|
||||
Randomize the 20-byte tracker `peer_id` per reconnect attempt and keep it stable
|
||||
only for that attempt. The peer that finds the other already registered sends
|
||||
the offer: announce responses report swarm counts, so the second arrival can
|
||||
gather a fresh offer immediately. If both offer at once, the offer from the
|
||||
lower paired device public key wins and the other peer discards its own. Reject
|
||||
equal identities for this automatic role scheme and leave manual setup available.
|
||||
|
||||
Use the WebSocket tracker's normal `announce`, `offers`, `offer_id`, `answer`,
|
||||
and `to_peer_id` fields. Encode 20-byte identifiers as the protocol's binary
|
||||
strings inside JSON, not hex strings. Use constant placeholder transfer counters
|
||||
where needed; never expose actual filenames or transferred byte counts.
|
||||
|
||||
Carry a versioned encrypted HellCon envelope in the offer/answer `sdp` string,
|
||||
following the opaque-payload approach used by Trystero. The decrypted envelope
|
||||
contains the complete HellCon identity-enabled code. Only decrypted and validated
|
||||
SDP reaches `setRemoteDescription`. This is a HellCon signaling convention over
|
||||
a tracker protocol, not interoperability with ordinary torrent clients or with
|
||||
Trystero rooms.
|
||||
|
||||
Each envelope uses a fresh random 96-bit AES-GCM IV. Authenticate the protocol
|
||||
version, discovery identifier, offer ID, message role, source peer ID, and answer
|
||||
destination in unambiguously encoded associated data. Include attempt nonces and
|
||||
an expiry inside the ciphertext; answers must bind the outstanding offer nonce.
|
||||
Fix the allowed clock skew together with the encoding.
|
||||
Freeze the exact encoding and publish test vectors before implementation ships.
|
||||
|
||||
Track outstanding offers and bounded duplicate caches. Ignore exact retransmits,
|
||||
reject mismatched answers, and never reuse an offer from a disposed peer
|
||||
connection. Expiry and duplicate checks reduce replay; they do not guarantee
|
||||
that a captured offer is undeliverable after browser reload. Fresh device proofs
|
||||
bound to both session nonces and fingerprints remain mandatory before releasing
|
||||
file metadata. Invalid or changed identity ends automatic reconnect; switching
|
||||
to manual verification requires a deliberate new manual setup.
|
||||
|
||||
## Connection lifecycle and failure handling
|
||||
|
||||
Trackers forward offers only to peers already registered; registration alone
|
||||
does not guarantee delivery. The first arrival registers without offers and
|
||||
keeps its registration alive at the tracker interval; the second arrival offers.
|
||||
If a tracker reports no usable counts, fall back to bounded periodic offers and
|
||||
gather a fresh offer for each one: never resend an offer whose candidates may
|
||||
have expired. Configure our tracker for interactive discovery. Respect custom
|
||||
tracker pacing and show a waiting state rather than assuming immediate matching.
|
||||
|
||||
Limit each slot to one reconnect attempt per browser profile with a Web Locks
|
||||
(`navigator.locks`) lock; propagate revocation through the existing
|
||||
`BroadcastChannel`. Bound in-flight negotiations, frame sizes, peer counts and
|
||||
retry state. Multiple tabs or a third party must not cause unbounded peer
|
||||
allocation. Do not assume the tracker enforces two clients per room.
|
||||
|
||||
Trackers deliver each offer to a random registered peer, so a third peer in the
|
||||
swarm can receive an offer meant for the paired device and stall the attempt.
|
||||
Send at most one offer per counted peer, up to a small cap, and report this as
|
||||
a failed attempt, not an authentication failure; it denies service but cannot
|
||||
authenticate as the paired device.
|
||||
|
||||
Use a five-minute total attempt deadline and retain the existing ICE gathering
|
||||
limit. Validate incoming frames before decrypting or creating peers. Handle
|
||||
tracker rejection, malformed data, socket loss, an absent peer, stale answers,
|
||||
and authentication failure with specific errors and a manual-code recovery path.
|
||||
|
||||
After mutual authentication, stop announcing, send a best-effort stopped event,
|
||||
and close the tracker socket. Cancel, timeout and Reset also dispose timers,
|
||||
sockets and pending WebRTC peers. Tracker loss after setup does not interrupt
|
||||
an established transfer. A later reconnect creates fresh signaling state.
|
||||
|
||||
## Compatibility and rollout
|
||||
|
||||
Plan signaling v5 for identity-enabled sessions to negotiate the pairing exchange
|
||||
and bind that version into device proofs. Temporary manual v3 sessions remain
|
||||
available. Existing paired v4 slots retain their trusted device key but require
|
||||
one new manual session on compatible builds to enable tracker reconnect.
|
||||
|
||||
Use an IndexedDB schema migration without dropping names, history or trust.
|
||||
Clearing reconnect settings must not delete unrelated connection history.
|
||||
Document version mismatch errors and make the tracker mode's capabilities
|
||||
explicit; an older HellCon client must not silently skip authentication.
|
||||
|
||||
## Self-hosting and custom endpoints
|
||||
|
||||
Run a pinned release of `webtorrent/bittorrent-tracker` with WebSocket support in
|
||||
a dedicated container behind the existing HTTPS reverse proxy. Expose a single
|
||||
`wss://` endpoint; disable UDP/HTTP tracker APIs and public statistics. Keep the
|
||||
backend port private. Build the image from a pinned package version and
|
||||
lockfile; the tracker never enters HellCon's `package.json`. Run it from Compose
|
||||
for local development, as with coturn, and set explicit CPU/memory, connection,
|
||||
frame-size and request-rate limits in the deployment configuration.
|
||||
|
||||
The reverse proxy alone provides no rate limiting. Where the pinned release lacks
|
||||
per-IP limits, swarm caps or origin checks, the container runs a small start
|
||||
script around the tracker library that adds them and trusts forwarded client
|
||||
addresses only from the proxy. These are operator protections: the client must
|
||||
not depend on them, and custom trackers without them must still work.
|
||||
|
||||
Configure short announcement intervals and cleanup of stale peers and empty
|
||||
swarms. Bound the total number of swarms as well as peers per swarm. Disable
|
||||
payload/debug logging and identifying access logs on the tracker path. Health
|
||||
checks and aggregate metrics must not expose pairing identifiers or IPs.
|
||||
Origin checks can restrict normal browser use but cannot authenticate arbitrary
|
||||
clients or prevent deliberate abuse.
|
||||
|
||||
For Custom, require a valid `wss://` URL without embedded credentials or a fragment;
|
||||
allow `ws://` loopback only in local development. Do not implement arbitrary
|
||||
tracker-specific login schemes in the first release. Unsupported authentication
|
||||
or payload policies produce a clear error.
|
||||
|
||||
To support arbitrary user-selected secure WebSocket endpoints, the hosted build
|
||||
will need `connect-src 'self' wss:` in place of its current self-only policy.
|
||||
This deliberately trades a narrower exfiltration boundary for client
|
||||
independence; document the broader network permission. Self-hosters may retain
|
||||
an explicit
|
||||
host allowlist; the UI must explain when their CSP blocks a custom endpoint.
|
||||
|
||||
Public tracker compatibility is a release gate, not a blanket promise. Verify
|
||||
encrypted offer forwarding, identifier encoding, payload limits, announcement
|
||||
timing and usage policy against the selected implementation. Record the tested
|
||||
server version and configuration. No public tracker is bundled without a policy
|
||||
and availability review.
|
||||
|
||||
## Privacy limits
|
||||
|
||||
The tracker sees connecting IPs, Origin, discovery identifiers, temporary peer
|
||||
IDs, routing fields, timing and ciphertext sizes. It can associate the clients
|
||||
it matches. Other clients may also observe or probe discovery identifiers if a
|
||||
tracker exposes them. An unguessable identifier helps against guessing; the
|
||||
pairing secret and device proofs protect access even if that identifier leaks.
|
||||
|
||||
Rotating identifiers removes a stable protocol label but does not prevent IP or
|
||||
timing correlation. No-log configuration reduces retained data; it cannot stop
|
||||
a malicious operator recording traffic. Self-hosting changes who observes this
|
||||
metadata. Direct WebRTC traffic also exposes endpoints to network observers.
|
||||
The feature provides convenient encrypted signaling, not anonymity.
|
||||
|
||||
## Implementation steps and acceptance checks
|
||||
|
||||
1. Prove interoperability with a pinned tracker: two native WebSocket clients
|
||||
exchange bounded opaque offer/answer payloads in both arrival orders. Confirm
|
||||
that announce responses count WebSocket peers and that a maximum-size code
|
||||
fits the frame limit after encryption and encoding. Resolve tracker
|
||||
restrictions before building the UI.
|
||||
2. Add pairing negotiation, migration and revocation; test matching derivations,
|
||||
domain separation, day boundaries, interrupted pairing and storage failures.
|
||||
3. Add encrypted envelopes and the adapter; test tampering, replay, duplicate
|
||||
routing, stale answers, third peers, retry bounds and complete cancellation.
|
||||
4. Integrate discovery settings and Reconnect with the existing setup lifecycle.
|
||||
Pair two browsers manually, reload both, reconnect without copying codes,
|
||||
authenticate the saved peer and transfer exact bytes in both directions.
|
||||
5. Verify Chromium/Firefox combinations, real separate-device networks, explicit
|
||||
TURN use, tracker outage, endpoint changes, clock skew, cross-tab attempts,
|
||||
forgotten devices and manual fallback. Local success alone is insufficient.
|
||||
6. Validate the deployment's TLS, CSP, rate/resource limits, cleanup, log behavior
|
||||
and upgrade procedure. Update user documentation only when the feature ships.
|
||||
|
||||
Maintenance centers on the pinned tracker and its dependencies, browser/network
|
||||
behavior, and the small HellCon adapter. Keep a reproducible local tracker fixture
|
||||
so upgrades can run the same interoperability and reconnect checks. Supporting
|
||||
additional discovery protocols would add independent maintenance and test paths.
|
||||
|
||||
## Concept status
|
||||
|
||||
Implemented in `src/lib/reconnect.ts` (pairing derivation, discovery identifier,
|
||||
sealed envelopes), `src/lib/tracker.ts` (WebSocket adapter and attempt logic) and
|
||||
`TransferPanel.vue`:
|
||||
|
||||
- Setup runs over a verified session whose peer proved the paired device key.
|
||||
Either person proposes a tracker URL; the peer sees the host and accepts or
|
||||
declines. Both contribute 32 random bytes; the HKDF context binds both device
|
||||
keys, both fingerprints of that session and the tracker URL. The proposer
|
||||
stores first, then the acceptor; each waits for its IndexedDB write, and the
|
||||
acceptor acknowledges its completed write before the proposer reports success.
|
||||
A failed write on either side is reported to both people, and the proposer
|
||||
removes its stored copy again if the acceptor's write failed. The base key is
|
||||
a non-extractable CryptoKey in the connection record, which Forget device, a
|
||||
replaced paired device and **Turn off reconnect** clear. A changed local
|
||||
identity blocks the attempt.
|
||||
- Every session that authenticates the paired device exchanges a 128-bit check
|
||||
value derived from the stored pairing (or an empty value without one) over
|
||||
the encrypted session. On a mismatch, the side holding a pairing turns it off
|
||||
and says so. This repairs interrupted setups, and **Turn off reconnect** on
|
||||
one device reaches the other at the next manual session. A match shows the
|
||||
pairing as set up on both devices.
|
||||
- **Connection discovery** in Network settings: Manual codes only, Default
|
||||
tracker (only when `VITE_TRACKER_URL` is set) or Custom tracker. The choice is
|
||||
a per-browser preference in `localStorage`, stays editable during a session,
|
||||
and is resolved to a concrete URL when setup is proposed; existing pairings
|
||||
keep their tracker.
|
||||
- The discovery identifier is derived per UTC day; envelopes are AES-256-GCM with
|
||||
a random IV, the role, info_hash, offer ID, source and destination peer IDs
|
||||
as associated data, and a two-minute lifetime with five minutes' tolerance.
|
||||
The decrypted code passes the usual `decodeCode` checks, and the peer's
|
||||
identity key must equal the paired key; fresh device proofs then authenticate
|
||||
the session as before.
|
||||
- Roles differ from the plan above: the lower device key always offers and
|
||||
creates the data channel, so there is no glare. If the other device arrives
|
||||
second, it announces a sealed, codeless **wake** that makes the initiator
|
||||
offer at once. Swarm counts from announce responses (which include the
|
||||
announcing peer) trigger the same. Offers and wakes are spaced 15 seconds apart
|
||||
and capped at 12; each offer uses a fresh peer connection. Envelopes that do
|
||||
not open are ignored, so other clients in a swarm cannot disturb it beyond
|
||||
receiving offers they cannot read.
|
||||
- One attempt per slot and browser profile via Web Locks, a five-minute
|
||||
deadline, a 15-second keepalive announce, `stopped` and socket close on
|
||||
success, cancel, reset, failure and unmount.
|
||||
|
||||
Checked on 2026-10-20 with `node scripts/browser-check.ts --tracker=<url>` against
|
||||
`wss://tracker.openwebtorrent.com` and `wss://tracker.webtorrent.dev`: pairing
|
||||
setup, reload of both pages, Reconnect without codes, device proofs and exact
|
||||
bytes in both directions, both roles. Both trackers report swarm counts, route
|
||||
binary 20-byte identifiers unchanged and remove peers on `stopped`.
|
||||
tracker.openwebtorrent.com relayed 56 KB payloads, tracker.webtorrent.dev 12 KB;
|
||||
typical sealed codes are a few KB. Neither tracker is bundled.
|
||||
|
||||
Still open before this can ship:
|
||||
|
||||
- Firefox and real separate-device networks, tracker outage and cross-tab
|
||||
behavior (step 5), `connect-src` for the hosted CSP, and the deployment checks.
|
||||
- Clock-skew detection and a frozen envelope encoding with published test vectors.
|
||||
|
||||
Deliberately not planned for now:
|
||||
|
||||
- Signaling v5. Pairing messages ride the v3 session protocol, so an outdated
|
||||
peer rejects them; reloading the page updates it.
|
||||
- Joining adjacent day identifiers around UTC midnight. If one person presses
|
||||
Reconnect just before UTC midnight and the other just after, they miss each
|
||||
other until the first presses Reconnect again.
|
||||
- An interrupted setup is not atomic across two browsers; the check in the
|
||||
next authenticated session removes a one-sided pairing.
|
||||
|
||||
## References
|
||||
|
||||
- [WebTorrent tracker server and client](https://github.com/webtorrent/bittorrent-tracker)
|
||||
- [WebSocket request parsing](https://github.com/webtorrent/bittorrent-tracker/blob/master/lib/server/parse-websocket.js)
|
||||
- [Trystero tracker adapter, for protocol reference](https://github.com/dmotz/trystero/blob/main/packages/torrent/src/index.ts)
|
||||
- [Existing device authentication](device-identities.md)
|
||||
+1482
File diff suppressed because it is too large.
Load diff
+6
-1
@@ -5,8 +5,13 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet" />
|
||||
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; style-src 'self'; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'none'; form-action 'none'"
|
||||
/>
|
||||
<link rel="icon" type="image/png" href="./HellNet_alt.png" />
|
||||
<title>HellCon — P2P File Share</title>
|
||||
<title>HellCon</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
+22
-22
@@ -1,38 +1,38 @@
|
||||
{
|
||||
"name": "hellcon",
|
||||
"private": true,
|
||||
"version": "0.0.6",
|
||||
"version": "1.0.2",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:setup": "node scripts/dev-setup.ts",
|
||||
"turn:up": "docker compose --env-file .env.development up -d",
|
||||
"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 && docker run --rm hellcon-tracker:test",
|
||||
"test:turn": "node scripts/browser-check.ts --turn",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"build": "vue-tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test tests/*.test.ts",
|
||||
"test:browser": "node scripts/browser-check.ts",
|
||||
"test:download": "node scripts/browser-check.ts --stream-download",
|
||||
"test:cross-browser": "node scripts/cross-browser-check.ts",
|
||||
"typecheck": "vue-tsc --noEmit"
|
||||
"typecheck": "vue-tsc",
|
||||
"lint": "biome check",
|
||||
"format": "biome check --write",
|
||||
"test": "vitest run && playwright test",
|
||||
"test:unit": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"test:install": "playwright install chromium firefox",
|
||||
"test:large": "LARGE=1 playwright test -g large"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.44"
|
||||
"vue": "^3.5.45"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^26.6.5",
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"axe-core": "^4.14.0",
|
||||
"@biomejs/biome": "2.6.3",
|
||||
"@playwright/test": "^1.65.0",
|
||||
"@types/node": "^26.6.6",
|
||||
"@vitejs/plugin-vue": "^6.0.11",
|
||||
"typescript": "~6.0.3",
|
||||
"vite": "^8.3.4",
|
||||
"vue-tsc": "^3.3.13"
|
||||
"vite": "^8.3.8",
|
||||
"vitest": "^5.1.0",
|
||||
"vue-tsc": "^3.3.14",
|
||||
"ws": "8.23.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18.0"
|
||||
}
|
||||
"node": ">=26.13.1"
|
||||
},
|
||||
"packageManager": "pnpm@12.16.1"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
// src/core.test.ts is Vitest's, see vite.config.ts. Loaded by Playwright, its vi.mock fails the whole run.
|
||||
export default defineConfig({ testIgnore: 'src/**' });
|
||||
Generated
+1382
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
minimumReleaseAgeExclude:
|
||||
- ws@8.23.0
|
||||
@@ -1,70 +0,0 @@
|
||||
/* Only handles single-use download URLs within this directory. No file uploads or cache. */
|
||||
const downloads = new Map();
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', event => event.waitUntil(self.clients.claim()));
|
||||
self.addEventListener('message', event => {
|
||||
const { type, id, name, size, stream } = event.data || {};
|
||||
const port = event.ports[0];
|
||||
if (type !== 'download' || !port || !/^[a-f0-9]{32}$/.test(id) ||
|
||||
typeof name !== 'string' || name.length > 255 || /[\r\n/\\]/.test(name) ||
|
||||
!Number.isSafeInteger(size) || size < 0 ||
|
||||
!(stream instanceof ReadableStream) || downloads.has(id)) return;
|
||||
const reader = stream.getReader();
|
||||
let controller, finished = false, received = 0;
|
||||
const finish = error => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
downloads.delete(id);
|
||||
if (error) {
|
||||
controller?.error(error);
|
||||
void reader.cancel(error.message).catch(() => {});
|
||||
}
|
||||
port.postMessage({ type: error ? 'error' : 'complete', message: error?.message });
|
||||
port.close();
|
||||
};
|
||||
const timer = setTimeout(() => finish(new Error('Download did not start in time.')), 60000);
|
||||
const body = new ReadableStream({
|
||||
start(value) { controller = value; },
|
||||
async pull() {
|
||||
try {
|
||||
const { done, value } = await reader.read();
|
||||
if (finished) return;
|
||||
if (done) {
|
||||
if (received !== size) throw new Error('Incomplete download.');
|
||||
controller.close(); finish();
|
||||
} else {
|
||||
if (!(value instanceof Uint8Array) || value.byteLength > 16 * 1024 || received + value.byteLength > size) throw new Error('Invalid download data.');
|
||||
received += value.byteLength;
|
||||
controller.enqueue(value);
|
||||
}
|
||||
} catch (error) { finish(error); }
|
||||
},
|
||||
cancel() { finish(new Error('Download canceled in the browser.')); },
|
||||
}, { highWaterMark: 0 });
|
||||
port.onmessage = event => {
|
||||
if (event.data?.type === 'abort') finish(new Error('Transfer canceled.'));
|
||||
};
|
||||
downloads.set(id, { body, name, size, timer, port });
|
||||
port.postMessage({ type: 'ready', url: new URL(`file-${id}`, self.registration.scope).href });
|
||||
});
|
||||
self.addEventListener('fetch', event => {
|
||||
const url = new URL(event.request.url);
|
||||
const base = new URL(self.registration.scope);
|
||||
if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname + 'file-')) return;
|
||||
const id = url.pathname.slice((base.pathname + 'file-').length);
|
||||
const download = downloads.get(id);
|
||||
if (event.request.method !== 'GET' || !download) {
|
||||
event.respondWith(new Response('Download expired.', { status: 404 })); return;
|
||||
}
|
||||
downloads.delete(id);
|
||||
clearTimeout(download.timer);
|
||||
download.port.postMessage({ type: 'started' });
|
||||
event.respondWith(new Response(download.body, { headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(download.name.toWellFormed()).replace(/['()*]/g, char => '%' + char.charCodeAt(0).toString(16))}`,
|
||||
'Content-Length': String(download.size),
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
} }));
|
||||
});
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
// Streams received files into the browser's download manager. It is the only script besides the app
|
||||
// because service workers can only be registered from a same-origin script URL. Registered with the
|
||||
// scope download/ by src/download.ts, its counterpart in the page, it sees no other requests.
|
||||
|
||||
// Of the messages with the page, see VERSION in src/download.ts.
|
||||
const VERSION = 1;
|
||||
|
||||
// Downloads by id while the page sends chunks: the queue, the stream controller, its wake up, the
|
||||
// reply port and how many bytes the download manager has read.
|
||||
const downloads = new Map();
|
||||
// Responses by download id, until the download navigation fetches them. Each is served only once.
|
||||
const responses = new Map();
|
||||
// The page pings every KEEPALIVE while a transfer stalls, see src/download.ts. Silent for this long,
|
||||
// it is gone, e.g. its tab was closed: Firefox would stop this worker 30 s after the last event and
|
||||
// save the truncated file as complete. A failed stream leaves the download failed instead. A page
|
||||
// that is still there, only late, e.g. throttled in the background, is told with silent.
|
||||
const SILENCE = 20_000;
|
||||
|
||||
function watch(id, download) {
|
||||
clearTimeout(download.watchdog);
|
||||
download.watchdog = setTimeout(() => {
|
||||
download.controller.error(new Error('the page is gone'));
|
||||
forget(id);
|
||||
download.port.postMessage('silent');
|
||||
}, SILENCE);
|
||||
}
|
||||
|
||||
function forget(id) {
|
||||
clearTimeout(downloads.get(id)?.watchdog);
|
||||
downloads.delete(id);
|
||||
}
|
||||
|
||||
function open(id, { version, name, size }, port) {
|
||||
if (version !== VERSION) return port.postMessage('outdated');
|
||||
// The page checks the sender's offer already. Anything else would throw below or lie to the browser.
|
||||
if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
|
||||
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
|
||||
const body = new ReadableStream(
|
||||
{
|
||||
start: (controller) => (download.controller = controller),
|
||||
// With highWaterMark 0 the download manager pulls only when it wants more, so reaching the end
|
||||
// marker here means it has read every byte.
|
||||
async pull(controller) {
|
||||
while (!download.chunks.length) await new Promise((resolve) => (download.wake = resolve));
|
||||
const chunk = download.chunks.shift();
|
||||
if (chunk) {
|
||||
download.read += chunk.byteLength;
|
||||
// Every MiB, the receiver forwards it to the sender for its flow control window.
|
||||
if (download.read - download.reported >= 2 ** 20) {
|
||||
download.reported = download.read;
|
||||
port.postMessage(download.read);
|
||||
}
|
||||
return controller.enqueue(chunk);
|
||||
}
|
||||
controller.close();
|
||||
forget(id);
|
||||
port.postMessage('finished');
|
||||
},
|
||||
// The user cancelled the download.
|
||||
cancel: () => {
|
||||
forget(id);
|
||||
port.postMessage('cancelled');
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
downloads.set(id, download);
|
||||
watch(id, download);
|
||||
|
||||
// RFC 8187 encoding, which leaves nothing in the name that could end the header value.
|
||||
const encoded = encodeURIComponent(name.toWellFormed()).replace(
|
||||
/['()*]/g,
|
||||
(char) => `%${char.charCodeAt(0).toString(16)}`,
|
||||
);
|
||||
const headers = {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Length': String(size),
|
||||
'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
|
||||
};
|
||||
responses.set(id, new Response(body, { headers }));
|
||||
port.postMessage('ready');
|
||||
}
|
||||
|
||||
// The page posts its version and the metadata with a reply port first, then every chunk as its own
|
||||
// message and finally done (queued as the end marker null) or an error. Pings come in between.
|
||||
self.addEventListener('message', ({ data, ports: [port] }) => {
|
||||
if (port) return open(data.id, data, port);
|
||||
const download = downloads.get(data.id);
|
||||
if (!download) return;
|
||||
watch(data.id, download);
|
||||
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/download.ts.
|
||||
if (data.ping) return;
|
||||
if (data.error) {
|
||||
download.controller.error(new Error(data.error));
|
||||
forget(data.id);
|
||||
download.port.postMessage('failed');
|
||||
} else {
|
||||
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
|
||||
download.wake();
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const id = new URL(event.request.url).pathname.split('/').pop();
|
||||
// download/ itself is the empty page src/download.ts keeps open to hold this worker during a transfer.
|
||||
if (!id)
|
||||
return event.respondWith(
|
||||
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
|
||||
);
|
||||
const response = responses.get(id);
|
||||
responses.delete(id);
|
||||
event.respondWith(response ?? new Response('download expired', { status: 404 }));
|
||||
});
|
||||
@@ -1,828 +0,0 @@
|
||||
// Dependency-free Chromium integration check. Run after `bun run build`.
|
||||
import { Readable, Writable } from 'node:stream';
|
||||
import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts';
|
||||
import { CODE_PREFIX, decodeCode } from '../src/lib/codes.ts';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createServer } from 'node:http';
|
||||
import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const axeSource = await readFile(join(root, 'node_modules/axe-core/axe.min.js'), 'utf8');
|
||||
const provider = process.argv.includes('--default-network') ? 'pagequit' : 'none';
|
||||
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-'));
|
||||
const server = createServer(async (req, res) => {
|
||||
if (vite) return vite.middlewares(req, res);
|
||||
try {
|
||||
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
|
||||
const base = join(root, 'dist');
|
||||
const path = resolve(base, '.' + (pathname === '/' ? '/index.html' : pathname));
|
||||
if (!path.startsWith(base + '/')) throw new Error('Invalid path');
|
||||
const types: Record<string, string> = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png', '.svg': 'image/svg+xml' };
|
||||
res.setHeader('Content-Type', types[extname(path)] || 'application/octet-stream');
|
||||
res.end(await readFile(path));
|
||||
} catch { res.statusCode = 404; res.end(); }
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== 'string');
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [
|
||||
'--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking',
|
||||
'--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank',
|
||||
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
|
||||
interface ProtocolResults {
|
||||
'Emulation.setDeviceMetricsOverride': object;
|
||||
'Emulation.setFocusEmulationEnabled': object;
|
||||
'Page.captureScreenshot': { data: string };
|
||||
'Page.bringToFront': object;
|
||||
'Input.dispatchKeyEvent': object;
|
||||
'Browser.setDownloadBehavior': object;
|
||||
'Target.createTarget': { targetId: string };
|
||||
'Target.attachToTarget': { sessionId: string };
|
||||
'Runtime.enable': object;
|
||||
'Page.enable': object;
|
||||
'Page.navigate': object;
|
||||
'Page.addScriptToEvaluateOnNewDocument': object;
|
||||
'Runtime.evaluate': { exceptionDetails?: unknown; result: { value?: unknown } };
|
||||
}
|
||||
interface ProtocolMessage {
|
||||
id?: number;
|
||||
method?: string;
|
||||
params?: { exceptionDetails?: unknown };
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
}
|
||||
const pipeIn = browser.stdio[3], pipeOut = browser.stdio[4];
|
||||
assert.ok(pipeIn instanceof Writable && pipeOut instanceof Readable && browser.stderr);
|
||||
const commandPipe = pipeIn;
|
||||
let stderr = '', nextId = 0, buffer = '';
|
||||
const pending = new Map<number, (message: ProtocolMessage) => void>();
|
||||
const browserErrors: unknown[] = [];
|
||||
browser.stderr.on('data', data => { stderr += data; });
|
||||
pipeIn.on('error', () => {}); pipeOut.on('error', () => {});
|
||||
pipeOut.on('data', data => {
|
||||
buffer += data;
|
||||
let end;
|
||||
while ((end = buffer.indexOf('\0')) !== -1) {
|
||||
const message: ProtocolMessage = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1);
|
||||
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
|
||||
if (message.method === 'Runtime.exceptionThrown') browserErrors.push(message.params?.exceptionDetails);
|
||||
}
|
||||
});
|
||||
function call<M extends keyof ProtocolResults>(method: M, params: Record<string, unknown> = {}, sessionId?: string): Promise<ProtocolResults[M]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++nextId;
|
||||
const timer = setTimeout(() => { pending.delete(id); reject(new Error(`Timed out: ${method}\n${stderr.slice(-1500)}`)); }, 45000);
|
||||
pending.set(id, message => { clearTimeout(timer); message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result as ProtocolResults[M]); });
|
||||
commandPipe.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');
|
||||
});
|
||||
}
|
||||
async function evaluate<T, Args extends unknown[]>(session: string, fn: (...args: Args) => T, ...args: Args): Promise<Awaited<T>> {
|
||||
const expression = `(${fn.toString()})(...${JSON.stringify(args)})`;
|
||||
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
// CDP returns the serialized result of this exact callback.
|
||||
return result.result.value as Awaited<T>;
|
||||
}
|
||||
async function wait(session: string, check: () => unknown) {
|
||||
const expression = `window.__hellcon.wait(${check.toString()})`;
|
||||
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
}
|
||||
async function page(url = origin) {
|
||||
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
|
||||
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
|
||||
await call('Runtime.enable', {}, sessionId);
|
||||
await call('Page.enable', {}, sessionId);
|
||||
// Background tabs otherwise skip focus/blur events, which the name editor relies on.
|
||||
await call('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId);
|
||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
|
||||
// The native picker would block headless runs; simulateSlowDisk installs a test double where needed.
|
||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId);
|
||||
// Without streaming downloads the app falls back to memory, whose bytes the default checks read in-page.
|
||||
if (!streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: "Object.defineProperty(navigator, 'serviceWorker', { value: undefined });" }, sessionId);
|
||||
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++) {
|
||||
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));
|
||||
}
|
||||
try { await wait(sessionId, () => !!document.querySelector('#stun-provider')); }
|
||||
catch (error) { throw new Error(`${url}: ${String(error)}; browser errors: ${JSON.stringify(browserErrors)}`); }
|
||||
return sessionId;
|
||||
}
|
||||
async function checkAccessibility(session: string, mode: string) {
|
||||
const injected = await call('Runtime.evaluate', { expression: axeSource }, session);
|
||||
assert.equal(injected.exceptionDetails, undefined, 'axe-core should load in the page');
|
||||
const violations = await evaluate(session, async () => {
|
||||
const axe = (window as unknown as { axe: { run: (context: Document) => Promise<{ violations: Array<{ id: string; nodes: Array<{ target: string[] }> }> }> } }).axe;
|
||||
const results = await axe.run(document);
|
||||
return results.violations.map(({ id, nodes }) => ({ id, targets: nodes.map(({ target }) => target) }));
|
||||
});
|
||||
assert.deepEqual(violations, [], `${mode} mode accessibility violations`);
|
||||
}
|
||||
const screenshot = async (session: string, name: string) => {
|
||||
if (!screenshotDirectory) return;
|
||||
await mkdir(screenshotDirectory, { recursive: true });
|
||||
await call('Page.bringToFront', {}, session);
|
||||
const { data } = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session);
|
||||
await writeFile(join(screenshotDirectory, name + '.png'), Buffer.from(data, 'base64'));
|
||||
};
|
||||
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);
|
||||
const enableTurn = (session: string) => evaluate(session, () => {
|
||||
const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input');
|
||||
if (!checkbox.checked) checkbox.click();
|
||||
});
|
||||
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'));
|
||||
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!');
|
||||
await click(receiver, 'Accept & create answer');
|
||||
await wait(receiver, () => !!document.querySelector('[role=alert]'));
|
||||
assert.equal(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').disabled), false);
|
||||
if (turn) await enableTurn(receiver);
|
||||
await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
|
||||
await wait(receiver, () => !!document.querySelector('#output-code'));
|
||||
const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||||
await input(sender, '#answer-input', offer); await click(sender, 'Connect');
|
||||
await wait(sender, () => document.querySelector('[role=alert]')?.textContent?.includes('not an answer'));
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer);
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false);
|
||||
await input(sender, '#answer-input', answer); await click(sender, 'Connect');
|
||||
await wait(sender, () => !!document.querySelector('.fingerprint'));
|
||||
const sf = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
|
||||
const rf = await evaluate(receiver, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
|
||||
assert.equal(sf[0], rf[1]); assert.equal(sf[1], rf[0]); assert.equal(sf[0]?.split(' ').length, 32);
|
||||
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
|
||||
if (changedIdentity) {
|
||||
// The receiver still trusts the unchanged sender and verifies automatically;
|
||||
// the sender must compare manually and is not offered a silent replacement.
|
||||
assert.ok(await evaluate(sender, () => document.body.textContent?.includes('Device identity differs from the paired device')));
|
||||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.fingerprint label')].find(el => el.textContent?.includes('Replace the paired device'))?.querySelector('input')?.checked), false);
|
||||
await wait(receiver, () => document.body.textContent?.includes('Verification submitted'));
|
||||
await click(sender, 'Both fingerprints match — confirm');
|
||||
} else {
|
||||
await click(sender, 'Both fingerprints match — confirm');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
|
||||
await click(receiver, 'Both fingerprints match — confirm');
|
||||
}
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
if (turn) {
|
||||
for (const session of [sender, receiver]) {
|
||||
const types = await evaluate(session, relayCandidateTypes);
|
||||
assert.deepEqual(types, ['relay', 'relay'], 'Both ends must actually use relay candidates');
|
||||
}
|
||||
}
|
||||
}
|
||||
async function verifySavedFile(path: string, size: number) {
|
||||
const deadline = Date.now() + 30000;
|
||||
while (true) {
|
||||
try { if ((await stat(path)).size === size) break; } catch {}
|
||||
if (Date.now() > deadline) throw new Error('Browser did not finish saving the download.');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
let bytes = 0;
|
||||
for await (const chunk of createReadStream(path)) {
|
||||
assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match');
|
||||
bytes += (chunk as Buffer).length;
|
||||
}
|
||||
assert.equal(bytes, size);
|
||||
await rm(path);
|
||||
}
|
||||
try {
|
||||
// Received files land in the throwaway profile instead of the user's Downloads.
|
||||
const downloads = join(profile, 'downloads');
|
||||
await mkdir(downloads);
|
||||
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
|
||||
if (connections) {
|
||||
const sender = await page(), receiver = await page(origin.replace('127.0.0.1', 'localhost'));
|
||||
const selectConnection = (session: string, name: string) => evaluate(session, (name: string) => {
|
||||
const label = [...document.querySelectorAll<HTMLElement>('.connection-name')].find(item => item.textContent === name);
|
||||
if (!label) throw new Error('Missing connection: ' + name);
|
||||
label.click();
|
||||
}, name);
|
||||
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }, sender);
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1');
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll<HTMLDetailsElement>('.config-details')].map(details => [details.querySelector('summary')?.textContent?.trim(), details.open])), [
|
||||
['Remembered device', false], ['Network settings', false],
|
||||
], 'Configuration panels start closed');
|
||||
await checkAccessibility(sender, 'Connections desktop');
|
||||
await screenshot(sender, 'connections-desktop');
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('.connection-rename-input')), false, 'Names start locked');
|
||||
await click(sender, 'Rename Con 1');
|
||||
assert.equal(await evaluate(sender, () => document.activeElement?.classList.contains('connection-rename-input')), true, 'The pen focuses the name editor');
|
||||
await input(sender, '.connection-rename-input', 'Work laptop');
|
||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.connection-rename-input').blur());
|
||||
await wait(sender, () => document.querySelector('.connection-name')?.textContent === 'Work laptop');
|
||||
await click(sender, 'Rename Work laptop');
|
||||
await input(sender, '.connection-rename-input', ' ');
|
||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.connection-rename-input').blur());
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop');
|
||||
await click(sender, 'Rename Work laptop');
|
||||
await input(sender, '.connection-rename-input', 'Work laptop ');
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender);
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }, sender);
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop');
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('.connection-rename-input')), false, 'Enter relocks the name');
|
||||
await click(sender, 'Rename Work laptop');
|
||||
await input(sender, '.connection-rename-input', 'Cancelled name');
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, sender);
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, sender);
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.connection-name')?.textContent), 'Work laptop', 'Escape discards the draft');
|
||||
assert.equal(await evaluate(sender, () => document.activeElement?.classList.contains('edit-action')), true, 'Escape returns focus to the pen');
|
||||
await click(receiver, 'Receive');
|
||||
await connect(sender, receiver, 4097);
|
||||
const fingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent));
|
||||
await click(sender, 'Add connection');
|
||||
await wait(sender, () => document.querySelector('.main-pane h1')?.textContent === 'Con 2');
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('.fingerprint')), false);
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => document.querySelector('.connection-item .connection-status')?.textContent === 'Connected');
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.connection-nav')?.textContent?.includes('browser-test.bin')), false, 'The sidebar shows connection status instead of filenames');
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('.activity-panel')), false, 'The workspace has no activity timeline');
|
||||
await selectConnection(sender, 'Work laptop');
|
||||
await wait(sender, () => document.querySelector('.connection-item.selected .connection-status')?.textContent === 'Connected');
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent)), fingerprints);
|
||||
await evaluate(sender, () => window.__hellcon.chooseFile(1234, 'after-switch.bin'));
|
||||
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('after-switch.bin'));
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => document.querySelector('.progress[aria-label="Sending progress"]')?.getAttribute('aria-valuenow') === '100');
|
||||
const received = await evaluate(receiver, async () => {
|
||||
const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
|
||||
return { size: bytes.length, valid: bytes.every(byte => byte === 123) };
|
||||
});
|
||||
assert.deepEqual(received, { size: 1234, valid: true });
|
||||
await click(sender, 'Disconnect'); await click(sender, 'Reset');
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Work laptop', 'Reset keeps the connection slot');
|
||||
await checkAccessibility(sender, 'Connections after transfer');
|
||||
await screenshot(sender, 'connections-after-transfer');
|
||||
await selectConnection(sender, 'Con 2');
|
||||
await evaluate(sender, () => window.__hellcon.chooseFile(10, 'draft.bin'));
|
||||
await selectConnection(sender, 'Work laptop'); await selectConnection(sender, 'Con 2');
|
||||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.panel li')].some(item => item.textContent?.includes('draft.bin'))), true, 'Selected file state survives slot switching');
|
||||
await call('Page.navigate', { url: origin }, sender);
|
||||
await wait(sender, () => !!document.querySelector('#stun-provider'));
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Work laptop');
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.connection-item.selected .connection-status')?.textContent), 'Ready to connect');
|
||||
await selectConnection(sender, 'Con 2');
|
||||
assert.equal(await evaluate(sender, () => document.querySelector<HTMLInputElement>('#file-input')?.files?.length), 0, 'File contents must not persist after reload');
|
||||
console.log('PASS: connections retain names across reload; switching preserves live transfers and drafts; Reset keeps the slot without activity history.');
|
||||
|
||||
const other = await page();
|
||||
await Promise.all([click(sender, 'Add connection'), click(other, 'Add connection')]);
|
||||
await wait(sender, () => document.querySelectorAll('.connection-link').length === 4);
|
||||
await wait(other, () => document.querySelectorAll('.connection-link').length === 4);
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].map(item => item.textContent)), ['Work laptop', 'Con 2', 'Con 3', 'Con 4']);
|
||||
console.log('PASS: concurrent tabs add distinct connection slots and synchronize their sidebars.');
|
||||
|
||||
await call('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: false }, sender);
|
||||
await selectConnection(sender, 'Work laptop');
|
||||
assert.deepEqual(await evaluate(sender, () => [document.querySelector('.mobile-current-name')?.textContent, document.querySelector('.mobile-current-status')?.textContent]),
|
||||
['Work laptop', 'Ready to connect'], 'Mobile shows the open connection and its status');
|
||||
await checkAccessibility(sender, 'Connections mobile');
|
||||
assert.equal(await evaluate(sender, () => document.documentElement.scrollWidth <= innerWidth), true, 'Mobile workspace must not overflow horizontally');
|
||||
await screenshot(sender, 'connections-mobile');
|
||||
await click(sender, 'Show connections');
|
||||
await click(sender, 'Remove Work laptop');
|
||||
await wait(sender, () => !!document.querySelector('dialog[open]'));
|
||||
await checkAccessibility(sender, 'Removal dialog mobile');
|
||||
await screenshot(sender, 'connections-mobile-dialog');
|
||||
await click(sender, 'Close dialog');
|
||||
await wait(sender, () => !document.querySelector('dialog[open]'));
|
||||
await checkAccessibility(sender, 'Connections mobile sidebar');
|
||||
assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'flex');
|
||||
await screenshot(sender, 'connections-mobile-sidebar');
|
||||
await selectConnection(sender, 'Con 2');
|
||||
assert.equal(await evaluate(sender, () => getComputedStyle(window.__hellcon.element('.sidebar')).display), 'none');
|
||||
console.log('PASS: mobile navigation opens and closes, fits the viewport, and passes accessibility checks.');
|
||||
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }, sender);
|
||||
await selectConnection(sender, 'Work laptop');
|
||||
await click(receiver, 'Reset');
|
||||
await connect(sender, receiver, 1024);
|
||||
await selectConnection(sender, 'Con 2');
|
||||
await selectConnection(other, 'Work laptop');
|
||||
await evaluate(other, () => window.__hellcon.element<HTMLButtonElement>('.connection-item.selected .remove-action').focus());
|
||||
await click(other, 'Remove Work laptop');
|
||||
await wait(other, () => !!document.querySelector('dialog[open]'));
|
||||
assert.equal(await evaluate(other, () => document.activeElement?.textContent?.trim()), 'Keep connection', 'Dialog starts on its non-destructive action');
|
||||
await checkAccessibility(other, 'Remove connection confirmation');
|
||||
await screenshot(other, 'connections-remove-dialog');
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }, other);
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }, other);
|
||||
assert.equal(await evaluate(other, () => !!document.querySelector('dialog[open]')?.contains(document.activeElement)), true, 'Tab stays within the modal');
|
||||
}
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other);
|
||||
await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }, other);
|
||||
await wait(other, () => !document.querySelector('dialog[open]'));
|
||||
assert.equal(await evaluate(other, () => document.activeElement?.classList.contains('remove-action')), true, 'Dialog restores focus to the opener');
|
||||
await click(other, 'Remove Work laptop');
|
||||
await click(other, 'Keep connection');
|
||||
assert.equal(await evaluate(other, () => document.querySelectorAll('.connection-link').length), 4);
|
||||
await click(sender, 'Remove Work laptop');
|
||||
await wait(sender, () => !!document.querySelector('dialog[open]'));
|
||||
await click(other, 'Remove Work laptop'); await click(other, 'Remove connection');
|
||||
await wait(other, () => document.querySelectorAll('.connection-link').length === 3);
|
||||
await wait(sender, () => document.querySelectorAll('.connection-link').length === 3);
|
||||
await wait(sender, () => !document.querySelector('dialog[open]'));
|
||||
await wait(receiver, () => !document.querySelector('.incoming'));
|
||||
await call('Page.navigate', { url: origin }, sender);
|
||||
await wait(sender, () => !!document.querySelector('#stun-provider'));
|
||||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Work laptop')), false);
|
||||
for (let count = 3; count > 0; count--) {
|
||||
const oldName = await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent);
|
||||
await click(sender, `Remove ${oldName}`); await click(sender, 'Remove connection');
|
||||
await wait(sender, () => !document.querySelector('dialog[open]'));
|
||||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.connection-link').length), Math.max(1, count - 1));
|
||||
assert.notEqual(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), oldName);
|
||||
}
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1');
|
||||
await call('Page.navigate', { url: origin }, sender);
|
||||
await wait(sender, () => !!document.querySelector('#stun-provider'));
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.connection-name')].map(item => item.textContent)), ['Con 1']);
|
||||
console.log('PASS: removal can be cancelled, persists across reload, closes cached sessions in other tabs, and replaces the last slot with a fresh Con 1.');
|
||||
await click(sender, 'Add connection');
|
||||
await wait(sender, () => document.querySelectorAll('.connection-link').length === 2);
|
||||
await selectConnection(sender, 'Con 1');
|
||||
const spareName = await evaluate(sender, () => document.querySelectorAll('.connection-name')[1]?.textContent);
|
||||
await click(sender, `Rename ${spareName}`);
|
||||
await input(sender, '.connection-rename-input', 'Spare device');
|
||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.connection-rename-input').blur());
|
||||
await wait(sender, () => [...document.querySelectorAll('.connection-name')].some(item => item.textContent === 'Spare device'));
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1', 'Renaming another row keeps the current connection');
|
||||
await click(sender, 'Remove Spare device');
|
||||
assert.match(await dialogText(sender), /Remove Spare device\?/);
|
||||
await click(sender, 'Remove connection');
|
||||
await wait(sender, () => document.querySelectorAll('.connection-link').length === 1);
|
||||
assert.equal(await evaluate(sender, () => document.querySelector('.main-pane h1')?.textContent), 'Con 1', 'Removing another row keeps the current connection');
|
||||
assert.equal(await evaluate(sender, () => document.activeElement?.classList.contains('connection-link')), true, 'Focus returns to the remaining connection after removal');
|
||||
console.log('PASS: sidebar actions target their own connection without changing the active workspace.');
|
||||
await evaluate(sender, async () => {
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open('hellcon-connections', 1);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('connections', 'readwrite');
|
||||
const store = tx.objectStore('connections');
|
||||
const request = store.getAll();
|
||||
request.onsuccess = () => store.put({ ...request.result[0], history: [{ name: 'old-file.bin' }] });
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = tx.onabort = () => reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
});
|
||||
await call('Page.navigate', { url: origin }, sender);
|
||||
await wait(sender, () => !!document.querySelector('#stun-provider'));
|
||||
const oldHistoryRemoved = await evaluate(sender, async () => {
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open('hellcon-connections', 1);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
const record = await new Promise<Record<string, unknown>>((resolve, reject) => {
|
||||
const request = db.transaction('connections', 'readonly').objectStore('connections').getAll();
|
||||
request.onsuccess = () => resolve(request.result[0]);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
db.close();
|
||||
return { name: record.name, hasHistory: Object.hasOwn(record, 'history') };
|
||||
});
|
||||
assert.deepEqual(oldHistoryRemoved, { name: 'Con 1', hasHistory: false }, 'Loading an old slot removes saved transfer history');
|
||||
console.log('PASS: legacy transfer history is removed from saved connections on load.');
|
||||
assert.deepEqual(browserErrors, []);
|
||||
} else if (streaming) {
|
||||
const sender = await page(), receiver = await page();
|
||||
await click(receiver, 'Receive');
|
||||
for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) {
|
||||
if (size === 0) await connect(sender, receiver, size);
|
||||
else {
|
||||
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
}
|
||||
assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/);
|
||||
await verifySavedFile(join(downloads, 'browser-test.bin'), size);
|
||||
console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`);
|
||||
}
|
||||
assert.deepEqual(browserErrors, []);
|
||||
} else {
|
||||
const sender = await page(), receiver = await page();
|
||||
if (!turn) {
|
||||
assert.equal(await evaluate(sender, () => document.querySelector<HTMLSelectElement>('#stun-provider')?.value), 'pagequit');
|
||||
}
|
||||
await click(receiver, 'Receive');
|
||||
await checkAccessibility(sender, 'Send');
|
||||
await checkAccessibility(receiver, 'Receive');
|
||||
console.log('PASS: axe-core accessibility scan in initial Send and Receive modes.');
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.checkbox input').checked), false);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
|
||||
await checkAccessibility(sender, 'Send during transfer');
|
||||
await checkAccessibility(receiver, 'Receive before accepting a file');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
await checkAccessibility(sender, 'Send after transfer');
|
||||
await checkAccessibility(receiver, 'Receive after transfer');
|
||||
console.log('PASS: axe-core accessibility scan during and after transfer.');
|
||||
const data = await evaluate(receiver, async () => {
|
||||
const response = await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
return { length: bytes.length, valid: bytes.every(b => b === 123) };
|
||||
});
|
||||
assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true });
|
||||
assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/);
|
||||
await verifySavedFile(join(downloads, 'browser-test.bin'), 2 * 1024 * 1024 + 7);
|
||||
await wait(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
|
||||
const diagnostics = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value);
|
||||
assert.match(diagnostics, /local code: host=\d+/);
|
||||
assert.match(diagnostics, /remote code: host=\d+/);
|
||||
assert.match(diagnostics, /requestsSent=/);
|
||||
assert.match(diagnostics, /transfer done/);
|
||||
assert.doesNotMatch(diagnostics, /browser-test\.bin|a=candidate:|a=ice-pwd:|a=fingerprint:|\.local\b/);
|
||||
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt; memory fallback saves to Downloads automatically.');
|
||||
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
|
||||
const originalFingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
|
||||
for (const size of [0, 4097]) {
|
||||
const previousDownload = await evaluate(receiver, () => window.__hellcon.element<HTMLAnchorElement>('a.download').href);
|
||||
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'another.bin'), size);
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
assert.equal(await evaluate(receiver, () => window.__hellcon.element<HTMLAnchorElement>('a.download').href), previousDownload);
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Waiting for the receiver to accept the file…');
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints);
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
const next = await evaluate(receiver, 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(next, { name: 'another.bin', length: size, valid: true });
|
||||
}
|
||||
console.log('PASS: consecutive files including an empty file reuse fingerprints, require acceptance, and preserve the previous download until acceptance.');
|
||||
// Queue two files and send back simultaneously, on the same peer connection.
|
||||
await evaluate(sender, () => {
|
||||
const input = window.__hellcon.element<HTMLInputElement>('#file-input');
|
||||
const files = new DataTransfer();
|
||||
for (const name of ['decline-me.bin', 'queued.bin', 'remove-me.bin']) files.items.add(new File([new Uint8Array(1024).fill(123)], name));
|
||||
input.files = files.files; input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
});
|
||||
await evaluate(sender, () => window.__hellcon.element<HTMLButtonElement>('button[aria-label="Remove remove-me.bin"]').click());
|
||||
await click(receiver, 'Send');
|
||||
assert.equal(await evaluate(receiver, () => document.activeElement?.getAttribute('aria-labelledby')), 'send-heading');
|
||||
await evaluate(receiver, () => window.__hellcon.chooseFile(8193, 'return.bin'));
|
||||
await click(receiver, 'Receive');
|
||||
assert.equal(await evaluate(receiver, () => document.activeElement?.getAttribute('aria-labelledby')), 'receive-heading');
|
||||
await click(sender, 'Receive');
|
||||
assert.equal(await evaluate(sender, () => document.activeElement?.getAttribute('aria-labelledby')), 'receive-heading');
|
||||
await wait(sender, () => !!document.querySelector('.incoming'));
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
await click(receiver, 'Decline file');
|
||||
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('queued.bin'));
|
||||
await click(sender, 'Accept file');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => document.querySelector<HTMLAnchorElement>('a.download')?.download === 'return.bin');
|
||||
await wait(receiver, () => document.querySelector<HTMLAnchorElement>('a.download')?.download === 'queued.bin');
|
||||
for (const [session, size] of [[sender, 8193], [receiver, 1024]] as const) {
|
||||
const received = await evaluate(session, async () => {
|
||||
const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
|
||||
return { length: bytes.length, valid: bytes.every(byte => byte === 123) };
|
||||
});
|
||||
assert.deepEqual(received, { length: size, valid: true });
|
||||
await checkAccessibility(session, 'Bidirectional session');
|
||||
}
|
||||
assert.equal(await evaluate(sender, () => [...document.querySelectorAll('.tabs button')].every(button => !(button as HTMLButtonElement).disabled)), true);
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints);
|
||||
console.log('PASS: simultaneous bidirectional transfers, multiple-file queue, removal, decline, exact bytes, and live Send/Receive navigation without reconnecting.');
|
||||
|
||||
await click(sender, 'Reset'); await click(receiver, 'Reset');
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Choose a file to start.');
|
||||
assert.equal(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), 'Paste the sender’s connection code to start.');
|
||||
console.log('PASS: Reset restores the ready state on both sides.');
|
||||
await evaluate(receiver, simulateSlowDisk);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024);
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(receiver, () => !!window.__hellcon.releaseWrite);
|
||||
await evaluate(sender, () => window.__hellcon.chooseFile(1024, 'pending-at-disconnect.bin'));
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), true);
|
||||
await click(sender, 'Disconnect');
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), false);
|
||||
await wait(receiver, () => window.__hellcon.aborted);
|
||||
assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false);
|
||||
await wait(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
|
||||
assert.match(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value), /session failed/);
|
||||
console.log('PASS: privacy-safe candidate/check diagnostics remain available after completion and failure.');
|
||||
console.log('PASS: Disconnect closes the connection and aborts the receiver’s pending disk write.');
|
||||
await click(sender, 'Reset'); await click(receiver, 'Reset');
|
||||
await evaluate(receiver, () => { window.showSaveFilePicker = undefined; });
|
||||
await connect(sender, receiver, 2048);
|
||||
await click(receiver, 'Accept file');
|
||||
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) {
|
||||
const identitySender = await page();
|
||||
const receiverOrigin = origin.replace('127.0.0.1', 'localhost');
|
||||
const identityReceiver = await page(receiverOrigin);
|
||||
await click(identityReceiver, 'Receive');
|
||||
const pairedKey = (session: string) => evaluate(session, () => document.querySelector('.device-settings code')?.textContent || '');
|
||||
// Clears the paired device directly in storage, so this tab is not notified.
|
||||
const forgetQuietly = (session: string) => evaluate(session, async () => {
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => { const request = indexedDB.open('hellcon-connections', 1); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('connections', 'readwrite'), store = tx.objectStore('connections'), request = store.getAll();
|
||||
request.onsuccess = () => { for (const record of request.result) store.put({ ...record, peerKey: '' }); };
|
||||
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
|
||||
}); db.close();
|
||||
});
|
||||
for (const session of [identitySender, identityReceiver]) {
|
||||
await evaluate(session, () => { const details = [...document.querySelectorAll('details')].find(el => el.querySelector('summary')?.textContent === 'Remembered device'); if (details) details.open = true; });
|
||||
await wait(session, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity' && !button.disabled));
|
||||
await click(session, 'Create device identity');
|
||||
await wait(session, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
|
||||
}
|
||||
await connect(identitySender, identityReceiver, 2048);
|
||||
for (const session of [identitySender, identityReceiver]) {
|
||||
await wait(session, () => document.body.textContent?.includes('Remembered for Con 1'));
|
||||
await wait(session, () => !!document.querySelector('.device-settings code'));
|
||||
}
|
||||
await checkAccessibility(identitySender, 'remembered identity');
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reset'));
|
||||
// Reload both pages to exercise persisted CryptoKeys and paired connections.
|
||||
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 [identitySender, identityReceiver]) {
|
||||
await wait(session, () => !!document.querySelector('.device-settings code'));
|
||||
assert.equal(await evaluate(session, () => !!document.querySelector('#remember-device')), false, 'A paired connection shows its device instead of the opt-in');
|
||||
await input(session, '#stun-provider', 'none');
|
||||
}
|
||||
await evaluate(identitySender, () => window.__hellcon.chooseFile(4096, 'remembered.bin'));
|
||||
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);
|
||||
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);
|
||||
await input(identitySender, '#answer-input', answer); await click(identitySender, 'Connect');
|
||||
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
|
||||
for (const session of [identitySender, identityReceiver]) assert.ok(await evaluate(session, () => document.body.textContent?.includes('Paired device authenticated')));
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
const rememberedBytes = await evaluate(identityReceiver, async () => { const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer()); return { length: bytes.length, valid: bytes.every(byte => byte === 123) }; });
|
||||
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');
|
||||
for (const forgottenSide of [identitySender, identityReceiver]) {
|
||||
await forgetQuietly(forgottenSide);
|
||||
assert.ok(await pairedKey(forgottenSide), 'Original tab still shows the stale paired device before connection setup');
|
||||
|
||||
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-device.bin'));
|
||||
await click(identitySender, 'Create code'); await wait(identitySender, () => !!document.querySelector('#output-code'));
|
||||
const freshOffer = await evaluate(identitySender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||||
await input(identityReceiver, '#offer-input', freshOffer); await click(identityReceiver, 'Accept & create answer');
|
||||
await wait(identityReceiver, () => !!document.querySelector('#output-code'));
|
||||
const freshAnswer = await evaluate(identityReceiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||||
await input(identitySender, '#answer-input', freshAnswer); await click(identitySender, 'Connect');
|
||||
await wait(forgottenSide, () => document.body.textContent?.includes('New device. Compare both fingerprints manually'));
|
||||
assert.equal(await pairedKey(forgottenSide), '', 'Connection setup re-reads the forgotten pairing');
|
||||
assert.equal(await evaluate(forgottenSide, () => [...document.querySelectorAll('.fingerprint label')].find(el => el.textContent?.includes('Remember this device for Con 1'))?.querySelector('input')?.checked), true);
|
||||
assert.equal(await evaluate(identityReceiver, () => !!document.querySelector('.incoming')), false, 'Forgotten trust must not release file metadata');
|
||||
await click(forgottenSide, 'Both fingerprints match — confirm');
|
||||
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
|
||||
await wait(forgottenSide, () => !!document.querySelector('.device-settings code'));
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||||
}
|
||||
console.log('PASS: forgetting a device in another tab removes stale trust before either role reconnects; manual confirmation gates metadata and pairs the connection again.');
|
||||
|
||||
await evaluate(identitySender, () => { indexedDB.open = () => { throw new DOMException('Storage denied during refresh', 'SecurityError'); }; });
|
||||
await evaluate(identitySender, () => window.__hellcon.chooseFile(1, 'storage-failure.bin'));
|
||||
await click(identitySender, 'Create code');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('Storage denied during refresh'));
|
||||
assert.equal(await evaluate(identitySender, () => !!document.querySelector('#output-code')), false, 'Failed storage refresh must not use cached trust');
|
||||
await evaluate(identitySender, () => { Reflect.deleteProperty(indexedDB, 'open'); });
|
||||
await click(identitySender, 'Reset');
|
||||
console.log('PASS: unreadable storage during connection setup cannot reuse a cached identity or paired device.');
|
||||
|
||||
const senderPaired = await pairedKey(identitySender);
|
||||
await evaluate(identityReceiver, () => {
|
||||
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s device identity'));
|
||||
label?.querySelector<HTMLInputElement>('input')?.click();
|
||||
});
|
||||
await click(identityReceiver, 'Delete device identity');
|
||||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity'));
|
||||
await click(identityReceiver, 'Create device identity');
|
||||
await wait(identityReceiver, () => !!document.querySelector('.device-settings code'));
|
||||
await connect(identitySender, identityReceiver, 512, true);
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('This device was not remembered.')));
|
||||
assert.equal(await pairedKey(identitySender), senderPaired, 'Changed identity must not replace the paired device automatically');
|
||||
console.log('PASS: replaced peer identity requires manual comparison and preserves the paired device.');
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
||||
const stale = await page();
|
||||
await wait(stale, () => !!document.querySelector('.device-settings code'));
|
||||
await click(stale, 'Forget device');
|
||||
await wait(stale, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
|
||||
await wait(identitySender, () => document.querySelector<HTMLInputElement>('#remember-device')?.checked);
|
||||
console.log('PASS: Forget device keeps the per-connection opt-in and reaches other tabs.');
|
||||
await evaluate(stale, async () => {
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => { const request = indexedDB.open('hellcon-devices', 1); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite'), store = tx.objectStore('settings'), request = store.get('state');
|
||||
request.onsuccess = () => store.put({ ...request.result, revision: crypto.randomUUID() }, 'state');
|
||||
tx.oncomplete = () => resolve(); tx.onabort = () => reject(tx.error);
|
||||
}); db.close();
|
||||
});
|
||||
await evaluate(stale, () => [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Delete this browser’s device identity'))?.querySelector<HTMLInputElement>('input')?.click());
|
||||
await click(stale, 'Delete device identity');
|
||||
await wait(stale, () => document.body.textContent?.includes('Device settings changed in another tab'));
|
||||
await evaluate(stale, async () => {
|
||||
const db = await new Promise<IDBDatabase>(resolve => { const request = indexedDB.open('hellcon-devices', 1); request.onsuccess = () => resolve(request.result); });
|
||||
await new Promise<void>(resolve => { const tx = db.transaction('settings', 'readwrite'); tx.objectStore('settings').put({ identity: { publicKey: 'broken' }, revision: 'broken' }, 'state'); tx.oncomplete = () => resolve(); }); db.close();
|
||||
});
|
||||
await call('Page.navigate', { url: origin }, stale);
|
||||
await wait(stale, () => document.body.textContent?.includes('Invalid device identity'));
|
||||
await evaluate(stale, () => [...document.querySelectorAll('label')].find(label => label.textContent?.includes('Delete unreadable device storage'))?.querySelector<HTMLInputElement>('input')?.click());
|
||||
await click(stale, 'Clear device storage');
|
||||
await wait(stale, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity' && !button.disabled));
|
||||
console.log('PASS: stale identity edits cannot overwrite newer settings; unreadable storage can be cleared with explicit consent.');
|
||||
const denied = await page();
|
||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: "indexedDB.open = () => { throw new DOMException('Storage denied', 'SecurityError'); };" }, denied);
|
||||
await call('Page.navigate', { url: origin }, denied);
|
||||
await wait(denied, () => document.body.textContent?.includes('Storage denied'));
|
||||
await evaluate(denied, () => window.__hellcon.chooseFile(1, 'temporary.bin'));
|
||||
await input(denied, '#stun-provider', 'none'); await click(denied, 'Create code');
|
||||
await wait(denied, () => !!document.querySelector('#output-code'));
|
||||
const temporary = await evaluate(denied, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||||
assert.equal((await decodeCode(temporary)).identity, undefined);
|
||||
await click(denied, 'Cancel connection');
|
||||
console.log('PASS: denied identity storage still allows temporary v3 connection setup.');
|
||||
|
||||
}
|
||||
if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`);
|
||||
assert.deepEqual(browserErrors, []);
|
||||
}
|
||||
} finally {
|
||||
browser.kill();
|
||||
await new Promise<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); });
|
||||
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
await vite?.close();
|
||||
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
// These functions are serialized into isolated browser pages by the checks.
|
||||
// Keep their dependencies inside the function or on window.__hellcon.
|
||||
export function installBrowserContext() {
|
||||
function element<E extends Element>(selector: string): E {
|
||||
const value = document.querySelector<E>(selector);
|
||||
if (!value) throw new Error(`Missing element: ${selector}`);
|
||||
return value;
|
||||
}
|
||||
const context = {
|
||||
element,
|
||||
peers: [] as RTCPeerConnection[],
|
||||
aborted: false,
|
||||
releaseWrite: undefined as (() => void) | undefined,
|
||||
click(label: string) {
|
||||
const button = [...document.querySelectorAll('button')].find(button => {
|
||||
const content = button.cloneNode(true) as HTMLButtonElement;
|
||||
content.querySelectorAll('[aria-hidden="true"]').forEach(item => item.remove());
|
||||
return button.getAttribute('aria-label') === label || content.textContent?.trim() === label;
|
||||
});
|
||||
if (!button || button.disabled) throw new Error(`Unavailable button: ${label}`);
|
||||
button.click();
|
||||
},
|
||||
input(selector: string, value: string) {
|
||||
const input = element<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(selector);
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
|
||||
},
|
||||
chooseFile(size: number, name: string) {
|
||||
const input = element<HTMLInputElement>('#file-input');
|
||||
const files = new DataTransfer();
|
||||
files.items.add(new File([new Uint8Array(size).fill(123)], name));
|
||||
input.files = files.files;
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
},
|
||||
async wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>> {
|
||||
const deadline = Date.now() + 36000;
|
||||
while (Date.now() < deadline) {
|
||||
const value = await check();
|
||||
if (value) return value;
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
throw new Error('UI condition timed out: ' + document.body.innerText);
|
||||
},
|
||||
};
|
||||
window.__hellcon = context;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__hellcon: {
|
||||
element<E extends Element>(selector: string): E;
|
||||
peers: RTCPeerConnection[];
|
||||
aborted: boolean;
|
||||
releaseWrite?: () => void;
|
||||
click(label: string): void;
|
||||
input(selector: string, value: string): void;
|
||||
chooseFile(size: number, name: string): void;
|
||||
wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>>;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function forceRelay(transport: 'udp' | 'tcp') {
|
||||
const NativePC = window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends NativePC {
|
||||
constructor(config?: RTCConfiguration) {
|
||||
super({ ...config, iceTransportPolicy: 'relay' });
|
||||
window.__hellcon.peers.push(this);
|
||||
}
|
||||
override setConfiguration(config: RTCConfiguration) {
|
||||
const iceServers = (config.iceServers ?? []).filter(server => server.username).map(server => ({
|
||||
...server,
|
||||
urls: (Array.isArray(server.urls) ? server.urls : [server.urls]).filter(url => url.endsWith(`transport=${transport}`)),
|
||||
}));
|
||||
super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function relayCandidateTypes() {
|
||||
for (let attempt = 0; attempt < 50; attempt++) {
|
||||
const pc = window.__hellcon.peers.at(-1);
|
||||
if (!pc) throw new Error('No peer connection');
|
||||
const stats = await pc.getStats();
|
||||
const transport = [...stats.values()].find((entry: RTCStats) => entry.type === 'transport') as RTCTransportStats | undefined;
|
||||
const pair = transport?.selectedCandidatePairId ? stats.get(transport.selectedCandidatePairId) as RTCIceCandidatePairStats | undefined : undefined;
|
||||
if (pair) {
|
||||
const local = stats.get(pair.localCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
|
||||
const remote = stats.get(pair.remoteCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
|
||||
return [local?.candidateType, remote?.candidateType];
|
||||
}
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error('No selected ICE candidate pair in WebRTC statistics');
|
||||
}
|
||||
|
||||
export function simulateSlowDisk() {
|
||||
window.__hellcon.aborted = false;
|
||||
// Only the methods used by the app are implemented by this browser test double.
|
||||
window.showSaveFilePicker = async () => ({
|
||||
createWritable: async () => ({
|
||||
write() { return new Promise<void>(resolve => { window.__hellcon.releaseWrite = resolve; }); },
|
||||
async close() {},
|
||||
async abort() { window.__hellcon.aborted = true; window.__hellcon.releaseWrite?.(); },
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { execFileSync, spawn } from 'node:child_process';
|
||||
import { stripTypeScriptTypes } from 'node:module';
|
||||
import { createSocket } from 'node:dgram';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
// A controlled ICE experiment, not a cross-device transfer test. Reads the
|
||||
// original signaling helpers from git without checking out or editing files.
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
const legacy = execFileSync('git', ['show', 'd198332:src/lib/webrtc.js'], { cwd: root, encoding: 'utf8' });
|
||||
const current = stripTypeScriptTypes(await readFile(root + '/src/lib/webrtc.ts', 'utf8'));
|
||||
const validation = stripTypeScriptTypes(await readFile(root + '/src/lib/validation.ts', 'utf8'));
|
||||
const udp = createSocket('udp4');
|
||||
await new Promise(resolve => udp.bind(0, '127.0.0.1', resolve));
|
||||
const stunUrl = process.argv.includes('--slow-stun') ? 'stun:127.0.0.1:' + udp.address().port : null;
|
||||
const rewritePorts = !process.argv.includes('--normal-candidates');
|
||||
const browserCode = String.raw`
|
||||
import * as old from '/old.js';
|
||||
import * as current from '/current.js';
|
||||
async function run(mode) {
|
||||
const api = mode === 'original' ? old : current;
|
||||
const start = performance.now();
|
||||
const events = [];
|
||||
const log = (event) => events.push([Math.round(performance.now()-start),event]);
|
||||
const {stunUrl,rewritePorts} = await (await fetch('/config')).json();
|
||||
const a = api.createPeerConnection(mode === 'original' ? stunUrl : {stunUrl});
|
||||
const b = api.createPeerConnection(mode === 'original' ? stunUrl : {stunUrl});
|
||||
if(mode !== 'original') { a.setConfiguration(current.iceConfiguration({stunUrl})); b.setConfiguration(current.iceConfiguration({stunUrl})); }
|
||||
let received = false;
|
||||
for(const [role,pc] of [['sender',a],['receiver',b]]) {
|
||||
pc.oniceconnectionstatechange = () => log(role + ' ICE ' + pc.iceConnectionState);
|
||||
pc.onconnectionstatechange = () => {
|
||||
log(role + ' PC ' + pc.connectionState);
|
||||
if(mode === 'current' && pc.connectionState === 'failed') pc.close();
|
||||
};
|
||||
}
|
||||
const dc = a.createDataChannel('file');
|
||||
dc.onopen = () => { log('sender channel open'); dc.send('exact-file-bytes'); };
|
||||
b.ondatachannel = e => { e.channel.onmessage = e => { received = e.data === 'exact-file-bytes'; log('receiver bytes '+received); }; };
|
||||
try {
|
||||
// The original helpers exchange encoded codes; current helpers exchange SDP.
|
||||
let sdp = mode === 'original' ? api.decodeSignal(await api.createOfferCode(a)) : await api.createOffer(a);
|
||||
// Deliberately unusable advertised ports: only sender-initiated checks
|
||||
// after the answer can discover the real sender. No host firewall changes.
|
||||
if(rewritePorts) sdp = sdp.split('\r\n').filter(l=>!/^a=candidate:.* tcp /i.test(l)).map(l=>{
|
||||
if(!l.startsWith('a=candidate:'))return l;
|
||||
const fields=l.split(' '); fields[5]='9'; return fields.join(' ');
|
||||
}).join('\r\n');
|
||||
log('offer ready; end-of-candidates='+sdp.includes('a=end-of-candidates'));
|
||||
const answer = mode === 'original' ? await api.createAnswerCode(b, api.encodeSignal(sdp)) : await api.createAnswer(b, sdp);
|
||||
log('answer ready');
|
||||
await new Promise(r=>setTimeout(r,20000));
|
||||
log('apply answer');
|
||||
await (mode === 'original' ? api.acceptAnswerCode(a,answer) : api.acceptAnswer(a,answer));
|
||||
await new Promise(r=>setTimeout(r,12000));
|
||||
return {mode,received,events};
|
||||
} catch { return {mode,received,events,error:'Signaling failed; raw browser error omitted'}; }
|
||||
finally {a.close();b.close();}
|
||||
}
|
||||
const results = await Promise.all(['original','current','current-keep'].map(run));
|
||||
await fetch('/result',{method:'POST',body:JSON.stringify(results)});
|
||||
`;
|
||||
let done;
|
||||
const finished = new Promise(resolve=>done=resolve);
|
||||
const server = createServer(async(req,res)=>{
|
||||
if(req.url === '/config') { res.setHeader('Content-Type','application/json');res.end(JSON.stringify({stunUrl,rewritePorts}));return; }
|
||||
if(req.url === '/result') {let body=''; for await(const part of req)body+=part; console.log(body);res.end('ok');done();return;}
|
||||
res.setHeader('Content-Type',req.url==='/'?'text/html':'text/javascript');
|
||||
res.end(({'/':'<script type="module" src="/run.js"></script>','/old.js':legacy,'/current.js':current,'/validation.ts':validation,'/run.js':browserCode})[req.url] || '');
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const profile=await mkdtemp(join(tmpdir(), 'hellcon-ice-comparison-'));
|
||||
const name=process.argv[2] || 'firefox';
|
||||
const url='http://127.0.0.1:'+server.address().port;
|
||||
const args=name==='firefox'?['--headless','--no-remote','--profile',profile,url]:['--headless','--no-sandbox','--disable-gpu','--no-first-run','--user-data-dir='+profile,url];
|
||||
const child=spawn('/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});
|
||||
child.on('error',()=>{console.error('Could not launch browser');process.exitCode=1;done();});
|
||||
let errors='';child.stderr.on('data',chunk=>errors+=chunk);
|
||||
const timer=setTimeout(()=>{console.log('Comparison timed out');process.exitCode=1;done();},85000);
|
||||
try {await finished;} finally {
|
||||
clearTimeout(timer);child.kill();
|
||||
if(child.pid && child.exitCode===null && child.signalCode===null) await new Promise(resolve=>child.once('exit',resolve));
|
||||
server.closeAllConnections();server.close();udp.close();
|
||||
await rm(profile,{recursive:true,force:true,maxRetries:3});
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
// Exercises the built Vue app in separate Brave and Firefox processes.
|
||||
import { installBrowserContext } from './browser-context.ts';
|
||||
import { crossBrowserDriver } from './cross-browser-driver.ts';
|
||||
import { isRecord } from '../src/lib/validation.ts';
|
||||
import { createServer } from 'node:http';
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { readFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { tmpdir } from 'node:os';
|
||||
const types: Record<string, string> = {'.html':'text/html','.js':'text/javascript','.css':'text/css','.png':'image/png'};
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const state: Record<string, unknown> = {};
|
||||
const profiles: string[] = [];
|
||||
const children: ChildProcess[] = [];
|
||||
const provider = process.argv.includes('--default-network') ? 'pagequit' : 'none';
|
||||
const reversed = process.argv.includes('--reverse');
|
||||
const driver = `(${installBrowserContext.toString()})(); (${crossBrowserDriver.toString()})(${JSON.stringify(provider)});`;
|
||||
let finish: () => void = () => {};
|
||||
const result = new Promise<void>(resolve => { finish = resolve; });
|
||||
const server = createServer(async (req,res) => {
|
||||
try {
|
||||
const pathname=new URL(req.url ?? '/','http://localhost').pathname;
|
||||
if(pathname==='/.test/driver.js'){res.setHeader('Content-Type','text/javascript');res.end(driver);return;}
|
||||
if(pathname.startsWith('/.test/')){
|
||||
const key=pathname.slice('/.test/'.length);
|
||||
if(req.method==='POST'){
|
||||
let body='';for await(const part of req){body+=part;if(body.length>262144)throw new Error('Too big');}
|
||||
const previous=state[key];
|
||||
state[key]=JSON.parse(body);
|
||||
if(key.endsWith('Stage'))console.log(key+': '+state[key]);
|
||||
if(key.endsWith('Diagnostic')&&JSON.stringify(previous)!==JSON.stringify(state[key]))console.log(key+': '+JSON.stringify(state[key]));
|
||||
if(key.endsWith('Result')){
|
||||
console.log(key+': '+JSON.stringify(state[key]));
|
||||
if(!isRecord(state[key]) || !state[key].ok ||(state.senderResult&&state.receiverResult))finish();
|
||||
}
|
||||
}
|
||||
res.setHeader('Content-Type','application/json');res.end(JSON.stringify(state[key]??null));return;
|
||||
}
|
||||
const base=join(root,'dist');const path=resolve(base,'.'+(pathname==='/'?'/index.html':pathname));
|
||||
if(!path.startsWith(base+'/'))throw new Error('Invalid path');
|
||||
let body: string | Buffer = await readFile(path);
|
||||
if(pathname==='/')body=body.toString().replace('</body>','<script type="module" src="/.test/driver.js"></script></body>');
|
||||
res.setHeader('Content-Type',types[extname(path)]||'application/octet-stream');res.end(body);
|
||||
}catch{res.statusCode=404;res.end();}
|
||||
});
|
||||
await new Promise<void>(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') throw new Error('Missing server address');
|
||||
const origin='http://127.0.0.1:'+address.port;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try{
|
||||
for(const name of ['brave','firefox']){
|
||||
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
|
||||
// Received files are saved automatically; keep them in the throwaway profile instead of the user's Downloads.
|
||||
const downloads=join(profile,'downloads');await mkdir(downloads);
|
||||
if(name==='brave'){await mkdir(join(profile,'Default'));await writeFile(join(profile,'Default','Preferences'),JSON.stringify({download:{default_directory:downloads,prompt_for_download:false}}));}
|
||||
else await writeFile(join(profile,'user.js'),['user_pref("browser.download.folderList", 2);','user_pref("browser.download.dir", '+JSON.stringify(downloads)+');','user_pref("browser.download.useDownloadDir", true);','user_pref("browser.download.always_ask_before_handling_new_types", false);'].join('\n'));
|
||||
const role=(name==='brave')!==reversed?'sender':'receiver';
|
||||
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
|
||||
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
|
||||
let errors='';child.stderr.on('data',chunk=>{errors+=chunk;});
|
||||
child.on('error',err=>{console.error(name,err.message);finish();});
|
||||
child.on('exit',code=>{if(code){console.error(name+' exited: '+errors.slice(-1500));finish();}});
|
||||
}
|
||||
timer=setTimeout(()=>{console.error('Cross-browser check timed out.', JSON.stringify({sender:state.senderDiagnostic,receiver:state.receiverDiagnostic}));finish();},provider==='none'?15000:90000);
|
||||
await result;
|
||||
if(!isRecord(state.senderResult) || !state.senderResult.ok || !isRecord(state.receiverResult) || !state.receiverResult.ok)process.exitCode=1;
|
||||
else console.log('PASS: '+(reversed?'Firefox → Brave':'Brave → Firefox')+' full UI transfer, fingerprint verification and exact file contents.');
|
||||
}finally{
|
||||
clearTimeout(timer);
|
||||
for(const child of children)child.kill();
|
||||
await Promise.all(children.map(child=>new Promise<void>(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once('exit', () => resolve());})));
|
||||
server.closeAllConnections();await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
for(const profile of profiles)await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:200});
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import type {} from './browser-context.ts';
|
||||
|
||||
interface Exchange {
|
||||
offer: string;
|
||||
answer: string;
|
||||
senderFingerprints: string[];
|
||||
receiverFingerprints: string[];
|
||||
senderResult: { ok: boolean };
|
||||
}
|
||||
|
||||
// Serialized by the runner; all runtime dependencies live in this function or window.
|
||||
export async function crossBrowserDriver(provider: string) {
|
||||
const role = new URL(location.href).searchParams.get('role');
|
||||
if (role !== 'sender' && role !== 'receiver') throw new Error('Invalid role');
|
||||
const { click, input, wait, element } = window.__hellcon;
|
||||
// Use the memory fallback so the received bytes can be checked in-page.
|
||||
Object.defineProperty(navigator, 'serviceWorker', { value: undefined });
|
||||
const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
|
||||
const post = async (key: string, value: unknown) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
|
||||
const get = async <K extends keyof Exchange>(key: K): Promise<Exchange[K] | null> => (await fetch('/.test/' + key)).json();
|
||||
const stage = async (text: string) => post(role+'Stage', text);
|
||||
const peers: RTCPeerConnection[] = []; const NativePC = window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends NativePC { constructor(config?: RTCConfiguration) { super(config); peers.push(this); } };
|
||||
setInterval(()=>post(role+'Diagnostic',{status:document.querySelector('[role=status]')?.textContent,error:document.querySelector('[role=alert]')?.textContent,download:!!document.querySelector('a.download')}),2000);
|
||||
try {
|
||||
await wait(()=>document.querySelector('#stun-provider'));
|
||||
if(role==='receiver'){click('Receive');await pause(20);}
|
||||
if(role==='sender'){
|
||||
window.__hellcon.chooseFile(2*1024*1024+7, 'cross-browser.bin'); await pause(20);
|
||||
}
|
||||
input('#stun-provider',provider);await pause(20);
|
||||
if(role==='sender'){
|
||||
await stage('creating offer'); click('Create code');await wait(()=>document.querySelector('#output-code'));
|
||||
await post('offer',element<HTMLTextAreaElement>('#output-code').value);
|
||||
await stage('waiting for answer'); const answer=await wait(()=>get('answer'));input('#answer-input',answer);await pause(20);click('Connect');
|
||||
}else{
|
||||
await stage('waiting for offer'); const offer=await wait(()=>get('offer'));input('#offer-input',offer);await pause(20);
|
||||
await stage('creating answer');click('Accept & create answer');await wait(()=>document.querySelector('#output-code'));
|
||||
await post('answer',element<HTMLTextAreaElement>('#output-code').value);
|
||||
}
|
||||
await stage('comparing fingerprints');await wait(()=>document.querySelector('.fingerprint'));
|
||||
const fps=[...document.querySelectorAll('.fp-row code')].map(el=>el.textContent);
|
||||
await post(role+'Fingerprints',fps);
|
||||
const other=await wait(()=>get(role === 'sender' ? 'receiverFingerprints' : 'senderFingerprints'));
|
||||
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
|
||||
click('Both fingerprints match — confirm');
|
||||
if(role==='receiver'){
|
||||
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Accept file');
|
||||
await stage('receiving');await wait(()=>document.querySelector('a.download'));
|
||||
await wait(()=>get('senderResult'));
|
||||
await pause(250);
|
||||
if(!document.querySelector('a.download'))throw new Error('Download was revoked after sender shutdown');
|
||||
await stage('checking downloaded bytes');
|
||||
const bytes=new Uint8Array(await (await fetch(element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
|
||||
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
|
||||
}else{
|
||||
await stage('waiting for receipt');await wait(()=>element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
click('Disconnect');
|
||||
}
|
||||
await post(role+'Result',{ok:true});
|
||||
}catch(error){
|
||||
await post(role+'Result',{ok:false,error:error instanceof Error ? error.message : String(error),peers:peers.map(pc=>({connection:pc.connectionState,gathering:pc.iceGatheringState,ice:pc.iceConnectionState,localFingerprints:pc.localDescription?.sdp.match(/^a=fingerprint:.*$/gm),remoteFingerprints:pc.remoteDescription?.sdp.match(/^a=fingerprint:.*$/gm)}))});
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
await writeFile(new URL('../.env.development', import.meta.url),
|
||||
`# Local development only; shared by Compose and Vite.\nTURN_SECRET=${randomBytes(32).toString('hex')}\nTURN_HOST=127.0.0.1\nTURN_PORT=3478\nVITE_ICE_ENDPOINT=/api/ice-servers\nVITE_STUN_URL=stun:127.0.0.1:3478\n`,
|
||||
{ flag: 'wx', mode: 0o600 });
|
||||
console.log('Created .env.development with a private development TURN secret.');
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;
|
||||
console.log('.env.development already exists; left unchanged. See .env.example for required settings.');
|
||||
}
|
||||
+610
-209
@@ -1,233 +1,634 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
|
||||
import AppDialog from './components/AppDialog.vue';
|
||||
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts';
|
||||
import type { ReconnectPairing } from './lib/reconnect.ts';
|
||||
import { asError } from './lib/validation.ts';
|
||||
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
|
||||
import {
|
||||
answerOffer,
|
||||
type Check,
|
||||
settings as coreSettings,
|
||||
createOffer,
|
||||
DEFAULT_STUN_SERVERS,
|
||||
DEFAULT_TRACKERS,
|
||||
type Events,
|
||||
formatTime,
|
||||
type Incoming,
|
||||
type Phase,
|
||||
PROTOCOL,
|
||||
type ReceiveEvents,
|
||||
randomCode,
|
||||
receiveViaTracker,
|
||||
type SendEvents,
|
||||
sendViaTracker,
|
||||
} from './core';
|
||||
|
||||
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('');
|
||||
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
|
||||
const current = computed(() => connections.value.find(item => item.id === selected.value));
|
||||
const sidebarOpen = ref(false), adding = ref(false);
|
||||
const confirmingRemoval = ref(false), removing = ref(false), removalId = ref('');
|
||||
const renamingId = ref(''), renameDraft = ref('');
|
||||
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);
|
||||
let persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
|
||||
let updates: BroadcastChannel | undefined;
|
||||
function select(id: string) {
|
||||
selected.value = id; confirmingRemoval.value = false; sidebarOpen.value = false;
|
||||
void nextTick(() => heading.value?.focus());
|
||||
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
|
||||
// defaults.
|
||||
const settings = reactive(coreSettings);
|
||||
|
||||
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
|
||||
const ownSalt = reactive({ on: false, text: '' });
|
||||
// Empty is no salt, Share and Receive wait for one.
|
||||
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
|
||||
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
|
||||
// From the code's alphabet, 16 characters are about 95 bits.
|
||||
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
|
||||
|
||||
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
|
||||
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
|
||||
// contacts nobody before an offer, but typing makes one per keystroke, so each line is checked once.
|
||||
const stunChecks = new Map<string, boolean>();
|
||||
function isStun(url: string) {
|
||||
if (!stunChecks.has(url)) {
|
||||
try {
|
||||
new RTCPeerConnection({ iceServers: [{ urls: url }] }).close();
|
||||
stunChecks.set(url, /^stuns?:/i.test(url));
|
||||
} catch {
|
||||
stunChecks.set(url, false);
|
||||
}
|
||||
function startRename(item: SavedConnection, opener: HTMLButtonElement) {
|
||||
renameContainer = opener.closest<HTMLElement>('.connection-item');
|
||||
renamingId.value = item.id;
|
||||
renameDraft.value = item.name;
|
||||
void nextTick(() => { const input = document.querySelector<HTMLInputElement>('.connection-rename-input'); input?.focus(); input?.select(); });
|
||||
}
|
||||
function saveRename() {
|
||||
const id = renamingId.value;
|
||||
if (!id) return;
|
||||
renamingId.value = '';
|
||||
const name = renameDraft.value.trim();
|
||||
const item = connections.value.find(record => record.id === id);
|
||||
if (name && item && name !== item.name) update(id, { name });
|
||||
return stunChecks.get(url)!;
|
||||
}
|
||||
function focusRenameAction() { void nextTick(() => renameContainer?.querySelector<HTMLButtonElement>('.edit-action')?.focus()); }
|
||||
function cancelRename() { renamingId.value = ''; focusRenameAction(); }
|
||||
function finishRename(event: KeyboardEvent) { (event.target as HTMLInputElement).blur(); focusRenameAction(); }
|
||||
function confirmRemove(id: string) { removalId.value = id; removalError.value = ''; confirmingRemoval.value = true; }
|
||||
function applyRecords(records: SavedConnection[]) {
|
||||
connections.value = records;
|
||||
for (const id of Object.keys(states.value)) if (!records.some(item => item.id === id)) delete states.value[id];
|
||||
if (!records.some(item => item.id === renamingId.value)) renamingId.value = '';
|
||||
// Close a removal prompt whose connection another tab already removed.
|
||||
if (!removing.value && !records.some(item => item.id === removalId.value)) confirmingRemoval.value = false;
|
||||
if (!records.some(item => item.id === selected.value)) select(records[0]!.id);
|
||||
|
||||
// public/ in the build, which works under any path, see vite.config.ts.
|
||||
const BASE = import.meta.env.BASE_URL;
|
||||
|
||||
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
|
||||
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
|
||||
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
|
||||
const secure = location.protocol === 'https:';
|
||||
const isLocal = (hostname: string) =>
|
||||
hostname === 'localhost' ||
|
||||
hostname.endsWith('.localhost') ||
|
||||
/^127\.\d+\.\d+\.\d+$/.test(hostname) ||
|
||||
hostname === '[::1]';
|
||||
const isTracker = (url: string) => {
|
||||
if (!URL.canParse(url) || url.includes('#')) return false;
|
||||
const { protocol, hostname } = new URL(url);
|
||||
return protocol === 'wss:' || (protocol === 'ws:' && (!secure || isLocal(hostname)));
|
||||
};
|
||||
|
||||
// A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped.
|
||||
function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
|
||||
const text = ref(settings[key].join('\n'));
|
||||
const lines = computed(() =>
|
||||
text.value
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
const invalid = computed(() => lines.value.filter((line) => !valid(line)));
|
||||
// Immediate, a default may be a line this browser rejects.
|
||||
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
|
||||
// Unwraps both refs, so the template can bind them as plain properties.
|
||||
return reactive({ text, invalid });
|
||||
}
|
||||
function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') {
|
||||
if (connections.value.some(item => item.id === id)) states.value[id] = state;
|
||||
|
||||
const stunServers = serverList('stunServers', isStun);
|
||||
const trackers = serverList('trackers', isTracker);
|
||||
|
||||
function onResetServers() {
|
||||
stunServers.text = DEFAULT_STUN_SERVERS.join('\n');
|
||||
trackers.text = DEFAULT_TRACKERS.join('\n');
|
||||
}
|
||||
function statusLabel(id: string) { return states.value[id] === 'connected' ? 'Connected' : states.value[id] === 'connecting' ? 'Connecting' : 'Ready to connect'; }
|
||||
async function refresh() {
|
||||
if (!persistent) return;
|
||||
if (pending || removing.value) { refreshRequested = true; return; }
|
||||
refreshRequested = false;
|
||||
try { const records = await loadConnections(); if (!pending && !removing.value) applyRecords(records); else refreshRequested = true; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
|
||||
const file = ref<File>();
|
||||
// The file of the send session, the user may have picked another one since.
|
||||
const shared = ref<File>();
|
||||
const offer = ref('');
|
||||
const answerInput = ref('');
|
||||
const sendCode = ref('');
|
||||
// Until when a receiver can find the share with its code, whether with an own salt and whether that
|
||||
// passed, as the core tells.
|
||||
const sendUntil = ref(0);
|
||||
const sendExpired = ref(false);
|
||||
|
||||
const offerInput = ref('');
|
||||
const answer = ref('');
|
||||
const receiveCode = ref('');
|
||||
|
||||
const check = ref<Check>();
|
||||
const confirmed = ref(false);
|
||||
// Changed in place and triggered, a deep ref would make each line cost every line kept.
|
||||
const log = shallowRef<string[]>([]);
|
||||
// Lines kept, the oldest go first and dropped counts them. A session logs a few dozen, a tracker or
|
||||
// peer that sends garbage could add lines until the tab freezes.
|
||||
const MAX_LOG = 1000;
|
||||
const dropped = ref(0);
|
||||
// Of the session, shown in the card of its side.
|
||||
const error = ref('');
|
||||
const status = ref<{ phase: Phase; text: string }>();
|
||||
// The bar's look, an error colors whatever it showed.
|
||||
const phase = computed(() => (error.value ? 'error' : status.value?.phase));
|
||||
|
||||
// Shared by both sides, each adds its own progress.
|
||||
const events: Omit<Events, 'progress'> = {
|
||||
log: (message) => {
|
||||
const lines = log.value;
|
||||
lines.push(`${new Date().toISOString().slice(11, 23)} ${message}`);
|
||||
if (lines.length > MAX_LOG) dropped.value += lines.splice(0, lines.length - MAX_LOG).length;
|
||||
triggerRef(log);
|
||||
},
|
||||
error: (message) => {
|
||||
events.log(message);
|
||||
error.value = message;
|
||||
},
|
||||
status: (phase, text) => (status.value = { phase, text }),
|
||||
check: (result) => {
|
||||
check.value = result;
|
||||
confirmed.value = false;
|
||||
},
|
||||
};
|
||||
|
||||
// Of the file in transfer, which on the sender isn't necessarily the one picked now. Undefined until
|
||||
// a transfer starts.
|
||||
type Progress = { read: number; size: number };
|
||||
|
||||
const sent = ref<Progress>();
|
||||
const sendEvents: SendEvents = {
|
||||
...events,
|
||||
progress: (read, size) => (sent.value = { read, size }),
|
||||
expired: () => (sendExpired.value = true),
|
||||
};
|
||||
|
||||
const incoming = ref<Incoming>();
|
||||
const received = ref<Progress>();
|
||||
const receiveEvents: ReceiveEvents = {
|
||||
...events,
|
||||
progress: (read, size) => (received.value = { read, size }),
|
||||
incoming: (file) => {
|
||||
incoming.value = file;
|
||||
received.value = undefined;
|
||||
},
|
||||
};
|
||||
|
||||
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
|
||||
|
||||
// Undefined makes the bar indeterminate: until the transfer starts it only shows how the session is
|
||||
// doing. After it, or an error before it, the bar is full.
|
||||
function barValue(progress?: Progress) {
|
||||
if (progress) return percent(progress);
|
||||
return ['start', 'wait', 'retry'].includes(phase.value!) ? undefined : 100;
|
||||
}
|
||||
onMounted(async () => {
|
||||
try { connections.value = await loadConnections(); }
|
||||
catch (err) {
|
||||
persistent = false; connections.value = [emptyConnection()];
|
||||
error.value = `${asError(err).message} Connections will only last for this tab.`;
|
||||
|
||||
function onConfirm() {
|
||||
confirmed.value = true;
|
||||
check.value?.confirm();
|
||||
}
|
||||
selected.value = connections.value[0]!.id;
|
||||
if (typeof BroadcastChannel !== 'undefined') {
|
||||
updates = new BroadcastChannel('hellcon-connections');
|
||||
updates.onmessage = () => { void refresh(); };
|
||||
|
||||
// The text copied last and whether that worked. Its button says so, after a success for a moment.
|
||||
const copied = ref<{ text: string; ok: boolean }>();
|
||||
let copiedTimer: number | undefined;
|
||||
|
||||
const copyLabel = (text: string) => (copied.value?.text !== text ? 'Copy' : copied.value.ok ? 'Copied' : 'Copy failed');
|
||||
const copyFailed = (text: string) => copied.value?.text === text && !copied.value.ok;
|
||||
|
||||
// Copies text, shown in the element with id. If the browser blocks that, the text gets selected, so
|
||||
// the user can copy it themselves.
|
||||
async function onCopy(text: string, id: string) {
|
||||
clearTimeout(copiedTimer);
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
events.log('copy failed, the browser blocked the clipboard');
|
||||
copied.value = { text, ok: false };
|
||||
const element = document.getElementById(id);
|
||||
if (element instanceof HTMLTextAreaElement) {
|
||||
element.focus();
|
||||
element.select();
|
||||
} else if (element) getSelection()?.selectAllChildren(element);
|
||||
return;
|
||||
}
|
||||
window.addEventListener('focus', refresh);
|
||||
copied.value = { text, ok: true };
|
||||
copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
|
||||
}
|
||||
|
||||
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||
|
||||
// One session at a time, started by Share, Create offer, Receive or Create answer. Starting one ends
|
||||
// the one before: its connections close and what it showed goes, so nothing else can write here.
|
||||
let session: AbortController | undefined;
|
||||
const side = ref<'send' | 'receive'>();
|
||||
// Whether the session is a tracker share or search, which runs with the salt it started with.
|
||||
const viaTracker = ref(false);
|
||||
|
||||
// what goes into the log, so the sessions in it can be told apart.
|
||||
function begin(on: 'send' | 'receive', what: string, tracker = false) {
|
||||
session?.abort();
|
||||
session = new AbortController();
|
||||
side.value = on;
|
||||
viaTracker.value = tracker;
|
||||
events.log(`--- ${what} ---`);
|
||||
error.value = '';
|
||||
status.value = undefined;
|
||||
check.value = undefined;
|
||||
confirmed.value = false;
|
||||
sent.value = undefined;
|
||||
incoming.value = undefined;
|
||||
received.value = undefined;
|
||||
sendCode.value = '';
|
||||
sendExpired.value = false;
|
||||
offer.value = '';
|
||||
answer.value = '';
|
||||
acceptAnswer = undefined;
|
||||
return session.signal;
|
||||
}
|
||||
|
||||
// Resolves with the result of a session step, or undefined if it failed, which is shown, or if a
|
||||
// newer session replaced it meanwhile.
|
||||
async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
|
||||
try {
|
||||
const result = await step;
|
||||
return signal.aborted ? undefined : result;
|
||||
} catch (failure) {
|
||||
if (!signal.aborted) events.error(failure instanceof Error ? failure.message : String(failure));
|
||||
}
|
||||
}
|
||||
|
||||
// The name of a dropped folder, until a file takes its place.
|
||||
const folder = ref('');
|
||||
|
||||
function take(picked: File) {
|
||||
file.value = picked;
|
||||
folder.value = '';
|
||||
}
|
||||
|
||||
// The input is emptied right away: Chromium fires no change event for the file its input already
|
||||
// holds, though that file may have changed on disk, or another one was dropped since, which the
|
||||
// input never saw. An event without a file has nothing to take. Empty, the input's own tooltip says no
|
||||
// file is chosen, so its title names the one taken.
|
||||
function onPick(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const picked = input.files?.[0];
|
||||
input.value = '';
|
||||
if (picked) take(picked);
|
||||
}
|
||||
|
||||
const dragging = ref(false);
|
||||
|
||||
// A folder comes as a file too, one that can't be read: refused here, it would fail only once the
|
||||
// receiver downloads it. The file picked before stays.
|
||||
function onDrop(event: DragEvent) {
|
||||
dragging.value = false;
|
||||
const dropped = event.dataTransfer?.files[0];
|
||||
const entry = [...(event.dataTransfer?.items ?? [])].find((item) => item.kind === 'file')?.webkitGetAsEntry();
|
||||
if (entry?.isDirectory) folder.value = entry.name;
|
||||
else if (dropped) take(dropped);
|
||||
}
|
||||
|
||||
function formatSize(bytes: number) {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let unit = 0;
|
||||
while (bytes >= 1024 && unit < units.length - 1) {
|
||||
bytes /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
|
||||
}
|
||||
|
||||
async function onCreateOffer() {
|
||||
const signal = begin('send', `manual offer for ${file.value!.name}`);
|
||||
shared.value = file.value;
|
||||
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
|
||||
if (!result) return;
|
||||
offer.value = result.offer;
|
||||
acceptAnswer = result.accept;
|
||||
}
|
||||
|
||||
// Part of the current session, a wrong answer can be corrected.
|
||||
function onAcceptAnswer() {
|
||||
error.value = '';
|
||||
if (acceptAnswer) attempt(session!.signal, acceptAnswer(answerInput.value));
|
||||
}
|
||||
|
||||
async function onCreateAnswer() {
|
||||
const signal = begin('receive', 'manual answer');
|
||||
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
||||
if (result) answer.value = result;
|
||||
}
|
||||
|
||||
async function onShare() {
|
||||
const signal = begin('send', `share ${file.value!.name} via tracker`, true);
|
||||
shared.value = file.value;
|
||||
const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
|
||||
if (!result) return;
|
||||
sendCode.value = result.code;
|
||||
sendUntil.value = result.until;
|
||||
}
|
||||
|
||||
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
|
||||
// the tracker ends it.
|
||||
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
||||
|
||||
function onReceive() {
|
||||
const signal = begin('receive', 'receive via tracker', true);
|
||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
|
||||
}
|
||||
|
||||
// The salt stays as it is while a tracker share runs: it waits in the swarm of the salt it started
|
||||
// with, another one shown would be the wrong one to give the receiver. A search only takes the salt
|
||||
// on Receive, so a wrong one can be fixed and searched with again.
|
||||
const saltLocked = computed(
|
||||
() => viaTracker.value && side.value === 'send' && !['error', 'done', 'stopped'].includes(phase.value!),
|
||||
);
|
||||
|
||||
// While a share waits or a transfer runs. A phone that dims and locks may suspend the tab and the
|
||||
// connection dies, a reload or a closed tab ends it for sure.
|
||||
const busy = computed(() => ['start', 'wait', 'retry', 'transfer'].includes(phase.value!));
|
||||
|
||||
// The screen's, held while busy. The browser releases it whenever the page is hidden, so it's
|
||||
// requested again once the page is visible.
|
||||
let wakeLock: Promise<WakeLockSentinel | undefined> | undefined;
|
||||
|
||||
function holdWakeLock() {
|
||||
// Missing outside a secure context, e.g. the dev server opened by its LAN address.
|
||||
if (!busy.value || document.hidden || wakeLock || !navigator.wakeLock) return;
|
||||
const request = navigator.wakeLock.request('screen').then(
|
||||
(sentinel) => {
|
||||
sentinel.addEventListener('release', () => {
|
||||
if (wakeLock === request) wakeLock = undefined;
|
||||
});
|
||||
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
|
||||
async function add() {
|
||||
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
|
||||
adding.value = true;
|
||||
try {
|
||||
await writes;
|
||||
if (persistent) connections.value = await addConnection();
|
||||
else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1));
|
||||
select(connections.value.at(-1)!.id); updates?.postMessage('changed');
|
||||
} catch (err) { error.value = asError(err).message; }
|
||||
finally { adding.value = false; }
|
||||
// Unless let go of meanwhile, releaseWakeLock releases it then.
|
||||
if (wakeLock === request) events.log('keeping the screen on');
|
||||
return sentinel;
|
||||
},
|
||||
(failure) => {
|
||||
if (wakeLock === request) wakeLock = undefined;
|
||||
events.log(`screen may lock: ${failure instanceof Error ? failure.message : failure}`);
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
wakeLock = request;
|
||||
}
|
||||
|
||||
// Forgotten right away, a session started before the browser released it requests a new one.
|
||||
function releaseWakeLock() {
|
||||
const request = wakeLock;
|
||||
wakeLock = undefined;
|
||||
request?.then((sentinel) => sentinel?.release());
|
||||
}
|
||||
|
||||
// The browser asks before a reload or a closed tab ends it. Only while busy, a page with the handler
|
||||
// may be kept out of the back/forward cache.
|
||||
const confirmLeave = (event: BeforeUnloadEvent) => event.preventDefault();
|
||||
|
||||
watch(busy, (busy) => {
|
||||
if (busy) {
|
||||
holdWakeLock();
|
||||
addEventListener('beforeunload', confirmLeave);
|
||||
} else {
|
||||
releaseWakeLock();
|
||||
removeEventListener('beforeunload', confirmLeave);
|
||||
}
|
||||
function update(id: string, change: ConnectionUpdate) {
|
||||
const index = connections.value.findIndex(item => item.id === id);
|
||||
if (index < 0) return;
|
||||
try { connections.value[index] = updateConnection(connections.value[index]!, change); }
|
||||
catch (err) { error.value = asError(err).message; return; }
|
||||
if (!persistent) return;
|
||||
pending++;
|
||||
writes = writes.then(async () => {
|
||||
try {
|
||||
const records = await saveConnection(id, change);
|
||||
if (pending === 1) applyRecords(records);
|
||||
updates?.postMessage('changed');
|
||||
} catch (err) {
|
||||
// Keep this tab usable without pretending the change reached storage.
|
||||
error.value = `${asError(err).message} Your latest changes may be lost when this tab closes.`;
|
||||
refreshRequested = true;
|
||||
} 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) {
|
||||
await writes;
|
||||
const records = persistent ? await loadConnections() : connections.value;
|
||||
const record = records.find(item => item.id === id);
|
||||
if (!record) throw new Error('This connection is no longer saved. Reload the page.');
|
||||
if (persistent && !pending && !removing.value) applyRecords(records);
|
||||
return record;
|
||||
}
|
||||
async function remove() {
|
||||
if (!removalTarget.value || removing.value || adding.value) return;
|
||||
const id = removalTarget.value.id, wasSelected = id === selected.value;
|
||||
const index = connections.value.findIndex(item => item.id === id);
|
||||
removing.value = true; removalError.value = '';
|
||||
try {
|
||||
await writes;
|
||||
const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id);
|
||||
applyRecords(records.length ? records : [emptyConnection()]);
|
||||
confirmingRemoval.value = false;
|
||||
await nextTick();
|
||||
// Focus the newly opened row, or the row that took the removed row's place.
|
||||
const row = wasSelected ? document.querySelector('.connection-item.selected') : document.querySelectorAll('.connection-item')[Math.min(index, connections.value.length - 1)];
|
||||
const link = row?.querySelector<HTMLButtonElement>('.connection-link');
|
||||
if (link?.offsetParent) link.focus();
|
||||
else heading.value?.focus();
|
||||
updates?.postMessage('changed');
|
||||
} catch (err) { removalError.value = asError(err).message; }
|
||||
finally { removing.value = false; if (refreshRequested) void refresh(); }
|
||||
}
|
||||
document.addEventListener('visibilitychange', holdWakeLock);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a class="skip-link" href="#main-content">Skip to main content</a>
|
||||
<div class="app-shell" :class="{ 'sidebar-open': sidebarOpen }">
|
||||
<aside id="connections-sidebar" class="sidebar" aria-label="Connections sidebar">
|
||||
<header class="brand">
|
||||
<img :src="logoUrl" width="38" height="38" alt="" />
|
||||
<div><span class="brand-name">HellCon</span><p>Direct file sharing</p></div>
|
||||
</header>
|
||||
<div class="sidebar-section-heading"><h2>Connections</h2><span>{{ connections.length }}</span></div>
|
||||
<nav class="connection-nav" aria-label="Connections">
|
||||
<div v-for="item in connections" :key="item.id" class="connection-item" :class="{ selected: selected === item.id }">
|
||||
<button v-if="renamingId !== item.id" class="connection-link" :aria-current="selected === item.id ? 'page' : undefined" @click="select(item.id)">
|
||||
<span class="connection-name">{{ item.name }}</span>
|
||||
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
|
||||
<header>
|
||||
<div>
|
||||
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
|
||||
<h1>HellCon</h1>
|
||||
</div>
|
||||
<div id="options">
|
||||
<div>
|
||||
<label>
|
||||
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
||||
Use STUN
|
||||
</label>
|
||||
<label>
|
||||
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
|
||||
Use own salt
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="ownSalt.on" role="group">
|
||||
<input
|
||||
id="salt"
|
||||
v-model="ownSalt.text"
|
||||
aria-label="Own salt"
|
||||
placeholder="Same salt on both sides"
|
||||
:aria-invalid="saltMissing"
|
||||
:disabled="saltLocked"
|
||||
autocapitalize="off"
|
||||
autocomplete="off"
|
||||
autocorrect="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
|
||||
Generate
|
||||
</button>
|
||||
<div v-else class="connection-edit">
|
||||
<input v-model="renameDraft" class="connection-rename-input" :aria-label="`New name for ${item.name}`" aria-describedby="rename-hint" maxlength="80" autocomplete="off" spellcheck="false"
|
||||
@blur="saveRename" @keydown.enter.prevent="finishRename" @keydown.esc.prevent="cancelRename" />
|
||||
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
|
||||
</div>
|
||||
<button v-if="renamingId !== item.id" class="connection-action edit-action" :aria-label="`Rename ${item.name}`" :title="`Rename ${item.name}`" :disabled="removing" @click="startRename(item, $event.currentTarget as HTMLButtonElement)"><span aria-hidden="true">✎</span></button>
|
||||
<button class="connection-action remove-action" :aria-label="`Remove ${item.name}`" :title="`Remove ${item.name}`" :disabled="adding || removing" @click="confirmRemove(item.id)"><span aria-hidden="true">✕</span></button>
|
||||
</div>
|
||||
<span id="rename-hint" class="sr-only">Press Enter or leave the field to save. Press Escape to cancel.</span>
|
||||
</nav>
|
||||
<button class="add-connection" :disabled="adding || removing || !connections.length || connections.length >= CONNECTION_LIMIT" @click="add"><span aria-hidden="true">+</span> Add connection</button>
|
||||
<footer class="sidebar-footer">
|
||||
<span class="sidebar-tag">Browser to browser</span>
|
||||
<p>No accounts. Your connections stay on this device.</p>
|
||||
<details class="privacy-details">
|
||||
<summary>About privacy & connections</summary>
|
||||
<p>Files travel over encrypted WebRTC data channels. Compare full fingerprints on first pairing, or let a connection authenticate its remembered device. Reconnect by exchanging fresh codes.</p>
|
||||
<p>Trust your browser and the app’s host: its code can read selected files and use your device identity. HTTPS protects delivery. A TURN relay is used only after opt-in.</p>
|
||||
<p>Clearing site data removes saved connections and identities.</p>
|
||||
</details>
|
||||
<a class="source-link" href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer" aria-label="View HellCon source code on Gitea">
|
||||
<img :src="giteaIconUrl" width="20" height="20" alt="" />
|
||||
<span>Source code</span>
|
||||
</a>
|
||||
</footer>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<p v-if="!settings.stun" id="no-stun" role="note">
|
||||
STUN is off: only devices on the same network or VPN can connect.
|
||||
</p>
|
||||
<p v-else-if="!settings.stunServers.length" id="no-stun" role="note">
|
||||
No STUN server under Servers: only devices on the same network or VPN can connect.
|
||||
</p>
|
||||
<aside v-if="check" role="alert">
|
||||
<p>
|
||||
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
|
||||
before.
|
||||
</p>
|
||||
<dl>
|
||||
<dt>You</dt>
|
||||
<dd><output id="check-local">{{ check.local }}</output></dd>
|
||||
<dt>Peer</dt>
|
||||
<dd><output id="check-remote">{{ check.remote }}</output></dd>
|
||||
</dl>
|
||||
<div v-if="!confirmed">
|
||||
<button id="confirm" type="button" @click="onConfirm">Codes match</button>
|
||||
<button id="reject" type="button" @click="check.reject()">Codes don't match</button>
|
||||
</div>
|
||||
</aside>
|
||||
<main id="main-content" class="main-pane" tabindex="-1">
|
||||
<h1 v-if="current" ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
|
||||
<div class="mobile-bar">
|
||||
<div v-if="current" class="mobile-current">
|
||||
<span class="mobile-current-name" aria-hidden="true">{{ current.name }}</span>
|
||||
<span class="connection-status-line"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span><span class="mobile-current-status">{{ statusLabel(current.id) }}</span></span>
|
||||
</div>
|
||||
<button class="sidebar-toggle" :aria-expanded="sidebarOpen" aria-controls="connections-sidebar" @click="sidebarOpen = !sidebarOpen">{{ sidebarOpen ? 'Hide connections' : 'Show connections' }}</button>
|
||||
</div>
|
||||
<div class="workspace-scroll">
|
||||
<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" :save-reconnect="saveReconnect"
|
||||
@status="setStatus" @update="update" />
|
||||
</KeepAlive>
|
||||
|
||||
<article>
|
||||
<h2>Send</h2>
|
||||
<label
|
||||
:data-dragging="dragging || undefined"
|
||||
@dragover.prevent="dragging = true"
|
||||
@dragleave="dragging = false"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<input type="file" :title="file?.name" @change="onPick" />
|
||||
<template v-if="file">
|
||||
<strong>{{ file.name }}</strong>
|
||||
{{ formatSize(file.size) }}
|
||||
</template>
|
||||
<p v-if="!current" class="status">Opening your connections…</p>
|
||||
<template v-else>Drop a file or click to choose</template>
|
||||
<span v-if="folder" id="not-a-file" role="alert">{{ folder }} is a folder, only a single file can be sent</span>
|
||||
</label>
|
||||
<div v-if="side === 'send' && phase" :data-phase="phase">
|
||||
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
|
||||
<div>
|
||||
<progress id="send-progress" max="100" :value="barValue(sent)" aria-label="Sent"></progress>
|
||||
</div>
|
||||
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="send-status">{{ status!.text }}</span>
|
||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h3>Tracker</h3>
|
||||
<button id="share" type="button" :disabled="!file || !settings.trackers.length || saltMissing" @click="onShare">
|
||||
Share via tracker
|
||||
</button>
|
||||
<template v-if="sendCode">
|
||||
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
|
||||
<label v-else for="send-code">
|
||||
Code, give this {{ ownSalt.on ? 'and your salt ' : '' }}to the receiver, valid until
|
||||
{{ formatTime(sendUntil) }}:
|
||||
</label>
|
||||
<div role="group">
|
||||
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
||||
<button
|
||||
id="copy-send-code"
|
||||
type="button"
|
||||
data-copy
|
||||
:disabled="codeGone"
|
||||
@click="onCopy(sendCode, 'send-code')"
|
||||
>
|
||||
{{ copyLabel(sendCode) }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="copyFailed(sendCode)" role="alert">
|
||||
The browser blocked copying. The code is selected, copy it yourself.
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<details id="send-manual">
|
||||
<summary>Manual</summary>
|
||||
<section>
|
||||
<button id="create-offer" type="button" :disabled="!file" @click="onCreateOffer">Create offer</button>
|
||||
<template v-if="offer">
|
||||
<label for="offer">Offer, send this to the receiver:</label>
|
||||
<textarea id="offer" readonly :value="offer"></textarea>
|
||||
<button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
|
||||
{{ copyLabel(offer) }}
|
||||
</button>
|
||||
<p v-if="copyFailed(offer)" role="alert">
|
||||
The browser blocked copying. The offer is selected, copy it yourself.
|
||||
</p>
|
||||
<label for="answer-input">Answer from the receiver:</label>
|
||||
<textarea id="answer-input" v-model="answerInput"></textarea>
|
||||
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
|
||||
Connect
|
||||
</button>
|
||||
</template>
|
||||
</section>
|
||||
</details>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h2>Receive</h2>
|
||||
<div id="incoming">
|
||||
<template v-if="incoming">
|
||||
<strong>{{ incoming.name }}</strong>
|
||||
{{ formatSize(incoming.size) }}
|
||||
<button v-if="!received" id="download" type="button" @click="incoming.download()">Download</button>
|
||||
</template>
|
||||
<template v-else>The sender's file shows up here after the security check</template>
|
||||
</div>
|
||||
<div v-if="side === 'receive' && phase" :data-phase="phase">
|
||||
<div>
|
||||
<progress id="receive-progress" max="100" :value="barValue(received)" aria-label="Received"></progress>
|
||||
</div>
|
||||
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="receive-status">{{ status!.text }}</span>
|
||||
<span v-if="received">{{ percent(received) }} %</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h3>Tracker</h3>
|
||||
<label for="receive-code">Code from the sender:</label>
|
||||
<div role="group">
|
||||
<input
|
||||
id="receive-code"
|
||||
v-model="receiveCode"
|
||||
autocapitalize="off"
|
||||
autocomplete="off"
|
||||
autocorrect="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<button
|
||||
id="receive"
|
||||
type="button"
|
||||
:disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
|
||||
@click="onReceive"
|
||||
>
|
||||
Receive
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<details id="receive-manual">
|
||||
<summary>Manual</summary>
|
||||
<section>
|
||||
<label for="offer-input">Offer from the sender:</label>
|
||||
<textarea id="offer-input" v-model="offerInput"></textarea>
|
||||
<button id="create-answer" type="button" :disabled="!offerInput.trim()" @click="onCreateAnswer">
|
||||
Create answer
|
||||
</button>
|
||||
<template v-if="answer">
|
||||
<label for="answer">Answer, send this back to the sender:</label>
|
||||
<textarea id="answer" readonly :value="answer"></textarea>
|
||||
<button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
|
||||
{{ copyLabel(answer) }}
|
||||
</button>
|
||||
<p v-if="copyFailed(answer)" role="alert">
|
||||
The browser blocked copying. The answer is selected, copy it yourself.
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
</details>
|
||||
</article>
|
||||
|
||||
<details id="servers">
|
||||
<summary>Servers</summary>
|
||||
<div>
|
||||
<section>
|
||||
<h3>STUN</h3>
|
||||
<label for="stun-servers">Tell each side its public address, one URL per line:</label>
|
||||
<textarea
|
||||
id="stun-servers"
|
||||
v-model="stunServers.text"
|
||||
:aria-invalid="!!stunServers.invalid.length"
|
||||
></textarea>
|
||||
<p v-if="stunServers.invalid.length">
|
||||
Skipped, not a STUN URL this browser accepts: {{ stunServers.invalid.join(', ') }}
|
||||
</p>
|
||||
</section>
|
||||
<section>
|
||||
<h3>Trackers</h3>
|
||||
<label for="trackers">WebTorrent trackers for the code exchange, one URL per line:</label>
|
||||
<textarea id="trackers" v-model="trackers.text" :aria-invalid="!!trackers.invalid.length"></textarea>
|
||||
<p v-if="trackers.invalid.length">
|
||||
Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}:
|
||||
{{ trackers.invalid.join(', ') }}
|
||||
</p>
|
||||
</section>
|
||||
<button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Log</summary>
|
||||
<pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
|
||||
</details>
|
||||
</main>
|
||||
</div>
|
||||
<AppDialog v-model="confirmingRemoval" :title="`Remove ${removalTarget?.name || 'connection'}?`" :busy="removing">
|
||||
<p>This ends its session and forgets its remembered device. Saved files and your device identity are kept.</p>
|
||||
<p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p>
|
||||
<p v-if="removalError" class="error" role="alert">{{ removalError }}</p>
|
||||
<template #actions="{ close }">
|
||||
<button :disabled="removing" autofocus @click="close">Keep connection</button>
|
||||
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
|
||||
</template>
|
||||
</AppDialog>
|
||||
|
||||
<footer>
|
||||
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
||||
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
|
||||
Source code
|
||||
</a>
|
||||
<span>Protocol {{ PROTOCOL }}</span>
|
||||
</footer>
|
||||
</template>
|
||||
@@ -1,41 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, useId, watch } from 'vue';
|
||||
|
||||
const open = defineModel<boolean>({ default: false });
|
||||
const props = defineProps<{ title: string; busy?: boolean }>();
|
||||
const dialog = ref<HTMLDialogElement | null>(null);
|
||||
const titleId = useId(), bodyId = useId();
|
||||
function close() { if (!props.busy) open.value = false; }
|
||||
function closed() { if (!dialog.value?.open) open.value = false; }
|
||||
// showModal() makes the page inert but lets Tab leave for the browser UI; wrap instead.
|
||||
function trap(event: KeyboardEvent) {
|
||||
const items = [...dialog.value?.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])') ?? []]
|
||||
.filter(item => !item.matches(':disabled') && item.offsetParent !== null);
|
||||
const first = items[0], last = items.at(-1);
|
||||
if (!first || !last) { event.preventDefault(); return; }
|
||||
const active = document.activeElement;
|
||||
if (event.shiftKey && (active === first || !dialog.value?.contains(active))) { event.preventDefault(); last.focus(); }
|
||||
else if (!event.shiftKey && (active === last || !dialog.value?.contains(active))) { event.preventDefault(); first.focus(); }
|
||||
}
|
||||
function sync() {
|
||||
if (open.value && !dialog.value?.open) dialog.value?.showModal();
|
||||
else if (!open.value && dialog.value?.open) dialog.value.close();
|
||||
}
|
||||
watch(open, sync, { flush: 'post' });
|
||||
onMounted(sync);
|
||||
onBeforeUnmount(() => dialog.value?.close());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<dialog ref="dialog" class="app-dialog" :aria-labelledby="titleId" :aria-describedby="bodyId" :aria-busy="busy || undefined"
|
||||
@cancel.prevent="close" @close="closed" @keydown.tab="trap">
|
||||
<header class="dialog-header">
|
||||
<h2 :id="titleId">{{ title }}</h2>
|
||||
<button class="dialog-close" type="button" aria-label="Close dialog" :disabled="busy" @click="close"><span aria-hidden="true">×</span></button>
|
||||
</header>
|
||||
<div :id="bodyId" class="dialog-body"><slot :close="close" /></div>
|
||||
<div v-if="$slots.actions" class="dialog-actions"><slot name="actions" :close="close" /></div>
|
||||
</dialog>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -1,36 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import TransferPanel from './TransferPanel.vue';
|
||||
import type { SavedConnection, ConnectionUpdate } from '../lib/connections.ts';
|
||||
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];
|
||||
}>();
|
||||
const mode = ref<'send' | 'receive'>('send');
|
||||
const sessionActive = ref(false), connected = ref(false);
|
||||
const direction = ref<'send' | 'receive'>('send');
|
||||
const panel = ref<InstanceType<typeof TransferPanel> | null>(null);
|
||||
function status() { emit('status', props.connection.id, connected.value ? 'connected' : sessionActive.value ? 'connecting' : 'ready'); }
|
||||
function navigate(next: 'send' | 'receive') {
|
||||
if (connected.value) { direction.value = next; panel.value?.focusDirection(next); }
|
||||
else if (!sessionActive.value) mode.value = next;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="connection-workspace">
|
||||
<div class="workspace-intro">
|
||||
<h2>{{ connected ? 'Share files' : 'Start a session' }}</h2>
|
||||
<p>{{ connected ? 'Your connection is ready.' : 'Exchange connection codes with your peer to start sharing.' }} Each direction sends one file at a time; both people can send on this connection.</p>
|
||||
</div>
|
||||
<div class="tabs" role="group" :aria-label="connected ? 'Transfer sections' : 'Connection setup'">
|
||||
<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)" :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>
|
||||
</template>
|
||||
@@ -1,84 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
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; 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 });
|
||||
const working = ref(false), loaded = ref(false);
|
||||
const error = ref(''), confirmDelete = ref(false);
|
||||
onMounted(async () => {
|
||||
if (!supported) return;
|
||||
try { state.value = await loadIdentityState(); loaded.value = true; }
|
||||
catch (err) { error.value = asError(err).message; }
|
||||
});
|
||||
onActivated(async () => {
|
||||
// Another slot may have replaced the shared identity while this workspace
|
||||
// was cached. Never interrupt an active session to refresh it.
|
||||
if (!loaded.value || props.disabled) return;
|
||||
try {
|
||||
const next = await loadIdentityState();
|
||||
if (props.disabled) return;
|
||||
if (next.revision !== state.value.revision) confirmDelete.value = false;
|
||||
state.value = next;
|
||||
} catch (err) { error.value = asError(err).message; }
|
||||
});
|
||||
async function run(action: () => Promise<void>) {
|
||||
if (props.disabled || working.value) return;
|
||||
working.value = true; error.value = '';
|
||||
try { await action(); } catch (err) { error.value = asError(err).message; }
|
||||
finally { working.value = false; }
|
||||
}
|
||||
function recover() { void run(async () => { if (!confirmDelete.value) return; await clearIdentityStorage(); state.value = { identity: null }; loaded.value = true; confirmDelete.value = false; }); }
|
||||
// Creating an identity from a connection opts that connection in.
|
||||
function create() { void run(async () => { state.value = await saveIdentityState({ identity: await createIdentity() }, state.value.revision); emit('update', { rememberDevice: true }); }); }
|
||||
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;
|
||||
try {
|
||||
const next = await loadIdentityState();
|
||||
if (next.revision !== state.value.revision) confirmDelete.value = false;
|
||||
state.value = next; loaded.value = true; error.value = '';
|
||||
return next.identity;
|
||||
} catch (err) {
|
||||
error.value = asError(err).message;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
defineExpose({ refreshIdentity });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<details v-if="supported" class="config-details">
|
||||
<summary>Remembered device</summary>
|
||||
<p class="status">Optionally remember the device on this connection, so later sessions verify it automatically. This uses a device identity stored in this browser and shared by all connections. Clearing site data loses it. Trusted app code is required: it can use this identity.</p>
|
||||
<fieldset class="device-settings" :disabled="disabled || working || !loaded">
|
||||
<button v-if="!state.identity" @click="create">Create device identity</button>
|
||||
<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>
|
||||
<p class="status">When enabled, your public identity is included in this connection’s codes and can link your sessions.</p>
|
||||
<label><input v-model="confirmDelete" type="checkbox" /> Delete this browser’s device identity</label>
|
||||
<button :disabled="!confirmDelete" @click="reset">Delete device identity</button>
|
||||
</template>
|
||||
</fieldset>
|
||||
<div v-if="!loaded && error">
|
||||
<label><input v-model="confirmDelete" type="checkbox" :disabled="disabled || working" /> Delete unreadable device storage</label>
|
||||
<button :disabled="disabled || working || !confirmDelete" @click="recover">Clear device storage</button>
|
||||
</div>
|
||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
||||
</details>
|
||||
</template>
|
||||
@@ -1,51 +0,0 @@
|
||||
<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 });
|
||||
// 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>
|
||||
<fieldset :disabled="disabled" class="network-settings">
|
||||
<legend>Connection settings</legend>
|
||||
<label for="stun-provider">STUN provider</label>
|
||||
<select id="stun-provider" v-model="settings.stunChoice" class="stun-select">
|
||||
<option v-for="provider in STUN_PROVIDERS" :key="provider.id" :value="provider.id">{{ provider.label }}</option>
|
||||
<option value="custom">Custom…</option>
|
||||
</select>
|
||||
<input v-if="settings.stunChoice === 'custom'" v-model="settings.customStun" class="stun-input" aria-label="Custom STUN address" placeholder="stun:your.domain:3478" />
|
||||
<p class="status">STUN helps discover a reachable address. Its operator sees your public IP and request timing, but does not carry your file. Direct connections may fail on restrictive networks.</p>
|
||||
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
|
||||
<template v-if="settings.allowTurn">
|
||||
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
|
||||
<label v-if="iceEndpoint" class="checkbox"><input type="checkbox" v-model="settings.managedTurn" /> Use the configured relay with temporary credentials</label>
|
||||
<template v-if="iceEndpoint && settings.managedTurn">
|
||||
<p v-if="!managedCredentials" class="status">The relay details will appear here when you create a connection code.</p>
|
||||
<input class="stun-input" aria-label="TURN address" :value="Array.isArray(managedCredentials?.turnUrl) ? managedCredentials.turnUrl.join(', ') : managedCredentials?.turnUrl || ''" placeholder="TURN address (filled when creating a code)" readonly />
|
||||
<input class="stun-input" aria-label="TURN username" :value="managedCredentials?.username || ''" placeholder="TURN username (filled when creating a code)" readonly />
|
||||
<input class="stun-input" type="password" aria-label="TURN password" :value="managedCredentials?.credential || ''" placeholder="TURN password (filled when creating a code)" autocomplete="off" readonly />
|
||||
</template>
|
||||
<template v-else>
|
||||
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
|
||||
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
|
||||
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
|
||||
</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>
|
||||
@@ -1,799 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
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, 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 { 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' | '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;
|
||||
diagnostics: ConnectionDiagnostics;
|
||||
localHello?: IdentityHello;
|
||||
remoteHello?: IdentityHello;
|
||||
identityContext?: IdentityContext;
|
||||
identity?: IdentityState['identity'];
|
||||
expected?: string;
|
||||
// Shared by this session's offer and answer codes.
|
||||
ref?: string;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
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
|
||||
// this connection's paired device: 'new' starts ticked, 'replace' does not.
|
||||
const pairing = ref<'' | 'new' | 'replace'>(''), rememberPeer = ref(false);
|
||||
const file = ref<File | null>(null);
|
||||
const selectedFiles = ref<File[]>([]);
|
||||
const queuedFiles = ref<QueueItem[]>([]);
|
||||
const sendState = ref<TransferState | null>(null);
|
||||
const receiveState = ref<TransferState | null>(null);
|
||||
const outgoing = ref<FileMetadata | null>(null);
|
||||
const receiveProgress = ref(0);
|
||||
const lastDirection = ref<'send' | 'receive'>('send');
|
||||
const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean]; update: [change: ConnectionUpdate] }>();
|
||||
const inputCode = ref('');
|
||||
const outputCode = ref('');
|
||||
const step = ref<Step>('idle');
|
||||
const error = ref('');
|
||||
const copied = ref(false);
|
||||
const fps = ref<Fingerprints | null>(null);
|
||||
const verified = ref(false);
|
||||
const progress = ref(0);
|
||||
const incoming = ref<FileMetadata | null>(null);
|
||||
const downloadUrl = ref('');
|
||||
const downloadName = ref('');
|
||||
const connected = ref(false);
|
||||
const sendSection = ref<HTMLElement | null>(null);
|
||||
const receiveSection = ref<HTMLElement | 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' });
|
||||
}
|
||||
defineExpose({ focusDirection });
|
||||
|
||||
const choosing = ref(false);
|
||||
const dragover = ref(false);
|
||||
const diagnosticLines = ref<string[]>([]);
|
||||
let latestDiagnostics: ConnectionDiagnostics | null = null;
|
||||
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);
|
||||
// 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(() => {
|
||||
if (!incoming.value) return null;
|
||||
if (supportsStreamingDownload()) return 'download';
|
||||
if (typeof window.showSaveFilePicker === 'function') return 'disk';
|
||||
return incoming.value.size <= MEMORY_LIMIT ? 'memory' : null;
|
||||
});
|
||||
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 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.',
|
||||
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
|
||||
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
|
||||
done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (savedToDisk.value ? 'File saved to disk.' : 'File handed to your browser. Check Downloads for the final save result.'),
|
||||
closed: props.sending
|
||||
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.'
|
||||
: 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.',
|
||||
}[step.value] || ''));
|
||||
|
||||
function revokeDownload() {
|
||||
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
|
||||
downloadUrl.value = ''; downloadName.value = '';
|
||||
}
|
||||
function saveDownload() {
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl.value; link.download = downloadName.value;
|
||||
document.body.append(link); link.click(); link.remove();
|
||||
}
|
||||
function dispose() {
|
||||
const old = active;
|
||||
if (old) {
|
||||
if (outgoing.value && sendState.value && !['done', 'closed'].includes(sendState.value)) sendState.value = 'closed';
|
||||
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);
|
||||
// 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());
|
||||
old.controller.abort();
|
||||
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;
|
||||
stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer);
|
||||
if (keepNetwork) settings.value.allowTurn = allowTurn;
|
||||
latestDiagnostics = null; diagnosticLines.value = [];
|
||||
managedCredentials.value = null;
|
||||
if (!keepNetwork) settings.value.allowTurn = false;
|
||||
inputCode.value = outputCode.value = error.value = '';
|
||||
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
|
||||
fps.value = incoming.value = null;
|
||||
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');
|
||||
stopAttempt(); dispose();
|
||||
managedCredentials.value = null;
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = false;
|
||||
settings.value.allowTurn = false;
|
||||
if (sendState.value && sendState.value !== 'done') sendState.value = 'closed';
|
||||
if (receiveState.value && receiveState.value !== 'done') receiveState.value = 'closed';
|
||||
error.value = asError(err).message; step.value = 'closed';
|
||||
}
|
||||
function pickFiles(event: Event) {
|
||||
const list = event.target instanceof HTMLInputElement ? event.target.files
|
||||
: event instanceof DragEvent ? event.dataTransfer?.files : null;
|
||||
const files = Array.from(list || []);
|
||||
if (!files.length) return;
|
||||
try {
|
||||
if (files.length > QUEUE_LIMIT) throw new Error(`Queue up to ${QUEUE_LIMIT} files at a time.`);
|
||||
for (const item of files) validateMetadata({ name: item.name, size: item.size, mime: item.type || '' });
|
||||
if (active?.transfer) active.transfer.add(files);
|
||||
else {
|
||||
if (active) throw new Error('Finish connecting before adding more files.');
|
||||
selectedFiles.value = files; file.value = files[0]!;
|
||||
}
|
||||
error.value = '';
|
||||
} catch (err) { error.value = asError(err).message; }
|
||||
if (event.target instanceof HTMLInputElement) event.target.value = '';
|
||||
}
|
||||
function removeQueued(id: number) { active?.transfer?.remove(id); }
|
||||
function disconnect() {
|
||||
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;
|
||||
}
|
||||
function declineFile() { if (!choosing.value) active?.transfer?.decline(); }
|
||||
function attach(session: Session, channel: RTCDataChannel) {
|
||||
if (active !== session) { channel.close(); return; }
|
||||
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;
|
||||
}
|
||||
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.'; 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;
|
||||
step.value = state; lastDirection.value = direction;
|
||||
session.diagnostics.record(`transfer ${direction} ${state}`);
|
||||
if (state === 'done') session.diagnostics.record('transfer done');
|
||||
if (direction === 'send') { sendState.value = state; outgoing.value = meta; if (state === 'waiting-accept') progress.value = 0; }
|
||||
else { receiveState.value = state; if (state === 'choose-storage' && meta.name) { incoming.value = meta; receiveProgress.value = 0; savedToDisk.value = false; } }
|
||||
},
|
||||
onProgress: (direction, bytes, size) => {
|
||||
if (active !== session) return;
|
||||
const percent = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100));
|
||||
if (direction === 'send') progress.value = percent; else receiveProgress.value = percent;
|
||||
},
|
||||
onComplete: (direction, { blob, meta }) => {
|
||||
if (active !== session) return;
|
||||
if (direction === 'send') progress.value = 100; else receiveProgress.value = 100;
|
||||
void session.diagnostics.capture();
|
||||
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); }
|
||||
},
|
||||
onDecline: direction => {
|
||||
if (active !== session) return;
|
||||
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
|
||||
if (lastDirection.value === direction) {
|
||||
const other = direction === 'send' ? receiveState.value : sendState.value;
|
||||
step.value = other && other !== 'done' ? other : 'session-ready';
|
||||
lastDirection.value = direction === 'send' ? 'receive' : 'send';
|
||||
}
|
||||
},
|
||||
onClose: () => { if (active === session) disconnect(); },
|
||||
onError: err => fail(session, err),
|
||||
});
|
||||
configureIdentity(session);
|
||||
if (verified.value) session.transfer.verify();
|
||||
}
|
||||
function start(initiator: boolean) {
|
||||
const chosen = settings.value;
|
||||
const options = {
|
||||
...chosen,
|
||||
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
|
||||
turnUrl: chosen.turnUrl.trim(),
|
||||
};
|
||||
// Fetch managed credentials before gathering, while retaining normal cancellation.
|
||||
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
|
||||
let diagnostics: ConnectionDiagnostics;
|
||||
diagnostics = new ConnectionDiagnostics(pc, lines => {
|
||||
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
|
||||
});
|
||||
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
|
||||
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);
|
||||
pc.onconnectionstatechange = () => {
|
||||
if (active !== session) return;
|
||||
if (['failed', 'closed'].includes(pc.connectionState)) {
|
||||
const unfinished = [sendState.value, receiveState.value].some(state => state && state !== 'done' && state !== 'closed');
|
||||
if (connected.value && !unfinished) disconnect();
|
||||
else fail(session, new Error(connected.value
|
||||
? 'Connection lost. Unfinished files were cancelled. Exchange fresh codes to reconnect.'
|
||||
: 'Could not establish the peer connection. Retry with fresh codes. If it fails again, copy Connection diagnostics from both devices.'));
|
||||
}
|
||||
};
|
||||
return session;
|
||||
}
|
||||
async function createCode() {
|
||||
const pasted = inputCode.value;
|
||||
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
|
||||
let session: Session | undefined;
|
||||
try {
|
||||
if (props.sending) {
|
||||
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(!!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) {
|
||||
const trust = await props.loadTrust();
|
||||
const identity = trust.rememberDevice ? await devices.value?.refreshIdentity() : null;
|
||||
if (active !== session) return;
|
||||
if (trust.rememberDevice) session.expected = trust.peerKey;
|
||||
if (identity) { session.identity = identity; session.localHello = hello(identity); }
|
||||
}
|
||||
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
|
||||
if (active !== session) return;
|
||||
session.pc.setConfiguration(iceConfiguration(configured));
|
||||
managedCredentials.value = session.options.allowTurn && session.options.managedTurn ? configured : null;
|
||||
const offer = props.sending ? null : await decodeCode(pasted, { type: 'offer', allowTurn: session.options.allowTurn });
|
||||
if (active !== session) return;
|
||||
session.ref = offer ? offer.ref : createRef(); session.remoteHello = offer?.identity;
|
||||
const options = { ...session.options, signal: session.controller.signal };
|
||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
|
||||
const sdp = offer ? await createAnswer(session.pc, offer.sdp, options) : await createOffer(session.pc, options);
|
||||
if (active !== session) return;
|
||||
const code = await encodeCode({ type: props.sending ? 'offer' : 'answer', ref: session.ref, sdp, identity: session.localHello });
|
||||
if (active !== session) return;
|
||||
outputCode.value = code;
|
||||
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
|
||||
session.diagnostics.descriptions();
|
||||
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';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
|
||||
}
|
||||
}
|
||||
async function useAnswer() {
|
||||
const session = active;
|
||||
if (!session || step.value !== 'offer-ready') return;
|
||||
error.value = '';
|
||||
step.value = 'verification';
|
||||
try {
|
||||
const answer = await decodeCode(inputCode.value, { type: 'answer', ref: session.ref, allowTurn: session.options.allowTurn });
|
||||
if (active !== session) return;
|
||||
session.remoteHello = answer.identity;
|
||||
await acceptAnswer(session.pc, answer.sdp, session.options);
|
||||
if (active !== session) return;
|
||||
session.diagnostics.record('answer applied');
|
||||
session.diagnostics.descriptions();
|
||||
void session.diagnostics.capture();
|
||||
fps.value = getFingerprints(session.pc, session.options);
|
||||
offerPairing(session);
|
||||
configureIdentity(session);
|
||||
} catch (err) {
|
||||
if (active !== session) return;
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
// correct a paste error instead of silently invalidating both peers' codes.
|
||||
if (session.pc.signalingState === 'have-local-offer') {
|
||||
error.value = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
|
||||
step.value = 'offer-ready';
|
||||
} else fail(session, err);
|
||||
}
|
||||
}
|
||||
function offerPairing(session: Session) {
|
||||
const key = session.localHello && session.remoteHello?.key;
|
||||
pairing.value = !key || key === session.expected ? '' : session.expected ? 'replace' : 'new';
|
||||
rememberPeer.value = pairing.value === 'new';
|
||||
}
|
||||
function configureIdentity(session: Session) {
|
||||
if (!fps.value || !session.transfer || session.identityContext) return;
|
||||
if (!session.identity || !session.localHello || !session.remoteHello) {
|
||||
if (session.expected) identityStatus.value = 'A device identity is missing. Compare both fingerprints manually; the paired device is not being used.';
|
||||
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 = session.initiator;
|
||||
const context: IdentityContext = {
|
||||
offer: initiator ? session.localHello : session.remoteHello,
|
||||
answer: initiator ? session.remoteHello : session.localHello,
|
||||
offerFingerprint: initiator ? fps.value.local : fps.value.remote,
|
||||
answerFingerprint: initiator ? fps.value.remote : fps.value.local,
|
||||
};
|
||||
session.identityContext = context;
|
||||
const identity = session.identity;
|
||||
session.transfer.authenticate({ sign: () => signIdentity(identity, context, initiator), verify: proof => verifyIdentity(proof, context, !initiator) });
|
||||
if (session.expected === session.remoteHello.key) {
|
||||
identityStatus.value = 'Checking the paired device’s fresh proof…'; verify();
|
||||
} else {
|
||||
identityStatus.value = session.expected ? 'Device identity differs from the paired device. Compare both fingerprints manually before continuing. The paired device is only replaced if you choose to.' : 'New device. Compare both fingerprints manually before remembering it.';
|
||||
}
|
||||
}
|
||||
function verify() {
|
||||
if (!active || !fps.value || verified.value) return;
|
||||
verified.value = true; step.value = 'verification';
|
||||
// Gathering/handshake timeout ends; Transfer manages verification and transfer deadlines.
|
||||
const session = active;
|
||||
clearTimeout(session.timer);
|
||||
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;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
if (destination === 'download') {
|
||||
writable = await createDownloadDestination(incoming.value, session.controller.signal);
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
} else if (destination === 'disk') {
|
||||
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
}
|
||||
revokeDownload();
|
||||
savedToDisk.value = destination === 'disk';
|
||||
session.diagnostics.record(`storage ${destination}`);
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
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() {
|
||||
const session = active;
|
||||
try {
|
||||
await navigator.clipboard.writeText(outputCode.value);
|
||||
if (active !== session) return;
|
||||
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';
|
||||
}
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const index = Math.min(5, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
|
||||
}
|
||||
function selectCode(event: FocusEvent) {
|
||||
if (event.target instanceof HTMLTextAreaElement) event.target.select();
|
||||
}
|
||||
onBeforeUnmount(() => { stopAttempt(); dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="panel">
|
||||
<section v-if="sending || connected" ref="sendSection" class="transfer-section" tabindex="-1" aria-labelledby="send-heading">
|
||||
<h2 id="send-heading" class="step">Send files</h2>
|
||||
<label class="step" for="file-input">{{ connected ? 'Add files to send' : 'Choose files' }}</label>
|
||||
<div class="dropzone" :class="{ dragover }" @dragover.prevent="dragover = true" @dragleave="dragover = false" @drop.prevent="dragover = false; pickFiles($event)">
|
||||
<p>Choose or drop files.</p>
|
||||
<input id="file-input" type="file" multiple @change="pickFiles" />
|
||||
</div>
|
||||
<p v-if="!connected && selectedFiles.length" class="status">{{ selectedFiles.length }} file(s) selected</p>
|
||||
<ul v-if="!connected && selectedFiles.length"><li v-for="(item, index) in selectedFiles" :key="index">{{ item.name }} — {{ formatBytes(item.size) }}</li></ul>
|
||||
<ul v-if="queuedFiles.length" aria-label="Files waiting to send"><li v-for="item in queuedFiles" :key="item.id">{{ item.file.name }} — {{ formatBytes(item.file.size) }} <button @click="removeQueued(item.id)" :aria-label="'Remove ' + item.file.name">Remove</button></li></ul>
|
||||
<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" :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" v-model:discovery="discovery" :disabled="busy || connected" :managed-credentials="managedCredentials" :default-tracker="defaultTracker" />
|
||||
</details>
|
||||
<template v-if="connection.reconnect && !connected">
|
||||
<button class="primary" :disabled="busy" @click="reconnect">Reconnect</button>
|
||||
<p class="status">Both people open {{ connection.name }} and press Reconnect; {{ trackerHost(connection.reconnect.trackers[0]!) }} introduces your browsers. Or exchange codes below.</p>
|
||||
</template>
|
||||
<p v-if="!connected" class="status">Exchange codes privately. They contain your IP address and connection details.</p>
|
||||
<template v-if="!sending">
|
||||
<label class="step" for="offer-input">Paste the sender’s connection code</label>
|
||||
<textarea id="offer-input" v-model="inputCode" :maxlength="MAX_INPUT_LENGTH" :disabled="busy" />
|
||||
</template>
|
||||
<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-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">
|
||||
<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">
|
||||
<h2 class="step">Verify both full SHA-256 fingerprints</h2>
|
||||
<div class="fp-row"><span>Your fingerprint</span><code>{{ fps.local }}</code></div>
|
||||
<div class="fp-row"><span>Their fingerprint</span><code>{{ fps.remote }}</code></div>
|
||||
<p class="status">Compare every byte over an authenticated channel an attacker cannot alter (for example, an in-person comparison). Your fingerprint must match their “Their fingerprint”, and vice versa. If either differs, cancel. Both people must confirm before the filename or contents are sent.</p>
|
||||
<label v-if="pairing"><input v-model="rememberPeer" type="checkbox" :disabled="verified" /> {{ pairing === 'new' ? `Remember this device for ${connection.name}` : `Replace the paired device of ${connection.name}` }}</label>
|
||||
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Verification submitted' : 'Both fingerprints match — confirm' }}</button>
|
||||
</div>
|
||||
<section v-if="connected || incoming || downloadUrl" ref="receiveSection" class="transfer-section" tabindex="-1" aria-labelledby="receive-heading">
|
||||
<h2 id="receive-heading" class="step">Receive files</h2>
|
||||
<p v-if="!incoming" class="status">Waiting for your peer to send a file. You can send files yourself using Send above.</p>
|
||||
<div v-if="incoming && receiveState === 'choose-storage'" class="incoming">
|
||||
<button :disabled="choosing" @click="declineFile">Decline file</button>
|
||||
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
|
||||
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
|
||||
<button v-if="receiveMethod" class="primary" :disabled="choosing" @click="acceptFile">Accept file</button>
|
||||
<p v-if="receiveMethod === 'disk'" class="status">Your browser asks where to save this file. Keep this page open until the transfer finishes.</p>
|
||||
<p v-else-if="receiveMethod" class="status">Your browser downloads this file. Allow the download and keep this page open until the transfer finishes.</p>
|
||||
<p v-else class="error">This browser cannot receive files over 64 MiB. Use a browser with streaming-download or file-system saving support, or send a smaller file.</p>
|
||||
</div>
|
||||
<p v-if="incoming && receiveState !== 'choose-storage'" class="status">Receiving: {{ incoming.name }} — {{ stateLabel(receiveState) }} ({{ receiveProgress }}%)</p>
|
||||
<div v-if="incoming" class="progress" role="progressbar" :aria-valuenow="receiveProgress" aria-valuemin="0" aria-valuemax="100" aria-label="Receiving progress"><div :style="{ width: receiveProgress + '%' }"></div></div>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save again</a></div>
|
||||
</section>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<details v-if="diagnosticLines.length">
|
||||
<summary>Connection diagnostics</summary>
|
||||
<p class="status">Candidate types and check counters only; no addresses, connection codes, credentials or filenames. Missing counters appear as ?. These details remain available after failure.</p>
|
||||
<label class="step" for="connection-diagnostics">Diagnostic log (select and copy)</label>
|
||||
<textarea id="connection-diagnostics" :value="diagnosticLines.join('\n')" readonly rows="12" @focus="selectCode" />
|
||||
</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>
|
||||
</div>
|
||||
<p class="status">Before connecting, Send/Receive chooses who starts. Once connected, use either button to jump between sending and receiving without disconnecting. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
|
||||
</div>
|
||||
</template>
|
||||
+1772
File diff suppressed because it is too large.
Load diff
+1404
File diff suppressed because it is too large.
Load diff
+165
@@ -0,0 +1,165 @@
|
||||
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
|
||||
// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests.
|
||||
// This is the page's half of it. The receiver in src/core.ts only sees startDownload, so it can be
|
||||
// tested against a download in memory, and another way of saving could take this one's place.
|
||||
|
||||
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
|
||||
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
|
||||
// Without either for longer, public/sw.js takes the page for gone and fails the download, see SILENCE.
|
||||
const KEEPALIVE = 10_000;
|
||||
// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its
|
||||
// download manager. Its frame removed before that, the download never shows up, though the worker
|
||||
// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests.
|
||||
const DOWNLOAD_GRACE = 1000;
|
||||
// Of the messages between this page and public/sw.js, which has it too. A page can talk to a worker
|
||||
// of another version: a new page while another tab's download holds the old worker, or an old page
|
||||
// once an update took over. The worker refuses a version it doesn't speak with outdated, each change
|
||||
// to the messages takes a new one, in both files.
|
||||
const VERSION = 1;
|
||||
|
||||
const downloads = registerDownloads();
|
||||
// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window.
|
||||
downloads.catch(() => {});
|
||||
|
||||
// Only the first visit has to wait here, updates are picked up per transfer by holdWorker.
|
||||
async function registerDownloads() {
|
||||
const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' });
|
||||
const pending = registration.installing ?? registration.waiting;
|
||||
if (!registration.active && pending) {
|
||||
await new Promise((resolve) =>
|
||||
pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)),
|
||||
);
|
||||
}
|
||||
if (!registration.active) throw new Error('service worker did not activate');
|
||||
}
|
||||
|
||||
// Awaited before receiving starts, so a browser without service workers fails before connecting.
|
||||
export function downloadsReady() {
|
||||
return downloads.catch((error) => {
|
||||
throw new Error(`downloads unavailable in this browser: ${error instanceof Error ? error.message : error}`);
|
||||
});
|
||||
}
|
||||
|
||||
// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling
|
||||
// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that
|
||||
// worker in the middle of the download.
|
||||
async function holdWorker() {
|
||||
await downloads;
|
||||
const frame = document.createElement('iframe');
|
||||
frame.hidden = true;
|
||||
frame.src = 'download/';
|
||||
document.body.append(frame);
|
||||
await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true }));
|
||||
const worker = frame.contentWindow!.navigator.serviceWorker.controller;
|
||||
if (!worker) {
|
||||
frame.remove();
|
||||
throw new Error('service worker did not take over');
|
||||
}
|
||||
return { frame, worker };
|
||||
}
|
||||
|
||||
// What the download manager does with a download, see startDownload. Each one but read ends it, only
|
||||
// the first of them comes, and none after fail.
|
||||
export type DownloadEvents = {
|
||||
// How many bytes it has read so far, every MiB.
|
||||
read: (bytes: number) => void;
|
||||
// It has read the last byte.
|
||||
finished: () => void;
|
||||
// The user cancelled it.
|
||||
cancelled: () => void;
|
||||
// Something else than fail ended it: no worker, the worker refused it or stopped.
|
||||
failed: (reason: string) => void;
|
||||
};
|
||||
|
||||
// The receiver writes every chunk, then ends it once all arrived, or fails it.
|
||||
export type Download = {
|
||||
write: (chunk: ArrayBuffer) => void;
|
||||
end: () => void;
|
||||
fail: (reason: string) => void;
|
||||
};
|
||||
|
||||
// Starts saving file in the browser's download manager. Writes can come before the worker is held,
|
||||
// they wait for it in order. Once it ended, its frames go and the worker is free for an update.
|
||||
export function startDownload(file: { name: string; size: number }, events: DownloadEvents): Download {
|
||||
const id = crypto.randomUUID();
|
||||
const frames: HTMLIFrameElement[] = [];
|
||||
let keepalive: ReturnType<typeof setInterval> | undefined;
|
||||
// By whatever came first: the worker's answer, its stop or fail.
|
||||
let ended = false;
|
||||
// Chaining every post on this keeps them in order.
|
||||
const worker: Promise<ServiceWorker | undefined> = holdWorker().then(
|
||||
({ frame, worker }) => {
|
||||
frames.push(frame);
|
||||
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
|
||||
// An update takes over only once the frames are released, then this changes nothing. Else
|
||||
// something stopped it in the middle, e.g. clearing the site data, it can't answer then.
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state !== 'redundant') return;
|
||||
if (!ended) events.failed('service worker stopped');
|
||||
ended = true;
|
||||
release();
|
||||
});
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.onmessage = ({ data }) => {
|
||||
if (typeof data === 'number') return ended || events.read(data);
|
||||
if (data === 'ready') {
|
||||
if (ended) return;
|
||||
// A navigation, not fetch(): only navigations hand the response to the download manager.
|
||||
const download = document.createElement('iframe');
|
||||
download.hidden = true;
|
||||
download.src = `download/${id}`;
|
||||
document.body.append(download);
|
||||
frames.push(download);
|
||||
return;
|
||||
}
|
||||
if (!ended) {
|
||||
if (data === 'finished') events.finished();
|
||||
if (data === 'cancelled') events.cancelled();
|
||||
if (data === 'failed') events.failed('the service worker refused it');
|
||||
if (data === 'silent') events.failed('the service worker heard nothing from this page for too long');
|
||||
if (data === 'outdated') {
|
||||
events.failed('this page and its service worker are different versions, reload once no tab receives');
|
||||
}
|
||||
}
|
||||
ended = true;
|
||||
release(data === 'finished');
|
||||
};
|
||||
worker.postMessage({ id, version: VERSION, ...file }, [port2]);
|
||||
return worker;
|
||||
},
|
||||
(error) => {
|
||||
if (!ended) events.failed(String(error));
|
||||
ended = true;
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
const post = (message: object, transfer: Transferable[] = []) =>
|
||||
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
|
||||
|
||||
// Removed earlier, Chromium keeps a failed download running instead of failing it. A finished
|
||||
// download keeps its own frame for DOWNLOAD_GRACE, that one doesn't hold the worker. Only the first
|
||||
// call counts, a later one would take that frame right away.
|
||||
let released = false;
|
||||
function release(finished = false) {
|
||||
if (released) return;
|
||||
released = true;
|
||||
clearInterval(keepalive);
|
||||
const [hold, download] = frames;
|
||||
hold?.remove();
|
||||
if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE);
|
||||
else download?.remove();
|
||||
}
|
||||
|
||||
return {
|
||||
write: (chunk) => post({ chunk }, [chunk]),
|
||||
end: () => post({ done: true }),
|
||||
// The worker answers with failed, only then the frames go. A worker that restarted lost the
|
||||
// download, and its stream with it, it never answers: they go after KEEPALIVE anyway.
|
||||
fail: (reason) => {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
post({ error: reason });
|
||||
void worker.then(() => setTimeout(release, KEEPALIVE));
|
||||
},
|
||||
};
|
||||
}
|
||||
Vendored
-10
@@ -4,13 +4,3 @@ declare module '*.vue' {
|
||||
const component: DefineComponent;
|
||||
export default component;
|
||||
}
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_ICE_ENDPOINT?: string;
|
||||
readonly VITE_STUN_URL?: string;
|
||||
readonly VITE_TRACKER_URL?: string;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<{ createWritable(): Promise<import('./lib/transfer.ts').FileDestination> }>;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
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)).
|
||||
// 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 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.';
|
||||
|
||||
export interface Signal {
|
||||
type: 'offer' | 'answer';
|
||||
// Chosen by the offerer and echoed by the answer, which addresses that offer.
|
||||
ref: string;
|
||||
sdp: string;
|
||||
identity?: IdentityHello;
|
||||
}
|
||||
export interface DecodeOptions extends Pick<IceOptions, 'allowTurn'> { type?: Signal['type']; ref?: string }
|
||||
|
||||
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(/=+$/, '');
|
||||
}
|
||||
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) {
|
||||
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw'));
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer());
|
||||
}
|
||||
// Stops reading once the output exceeds the limit, so a small hostile code
|
||||
// cannot expand without bound.
|
||||
async function inflate(bytes: Uint8Array<ArrayBuffer>) {
|
||||
const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw')).getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.byteLength;
|
||||
if (length > MAX_PAYLOAD) { void reader.cancel().catch(() => {}); throw new Error('Connection code is too large.'); }
|
||||
chunks.push(value);
|
||||
}
|
||||
const output = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.byteLength; }
|
||||
return output;
|
||||
}
|
||||
|
||||
export function createRef() { return toBase64Url(crypto.getRandomValues(new Uint8Array(16))); }
|
||||
|
||||
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)));
|
||||
if (code.length > MAX_CODE_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
|
||||
return code;
|
||||
}
|
||||
|
||||
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 = 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;
|
||||
try { legacy = isRecord(JSON.parse(atob(code))); } catch { /* not an old code either */ }
|
||||
throw new Error(legacy ? 'Both people need the current HellCon version.' : INVALID);
|
||||
}
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await inflate(fromBase64Url(code.slice(CODE_PREFIX.length)))));
|
||||
} catch (err) {
|
||||
if (asError(err).message === 'Connection code is too large.') throw err;
|
||||
throw new Error(INVALID);
|
||||
}
|
||||
if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
|
||||
if ((data.type !== 'offer' && data.type !== 'answer') || typeof data.ref !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(data.ref) || typeof data.sdp !== 'string') {
|
||||
throw new Error(INVALID);
|
||||
}
|
||||
if (data.version === 3 && data.identity !== undefined) throw new Error(INVALID);
|
||||
const identity = data.version === 4 ? parseHello(data.identity) : undefined;
|
||||
validateDescription(data.sdp, options);
|
||||
if (type && data.type !== type) {
|
||||
throw new Error(type === 'answer' ? 'This is a connection code, not an answer. Paste the answer your peer created.' : 'This is an answer, not a connection code. Paste the code the sender created.');
|
||||
}
|
||||
if (ref !== undefined && data.ref !== ref) throw new Error('This answer belongs to a different connection code. Ask your peer to answer your current code.');
|
||||
return { type: data.type, ref: data.ref, sdp: data.sdp, ...(identity ? { identity } : {}) };
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
// Only allowlisted categories and numbers leave this module. Never retain raw
|
||||
// SDP, candidate addresses/IDs, URLs, credentials, filenames or browser errors.
|
||||
const candidateTypes = ['host', 'srflx', 'prflx', 'relay'] as const;
|
||||
const protocols = ['udp', 'tcp'] as const;
|
||||
const pairStates = ['frozen', 'waiting', 'in-progress', 'failed', 'succeeded'] as const;
|
||||
const counters = ['requestsSent', 'requestsReceived', 'responsesSent', 'responsesReceived'] as const;
|
||||
type StatsEntry = Record<string, unknown>;
|
||||
type Stats = Pick<RTCStatsReport, 'forEach' | 'get'>;
|
||||
const category = (value: unknown, allowed: readonly string[]) => typeof value === 'string' && allowed.includes(value) ? value : 'unknown';
|
||||
const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? String(value) : '?';
|
||||
|
||||
export function summarizeCandidates(sdp: string | undefined): string {
|
||||
const counts = { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 };
|
||||
for (const line of sdp?.split(/\r?\n/) ?? []) {
|
||||
if (!line.startsWith('a=candidate:')) continue;
|
||||
const type = category(line.match(/\styp\s+(\S+)/)?.[1], candidateTypes) as keyof typeof counts;
|
||||
counts[type]++;
|
||||
}
|
||||
return Object.entries(counts).map(([type, n]) => `${type}=${n}`).join(' ') +
|
||||
` end=${sdp?.split(/\r?\n/).includes('a=end-of-candidates') ? 'yes' : 'no'}`;
|
||||
}
|
||||
|
||||
export function summarizeStats(stats: Stats): string[] {
|
||||
const pairs: StatsEntry[] = [];
|
||||
const selected = new Set<string>();
|
||||
const candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 } };
|
||||
stats.forEach((entry: StatsEntry) => {
|
||||
if (entry.type === 'transport' && typeof entry.selectedCandidatePairId === 'string') selected.add(entry.selectedCandidatePairId);
|
||||
if (entry.type === 'candidate-pair') pairs.push(entry);
|
||||
const side = entry.type === 'local-candidate' ? 'local' : entry.type === 'remote-candidate' ? 'remote' : null;
|
||||
if (side) candidates[side][category(entry.candidateType, candidateTypes) as keyof typeof candidates.local]++;
|
||||
});
|
||||
const endpoint = (id: unknown) => {
|
||||
const entry = typeof id === 'string' ? stats.get(id) as StatsEntry | undefined : undefined;
|
||||
return `${category(entry?.candidateType, candidateTypes)}/${category(entry?.protocol, protocols)}`;
|
||||
};
|
||||
const lines = (['local', 'remote'] as const).map(side => `${side} stats: ` + Object.entries(candidates[side]).map(([type, n]) => `${type}=${n}`).join(' '));
|
||||
lines.push(`pairs=${pairs.length}`);
|
||||
// Put a selected route first, cap output on machines with many interfaces.
|
||||
const isSelected = (pair: StatsEntry) => typeof pair.id === 'string' && selected.has(pair.id) || pair.selected === true;
|
||||
pairs.sort((a, b) => Number(isSelected(b)) - Number(isSelected(a)));
|
||||
for (const pair of pairs.slice(0, 12)) {
|
||||
lines.push(`pair ${endpoint(pair.localCandidateId)} → ${endpoint(pair.remoteCandidateId)} ${category(pair.state, pairStates)}` +
|
||||
` selected=${isSelected(pair)} nominated=${pair.nominated === true} ` + counters.map(key => `${key}=${count(pair[key])}`).join(' '));
|
||||
}
|
||||
stats.forEach((entry: StatsEntry) => {
|
||||
if (entry.type === 'transport') lines.push(`transport dtls=${category(entry.dtlsState, ['new', 'connecting', 'connected', 'closed', 'failed'])}`);
|
||||
});
|
||||
if (pairs.length > 12) lines.push(`pairs omitted=${pairs.length - 12}`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
export class ConnectionDiagnostics {
|
||||
readonly lines: string[] = [];
|
||||
private readonly started = performance.now();
|
||||
private stopped = false;
|
||||
private sampleTimers: ReturnType<typeof setTimeout>[] = [];
|
||||
private samplingStarted = false;
|
||||
private finishing: Promise<void> | undefined;
|
||||
private readonly listeners: Array<[EventTarget, string, EventListener]> = [];
|
||||
private readonly pc: RTCPeerConnection;
|
||||
private readonly update: (lines: string[]) => void;
|
||||
constructor(pc: RTCPeerConnection, update: (lines: string[]) => void) {
|
||||
this.pc = pc; this.update = update;
|
||||
const listen = (target: EventTarget, event: string, listener: EventListener) => {
|
||||
target.addEventListener(event, listener);
|
||||
this.listeners.push([target, event, listener]);
|
||||
};
|
||||
const state = () => {
|
||||
this.sampleWhileChecking();
|
||||
this.record(`pc=${category(pc.connectionState, ['new', 'connecting', 'connected', 'disconnected', 'failed', 'closed'])} ice=${category(pc.iceConnectionState, ['new', 'checking', 'connected', 'completed', 'disconnected', 'failed', 'closed'])} gathering=${category(pc.iceGatheringState, ['new', 'gathering', 'complete'])}`);
|
||||
};
|
||||
for (const event of ['connectionstatechange', 'iceconnectionstatechange', 'icegatheringstatechange']) listen(pc, event, state);
|
||||
listen(pc, 'icecandidateerror', event => this.record(`ICE server error=${count((event as RTCPeerConnectionIceErrorEvent).errorCode)}`));
|
||||
if (typeof document !== 'undefined') {
|
||||
const visibility = () => this.record(`page=${category(document.visibilityState, ['visible', 'hidden'])}`);
|
||||
listen(document, 'visibilitychange', visibility);
|
||||
visibility();
|
||||
}
|
||||
state();
|
||||
}
|
||||
private sampleWhileChecking() {
|
||||
if (this.stopped || this.finishing) return;
|
||||
if (this.pc.iceConnectionState !== 'checking') {
|
||||
for (const timer of this.sampleTimers) clearTimeout(timer);
|
||||
this.sampleTimers = [];
|
||||
return;
|
||||
}
|
||||
if (this.samplingStarted) return;
|
||||
this.samplingStarted = true;
|
||||
// Preserve evidence before browsers discard failed candidate pairs. Four
|
||||
// bounded snapshots cover short setup failures without polling indefinitely.
|
||||
this.sampleTimers = [3000, 6000, 9000, 12000].map(delay => setTimeout(() => {
|
||||
if (this.stopped || this.finishing || this.pc.iceConnectionState !== 'checking') return;
|
||||
this.record('connectivity sample');
|
||||
void this.capture();
|
||||
}, delay));
|
||||
}
|
||||
record(message: string) {
|
||||
if (this.stopped) return;
|
||||
this.lines.push(`${((performance.now() - this.started) / 1000).toFixed(1)}s ${message}`);
|
||||
this.lines.splice(0, Math.max(0, this.lines.length - 80));
|
||||
this.update([...this.lines]);
|
||||
}
|
||||
descriptions() {
|
||||
this.record(`local code: ${summarizeCandidates(this.pc.localDescription?.sdp)}`);
|
||||
this.record(`remote code: ${summarizeCandidates(this.pc.remoteDescription?.sdp)}`);
|
||||
}
|
||||
async capture() {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const stats = await Promise.race([
|
||||
this.pc.getStats(),
|
||||
new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), 300); }),
|
||||
]);
|
||||
if (stats) for (const line of summarizeStats(stats)) this.record(line);
|
||||
else this.record('stats unavailable: deadline');
|
||||
} catch { this.record('stats unavailable'); }
|
||||
finally { clearTimeout(timer); }
|
||||
}
|
||||
// Request final stats while the connection is alive. Always close, even when
|
||||
// getStats rejects or hangs. Reset can start a new session during this wait.
|
||||
finish(close: () => void) {
|
||||
for (const timer of this.sampleTimers) clearTimeout(timer);
|
||||
this.sampleTimers = [];
|
||||
return this.finishing ??= this.capture().finally(() => {
|
||||
this.stopped = true;
|
||||
for (const [target, event, listener] of this.listeners) target.removeEventListener(event, listener);
|
||||
close();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { parsePairing, type ReconnectPairing } from './reconnect.ts';
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export const CONNECTION_LIMIT = 100;
|
||||
export interface SavedConnection {
|
||||
id: string;
|
||||
number: number;
|
||||
name: string;
|
||||
// The peer this connection trusts. Only set after mutual verification.
|
||||
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 } | { 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.');
|
||||
return name;
|
||||
}
|
||||
export function updateConnection(current: SavedConnection, update: ConnectionUpdate): SavedConnection {
|
||||
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, 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, 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.');
|
||||
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) => {
|
||||
const request = indexedDB.open('hellcon-connections', 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('connections', { keyPath: 'id' });
|
||||
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
||||
request.onerror = () => reject(new Error('Connection storage is unavailable.'));
|
||||
request.onblocked = () => reject(new Error('Close other HellCon tabs to open connection storage.'));
|
||||
});
|
||||
}
|
||||
// Read and write within one transaction so other tabs cannot overwrite a rename
|
||||
// or paired device with a stale copy of the entire record.
|
||||
async function change(action: (records: SavedConnection[], store: IDBObjectStore) => void) {
|
||||
const db = await database();
|
||||
try {
|
||||
return await new Promise<SavedConnection[]>((resolve, reject) => {
|
||||
const tx = db.transaction('connections', 'readwrite'), store = tx.objectStore('connections');
|
||||
let records: SavedConnection[] = [], failure: unknown;
|
||||
const read = store.getAll();
|
||||
read.onsuccess = () => {
|
||||
try {
|
||||
records = read.result.map((raw: unknown) => {
|
||||
const record = validateConnection(raw);
|
||||
// Pre-release 0.0.5 builds saved filenames here. Remove them on the first load.
|
||||
if (isRecord(raw) && 'history' in raw) store.put(record);
|
||||
return record;
|
||||
}).sort((a, b) => a.number - b.number);
|
||||
action(records, store);
|
||||
} catch (error) { failure = error; tx.abort(); }
|
||||
};
|
||||
tx.oncomplete = () => resolve(records);
|
||||
tx.onabort = tx.onerror = () => reject(failure || new Error('Could not save connections.'));
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export function loadConnections() {
|
||||
return change((records, store) => {
|
||||
if (!records.length) { const first = emptyConnection(); store.add(first); records.push(first); }
|
||||
});
|
||||
}
|
||||
export async function addConnection() {
|
||||
const records = await change((records, store) => {
|
||||
if (records.length >= CONNECTION_LIMIT) throw new Error(`Keep up to ${CONNECTION_LIMIT} connections.`);
|
||||
const record = emptyConnection(Math.max(0, ...records.map(item => item.number)) + 1);
|
||||
store.add(record); records.push(record);
|
||||
});
|
||||
return records;
|
||||
}
|
||||
export function saveConnection(id: string, update: ConnectionUpdate) {
|
||||
return change((records, store) => {
|
||||
const index = records.findIndex(item => item.id === id);
|
||||
if (index < 0) throw new Error('This connection is no longer saved. Reload the page.');
|
||||
const record = updateConnection(records[index]!, update);
|
||||
store.put(record); records[index] = record;
|
||||
});
|
||||
}
|
||||
export function removeConnection(id: string) {
|
||||
return change((records, store) => {
|
||||
const index = records.findIndex(item => item.id === id);
|
||||
if (index >= 0) { store.delete(id); records.splice(index, 1); }
|
||||
if (!records.length) { const first = emptyConnection(); store.add(first); records.push(first); }
|
||||
});
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import type { FileDestination, FileMetadata } from './transfer.ts';
|
||||
|
||||
export function supportsStreamingDownload() {
|
||||
if (!['https:', 'http:'].includes(location.protocol) || !isSecureContext ||
|
||||
!navigator.serviceWorker || typeof TransformStream === 'undefined') return false;
|
||||
const channel = new MessageChannel();
|
||||
const stream = new ReadableStream({ start(controller) { controller.close(); } });
|
||||
try { channel.port1.postMessage(stream, [stream]); return true; }
|
||||
catch { return false; }
|
||||
finally { channel.port1.close(); channel.port2.close(); }
|
||||
}
|
||||
|
||||
export async function createDownloadDestination(meta: FileMetadata, signal: AbortSignal): Promise<FileDestination> {
|
||||
if (!supportsStreamingDownload()) throw new Error('Streaming downloads require a supported browser and HTTPS or localhost.');
|
||||
signal.throwIfAborted();
|
||||
const stream = new TransformStream<Uint8Array, Uint8Array>();
|
||||
const writer = stream.writable.getWriter();
|
||||
const channel = new MessageChannel();
|
||||
const frame = document.createElement('iframe');
|
||||
frame.hidden = true; frame.title = 'File download';
|
||||
let finished = false;
|
||||
let stopWatchingWorker = () => {};
|
||||
let resolveReady!: () => void, rejectReady!: (error: Error) => void;
|
||||
let resolveComplete!: () => void, rejectComplete!: (error: Error) => void;
|
||||
const ready = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const complete = new Promise<void>((resolve, reject) => { resolveComplete = resolve; rejectComplete = reject; });
|
||||
void ready.catch(() => {}); void complete.catch(() => {}); void writer.closed.catch(() => {});
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
stopWatchingWorker();
|
||||
signal.removeEventListener('abort', canceled);
|
||||
window.removeEventListener('pagehide', canceled);
|
||||
channel.port1.close(); frame.remove();
|
||||
};
|
||||
const fail = (error: Error) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
channel.port1.postMessage({ type: 'abort' });
|
||||
rejectReady(error); rejectComplete(error);
|
||||
void writer.abort(error).catch(() => {});
|
||||
cleanup();
|
||||
};
|
||||
const canceled = () => fail(new DOMException('Transfer canceled.', 'AbortError'));
|
||||
const timer = setTimeout(() => fail(new Error('Streaming download did not start. Check browser download permissions and try again.')), 30000);
|
||||
signal.addEventListener('abort', canceled, { once: true });
|
||||
window.addEventListener('pagehide', canceled);
|
||||
try {
|
||||
const registration = await Promise.race([
|
||||
navigator.serviceWorker.register(new URL('./download/worker.js', location.href).href),
|
||||
ready.then(() => { throw new Error('Unexpected download state.'); }),
|
||||
]);
|
||||
const worker = registration.active || registration.installing || registration.waiting;
|
||||
if (!worker) throw new Error('Download service worker is unavailable.');
|
||||
if (worker.state !== 'activated') await Promise.race([
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const changed = () => {
|
||||
if (worker.state === 'activated' || worker.state === 'redundant') {
|
||||
worker.removeEventListener('statechange', changed);
|
||||
worker.state === 'activated' ? resolve() : reject(new Error('Download service worker could not activate.'));
|
||||
}
|
||||
};
|
||||
stopWatchingWorker = () => worker.removeEventListener('statechange', changed);
|
||||
worker.addEventListener('statechange', changed); changed();
|
||||
}), ready,
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (finished) await ready;
|
||||
const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
|
||||
const url = new URL(`file-${id}`, registration.scope).href;
|
||||
channel.port1.onmessage = event => {
|
||||
if (event.data?.type === 'ready' && event.data.url === url) {
|
||||
frame.src = url; document.body.append(frame);
|
||||
}
|
||||
if (event.data?.type === 'started') { clearTimeout(timer); resolveReady(); }
|
||||
if (event.data?.type === 'error') fail(new Error(event.data.message || 'Download failed.'));
|
||||
if (event.data?.type === 'complete' && !finished) {
|
||||
finished = true; resolveComplete(); cleanup();
|
||||
}
|
||||
};
|
||||
worker.postMessage({ type: 'download', id, name: meta.name, size: meta.size, stream: stream.readable }, [channel.port2, stream.readable]);
|
||||
await ready;
|
||||
return {
|
||||
async write(data) { await writer.write(new Uint8Array(data)); },
|
||||
async close() { await writer.close(); await complete; },
|
||||
async abort() { canceled(); },
|
||||
};
|
||||
} catch (error) { fail(error instanceof Error ? error : new Error('Could not start download.')); throw error; }
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export interface Identity { publicKey: string; privateKey: CryptoKey }
|
||||
export interface IdentityHello { key: string; nonce: string }
|
||||
export interface IdentityState { revision?: string; identity: Identity | null }
|
||||
export interface IdentityContext { offer: IdentityHello; answer: IdentityHello; offerFingerprint: string; answerFingerprint: string }
|
||||
const curve = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
const signing = { name: 'ECDSA', hash: 'SHA-256' };
|
||||
const bytes = (text: string) => new TextEncoder().encode(text);
|
||||
const hex = (data: ArrayBuffer | Uint8Array) => Array.from(data instanceof Uint8Array ? data : new Uint8Array(data), n => n.toString(16).padStart(2, '0')).join('');
|
||||
function unhex(value: unknown, length: number): Uint8Array<ArrayBuffer> {
|
||||
if (typeof value !== 'string' || value.length !== length * 2 || !/^[0-9a-f]+$/.test(value)) throw new Error('Invalid device identity.');
|
||||
return Uint8Array.from(value.match(/../g)!, n => parseInt(n, 16));
|
||||
}
|
||||
export function parseHello(value: unknown): IdentityHello {
|
||||
if (!isRecord(value)) throw new Error('Invalid device identity.');
|
||||
unhex(value.key, 65); unhex(value.nonce, 32);
|
||||
if (!(value.key as string).startsWith('04')) throw new Error('Invalid device identity.');
|
||||
return { key: value.key as string, nonce: value.nonce as string };
|
||||
}
|
||||
export async function createIdentity(): Promise<Identity> {
|
||||
// Store the private key as a non-extractable CryptoKey. Same-origin JavaScript
|
||||
// can still use it to sign, so the app code must remain trusted.
|
||||
const pair = await crypto.subtle.generateKey(curve, false, ['sign', 'verify']);
|
||||
return { publicKey: hex(await crypto.subtle.exportKey('raw', pair.publicKey)), privateKey: pair.privateKey };
|
||||
}
|
||||
export function hello(identity: Identity): IdentityHello {
|
||||
return { key: identity.publicKey, nonce: hex(crypto.getRandomValues(new Uint8Array(32))) };
|
||||
}
|
||||
function transcript(context: IdentityContext, initiator: boolean) {
|
||||
const offer = parseHello(context.offer), answer = parseHello(context.answer);
|
||||
const fingerprint = /^(?:[0-9A-F]{2} ){31}[0-9A-F]{2}$/;
|
||||
if (!fingerprint.test(context.offerFingerprint) || !fingerprint.test(context.answerFingerprint)) throw new Error('Invalid identity session binding.');
|
||||
return bytes(JSON.stringify(['HellCon device proof', 1, 4, initiator ? 'offerer' : 'answerer', offer.key, offer.nonce, answer.key, answer.nonce, context.offerFingerprint, context.answerFingerprint]));
|
||||
}
|
||||
export async function signIdentity(identity: Identity, context: IdentityContext, initiator: boolean) {
|
||||
if (identity.publicKey !== (initiator ? context.offer : context.answer).key) throw new Error('Device identity changed. Start a new connection.');
|
||||
return hex(await crypto.subtle.sign(signing, identity.privateKey, transcript(context, initiator)));
|
||||
}
|
||||
export async function verifyIdentity(proof: unknown, context: IdentityContext, initiator: boolean) {
|
||||
const key = await crypto.subtle.importKey('raw', unhex((initiator ? context.offer : context.answer).key, 65), curve, false, ['verify']);
|
||||
if (!await crypto.subtle.verify(signing, key, unhex(proof, 64), transcript(context, initiator))) throw new Error('Device proof failed. Disconnect and verify fresh codes.');
|
||||
}
|
||||
|
||||
async function database() {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open('hellcon-devices', 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('settings');
|
||||
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
||||
request.onerror = () => reject(new Error('Device storage is unavailable. Use a temporary connection.'));
|
||||
request.onblocked = () => reject(new Error('Close other HellCon tabs and try again.'));
|
||||
});
|
||||
}
|
||||
export async function loadIdentityState(): Promise<IdentityState> {
|
||||
const db = await database();
|
||||
try {
|
||||
const state = await new Promise<IdentityState | undefined>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readonly');
|
||||
const request = tx.objectStore('settings').get('state');
|
||||
tx.oncomplete = () => resolve(request.result); tx.onabort = tx.onerror = () => reject(new Error('Could not read device storage.'));
|
||||
});
|
||||
if (!state) return { identity: null };
|
||||
if (state.identity) {
|
||||
unhex(state.identity.publicKey, 65);
|
||||
if (!(state.identity.privateKey instanceof CryptoKey) || state.identity.privateKey.type !== 'private') throw new Error('Stored identity is invalid. Clear device storage and create a new identity.');
|
||||
}
|
||||
return { revision: state.revision, identity: state.identity ?? null };
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function saveIdentityState(state: IdentityState, expectedRevision = state.revision): Promise<IdentityState> {
|
||||
const db = await database();
|
||||
const next = { ...state, revision: crypto.randomUUID() };
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite');
|
||||
const store = tx.objectStore('settings');
|
||||
const current = store.get('state');
|
||||
let conflict = false;
|
||||
current.onsuccess = () => {
|
||||
if (current.result?.revision !== expectedRevision) { conflict = true; tx.abort(); }
|
||||
else store.put(next, 'state');
|
||||
};
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onabort = tx.onerror = () => reject(new Error(conflict ? 'Device settings changed in another tab. Reload before editing them.' : 'Could not save device storage. Use a temporary connection.'));
|
||||
});
|
||||
return next;
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function clearIdentityStorage() {
|
||||
const db = await database();
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite');
|
||||
tx.objectStore('settings').delete('state');
|
||||
tx.oncomplete = () => resolve(); tx.onabort = tx.onerror = () => reject(new Error('Could not clear device storage.'));
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
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; }
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
import { Transfer, validateMetadata, type TransferChannel, type FileDestination, type FileMetadata, type TransferState, type TransferResult } from './transfer.ts';
|
||||
import { CHUNK_SIZE } from './webrtc.ts';
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
|
||||
export const QUEUE_LIMIT = 32;
|
||||
export interface QueueItem { id: number; file: File }
|
||||
export interface SessionCallbacks {
|
||||
onReady(): void;
|
||||
onQueue(items: QueueItem[]): void;
|
||||
onState(direction: 'send' | 'receive', state: TransferState, meta: FileMetadata): void;
|
||||
onProgress(direction: 'send' | 'receive', bytes: number, size: number): void;
|
||||
onComplete(direction: 'send' | 'receive', result: TransferResult): void;
|
||||
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 }
|
||||
|
||||
// One sequential queue per direction. At most two active transfers share the
|
||||
// transport, with separate bounded Transfer windows and unique session IDs.
|
||||
export class FileSession {
|
||||
private pending: QueueItem[] = [];
|
||||
private outgoing: Active | null = null;
|
||||
private incoming: Active | null = null;
|
||||
private nextId: number;
|
||||
private lastRemoteId = 0;
|
||||
private verified = false;
|
||||
private peerReady = false;
|
||||
private readySent = false;
|
||||
private started = false;
|
||||
private closed = false;
|
||||
private timer: ReturnType<typeof setTimeout>;
|
||||
private authentication?: SessionAuthentication;
|
||||
private proofSent = false;
|
||||
private incomingBytes = 0;
|
||||
private processing = Promise.resolve();
|
||||
private readonly dc: TransferChannel;
|
||||
private readonly initiator: boolean;
|
||||
private readonly callbacks: SessionCallbacks;
|
||||
constructor(dc: TransferChannel, initiator: boolean, callbacks: SessionCallbacks) {
|
||||
this.dc = dc; this.initiator = initiator; this.callbacks = callbacks;
|
||||
this.nextId = initiator ? 1 : 2;
|
||||
dc.binaryType = 'arraybuffer';
|
||||
dc.onopen = () => this.ready();
|
||||
dc.onmessage = event => {
|
||||
if (this.closed) return;
|
||||
const data: unknown = event.data;
|
||||
if (!this.verified) {
|
||||
try {
|
||||
if (typeof data !== 'string' || data.length > 4096 || JSON.parse(data)?.type !== 'ready') throw new Error('File data arrived before verification.');
|
||||
} catch (error) { this.fail(error); return; }
|
||||
}
|
||||
const size = typeof data === 'string' ? data.length * 2 : data instanceof ArrayBuffer ? data.byteLength : 0;
|
||||
this.incomingBytes += size;
|
||||
if (!size || this.incomingBytes > 2 * 1024 * 1024) { this.fail(new Error('Session receive queue exceeded.')); return; }
|
||||
this.processing = this.processing.then(() => this.message(data)).catch(error => this.fail(error)).finally(() => { this.incomingBytes -= size; });
|
||||
};
|
||||
dc.onclose = () => this.outgoing || this.incoming ? this.fail(new Error('Connection closed. Unfinished files were cancelled.')) : this.close();
|
||||
dc.onerror = () => this.fail(new Error('Connection failed. Exchange fresh codes.'));
|
||||
this.timer = setTimeout(() => this.fail(new Error('Verification timed out.')), 5 * 60 * 1000);
|
||||
}
|
||||
private control(data: object) { this.dc.send(JSON.stringify({ v: 3, ...data })); }
|
||||
authenticate(authentication: SessionAuthentication) {
|
||||
if (this.readySent || this.closed) throw new Error('Identity setup is too late.');
|
||||
this.authentication = authentication;
|
||||
}
|
||||
verify() { this.verified = true; this.ready(); }
|
||||
private ready() { void this.sendReady().catch(error => this.fail(error)); }
|
||||
private async sendReady() {
|
||||
if (this.closed || !this.verified || this.dc.readyState !== 'open') return;
|
||||
try {
|
||||
if (!this.readySent) {
|
||||
this.readySent = true;
|
||||
const proof = await this.authentication?.sign();
|
||||
if (this.closed) return;
|
||||
this.control({ type: 'ready', ...(proof ? { proof } : {}) });
|
||||
this.proofSent = true;
|
||||
}
|
||||
if (!this.proofSent) return;
|
||||
if (this.peerReady && !this.started) {
|
||||
this.started = true; clearTimeout(this.timer); this.callbacks.onReady(); this.pump();
|
||||
}
|
||||
} catch (error) { this.fail(error); }
|
||||
}
|
||||
add(files: File[]) {
|
||||
if (this.closed) throw new Error('Connection ended.');
|
||||
if (files.length + this.pending.length + (this.outgoing ? 1 : 0) > QUEUE_LIMIT) throw new Error(`Queue up to ${QUEUE_LIMIT} files at a time.`);
|
||||
for (const file of files) validateMetadata({ name: file.name, size: file.size, mime: file.type || '' });
|
||||
if (this.nextId + files.length * 2 > 0xffffffff) throw new Error('Start a new session.');
|
||||
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.');
|
||||
this.incoming.transfer.accept(destination);
|
||||
}
|
||||
decline() {
|
||||
const item = this.incoming;
|
||||
if (!item || item.transfer.state !== 'choose-storage') return;
|
||||
this.control({ type: 'decline', id: item.id });
|
||||
this.incoming = null; item.transfer.close(); this.callbacks.onDecline('receive', item.meta);
|
||||
}
|
||||
private pump() {
|
||||
if (!this.started || this.closed || this.outgoing || !this.pending.length) return;
|
||||
const item = this.pending.shift()!;
|
||||
this.callbacks.onQueue([...this.pending]);
|
||||
const meta = validateMetadata({ name: item.file.name, size: item.file.size, mime: item.file.type || '' });
|
||||
this.control({ type: 'start', id: item.id });
|
||||
this.outgoing = this.create(item.id, item.file, meta);
|
||||
this.outgoing.transfer.verify();
|
||||
}
|
||||
private create(id: number, file: File | null, meta: FileMetadata): Active {
|
||||
const raw = this.dc;
|
||||
const channel = new EventTarget() as TransferChannel;
|
||||
channel.binaryType = 'arraybuffer'; channel.bufferedAmountLowThreshold = 0;
|
||||
channel.onopen = channel.onmessage = channel.onclose = channel.onerror = null;
|
||||
let ended = false;
|
||||
Object.defineProperties(channel, {
|
||||
readyState: { get: () => ended ? 'closed' : raw.readyState },
|
||||
bufferedAmount: { get: () => raw.bufferedAmount },
|
||||
bufferedAmountLowThreshold: { get: () => raw.bufferedAmountLowThreshold, set: value => { raw.bufferedAmountLowThreshold = value; } },
|
||||
});
|
||||
const drain = () => channel.dispatchEvent(new Event('bufferedamountlow'));
|
||||
const close = () => channel.dispatchEvent(new Event('close'));
|
||||
raw.addEventListener('bufferedamountlow', drain);
|
||||
raw.addEventListener('close', close);
|
||||
channel.close = () => { ended = true; raw.removeEventListener('bufferedamountlow', drain); raw.removeEventListener('close', close); channel.dispatchEvent(new Event('close')); };
|
||||
channel.send = data => {
|
||||
if (ended || this.closed) throw new Error('Connection ended.');
|
||||
if (typeof data === 'string') this.control({ type: 'frame', id, data });
|
||||
else {
|
||||
const packet = new Uint8Array(data.byteLength + 4);
|
||||
new DataView(packet.buffer).setUint32(0, id);
|
||||
packet.set(new Uint8Array(data), 4); raw.send(packet.buffer);
|
||||
}
|
||||
};
|
||||
const direction = file ? 'send' : 'receive';
|
||||
const item: Active = { id, meta, transfer: new Transfer(channel, {
|
||||
file,
|
||||
onState: state => this.callbacks.onState(direction, state, item.meta),
|
||||
onMeta: metadata => { item.meta = metadata; this.callbacks.onState(direction, 'choose-storage', metadata); },
|
||||
onProgress: (bytes, size) => this.callbacks.onProgress(direction, bytes, size),
|
||||
onComplete: result => {
|
||||
if (this.closed) return;
|
||||
if (direction === 'send') this.outgoing = null; else this.incoming = null;
|
||||
item.transfer.close(); this.callbacks.onComplete(direction, result);
|
||||
queueMicrotask(() => { try { this.pump(); } catch (error) { this.fail(error); } });
|
||||
},
|
||||
onError: error => this.fail(error),
|
||||
}) };
|
||||
return item;
|
||||
}
|
||||
private async message(data: unknown) {
|
||||
if (this.closed) return;
|
||||
if (data instanceof ArrayBuffer) {
|
||||
if (!this.started || data.byteLength <= 4 || data.byteLength > CHUNK_SIZE + 4) throw new Error('Invalid file packet.');
|
||||
const id = new DataView(data).getUint32(0);
|
||||
if (!this.incoming || this.incoming.id !== id) throw new Error('Unexpected file ID.');
|
||||
this.incoming.transfer.enqueue(data.slice(4)); return;
|
||||
}
|
||||
if (typeof data !== 'string' || data.length > 4096) throw new Error('Invalid session message.');
|
||||
const msg: unknown = JSON.parse(data);
|
||||
if (!isRecord(msg) || msg.v !== 3) throw new Error('Unsupported session protocol.');
|
||||
if (msg.type === 'ready' && !this.peerReady) {
|
||||
if (this.authentication) await this.authentication.verify(msg.proof);
|
||||
else if (msg.proof !== undefined) throw new Error('Unexpected device proof.');
|
||||
if (this.closed) return;
|
||||
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.');
|
||||
this.lastRemoteId = msg.id;
|
||||
this.incoming = this.create(msg.id, null, { name: '', size: 0, mime: '' });
|
||||
this.incoming.transfer.verify(); return;
|
||||
}
|
||||
if (msg.type === 'decline') {
|
||||
const item = this.outgoing;
|
||||
if (!item || item.id !== msg.id || item.transfer.state !== 'waiting-accept') throw new Error('Unexpected decline.');
|
||||
this.outgoing = null; item.transfer.close(); this.callbacks.onDecline('send', item.meta); this.pump(); return;
|
||||
}
|
||||
if (msg.type === 'frame' && typeof msg.data === 'string') {
|
||||
const item = [this.incoming, this.outgoing].find(item => item?.id === msg.id);
|
||||
if (!item) throw new Error('Unexpected file ID.');
|
||||
item.transfer.enqueue(msg.data); return;
|
||||
}
|
||||
throw new Error('Unexpected session message.');
|
||||
}
|
||||
private fail(error: unknown) { if (!this.closed) { this.callbacks.onError(asError(error)); this.close(); } }
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer);
|
||||
this.outgoing?.transfer.close(); this.incoming?.transfer.close(); this.pending = [];
|
||||
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
|
||||
this.dc.close(); this.callbacks.onQueue([]); this.callbacks.onClose();
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
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,270 +0,0 @@
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
import type { BufferedChannel } from './webrtc.ts';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.ts';
|
||||
|
||||
export interface FileMetadata { name: string; size: number; mime: string }
|
||||
export type TransferState = 'verification' | 'waiting-accept' | 'choose-storage' | 'sending' |
|
||||
'receiving' | 'saving' | 'awaiting-receipt' | 'done' | 'closed';
|
||||
export interface TransferResult { blob?: Blob | null; meta: FileMetadata }
|
||||
export interface FileDestination {
|
||||
write(data: ArrayBuffer): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
abort(): Promise<void>;
|
||||
}
|
||||
export interface TransferChannel extends BufferedChannel {
|
||||
binaryType: BinaryType;
|
||||
onopen: ((event: Event) => void) | null;
|
||||
onmessage: ((event: MessageEvent<unknown>) => void) | null;
|
||||
onclose: ((event: Event) => void) | null;
|
||||
onerror: ((event: RTCErrorEvent) => void) | null;
|
||||
send(data: string | ArrayBuffer): void;
|
||||
close(): void;
|
||||
}
|
||||
export interface TransferOptions {
|
||||
file?: File | null;
|
||||
onState?: (state: TransferState) => void;
|
||||
onMeta?: (meta: FileMetadata) => void;
|
||||
onProgress?: (bytes: number, size: number) => void;
|
||||
onComplete?: (result: TransferResult) => void;
|
||||
onError?: (error: Error) => void;
|
||||
onClose?: () => void;
|
||||
timeout?: number;
|
||||
}
|
||||
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
|
||||
|
||||
export const MEMORY_LIMIT = 64 * 1024 * 1024;
|
||||
const CONTROL_LIMIT = 2048;
|
||||
const WINDOW = MAX_BUFFERED;
|
||||
|
||||
export function validateMetadata(meta: unknown): FileMetadata {
|
||||
if (!isRecord(meta) || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
|
||||
/[\x00-\x1f\x7f/\\\u202a-\u202e\u2066-\u2069]/.test(meta.name) ||
|
||||
typeof meta.size !== 'number' || !Number.isSafeInteger(meta.size) || meta.size < 0 ||
|
||||
typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) {
|
||||
throw new Error('Invalid file metadata. File size must be a nonnegative safe integer.');
|
||||
}
|
||||
return { name: meta.name, size: meta.size, mime: meta.mime };
|
||||
}
|
||||
|
||||
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
|
||||
export class Transfer {
|
||||
readonly dc: TransferChannel;
|
||||
file: File | null;
|
||||
readonly sending: boolean;
|
||||
peerSupportsRepeat = false;
|
||||
readonly onClose: () => void;
|
||||
readonly onState: NonNullable<TransferOptions['onState']>;
|
||||
readonly onMeta: NonNullable<TransferOptions['onMeta']>;
|
||||
readonly onProgress: NonNullable<TransferOptions['onProgress']>;
|
||||
readonly onComplete: NonNullable<TransferOptions['onComplete']>;
|
||||
readonly onError: NonNullable<TransferOptions['onError']>;
|
||||
readonly timeout: number;
|
||||
state: TransferState;
|
||||
verified: boolean;
|
||||
peerReady: boolean;
|
||||
readySent: boolean;
|
||||
closed: boolean;
|
||||
received: number;
|
||||
sent: number;
|
||||
acked: number;
|
||||
queued: number;
|
||||
messages: number;
|
||||
chunks: ArrayBuffer[];
|
||||
queue: Promise<void>;
|
||||
readonly controller: AbortController;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private meta: FileMetadata | null = null;
|
||||
private writable: FileDestination | null = null;
|
||||
private wake: (() => void) | null = null;
|
||||
|
||||
private get metadata(): FileMetadata {
|
||||
if (!this.meta) throw new Error('Missing file metadata.');
|
||||
return this.meta;
|
||||
}
|
||||
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, onClose = () => {}, timeout = 60000 }: TransferOptions = {}) {
|
||||
this.dc = dc;
|
||||
this.file = file;
|
||||
this.sending = !!file;
|
||||
this.onClose = onClose;
|
||||
this.onState = onState;
|
||||
this.onMeta = onMeta;
|
||||
this.onProgress = onProgress;
|
||||
this.onComplete = onComplete;
|
||||
this.onError = onError;
|
||||
this.timeout = timeout;
|
||||
this.state = 'verification';
|
||||
this.verified = false;
|
||||
this.peerReady = false;
|
||||
this.readySent = false;
|
||||
this.closed = false;
|
||||
this.received = this.sent = this.acked = this.queued = this.messages = 0;
|
||||
this.chunks = [];
|
||||
this.queue = Promise.resolve();
|
||||
this.controller = new AbortController();
|
||||
dc.binaryType = 'arraybuffer';
|
||||
dc.onopen = () => this.guard(() => this.ready());
|
||||
dc.onmessage = e => this.enqueue(e.data);
|
||||
const transportEnded = (message: string) => {
|
||||
// Firefox can report an SCTP error when the sender closes its peer
|
||||
// connection after receiving our completion ACK. The saved file remains
|
||||
// valid; a transport shutdown must not revoke a completed download.
|
||||
if (this.state === 'done') this.close();
|
||||
else this.fail(new Error(message));
|
||||
};
|
||||
dc.onclose = () => transportEnded('Connection closed before receipt was confirmed.');
|
||||
dc.onerror = () => transportEnded('Data channel failed.');
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
setState(state: TransferState) { this.state = state; this.onState(state); }
|
||||
touch(ms = this.timeout) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
|
||||
}
|
||||
guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } }
|
||||
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number; repeat?: boolean } = {}) {
|
||||
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
|
||||
const text = JSON.stringify({ v: 2, type, ...data });
|
||||
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
|
||||
this.dc.send(text);
|
||||
}
|
||||
verify() {
|
||||
if (this.closed || this.verified) return;
|
||||
this.verified = true;
|
||||
this.guard(() => this.ready());
|
||||
}
|
||||
ready() {
|
||||
if (!this.verified || this.dc.readyState !== 'open' || this.closed) return;
|
||||
if (!this.readySent) { this.control('ready', { repeat: true }); this.readySent = true; }
|
||||
if (this.file && this.peerReady && this.state === 'verification') {
|
||||
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
|
||||
this.setState('waiting-accept');
|
||||
this.control('meta', this.metadata);
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
enqueue(data: unknown) {
|
||||
if (this.closed) return;
|
||||
const binary = data instanceof ArrayBuffer;
|
||||
const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity;
|
||||
if (size > (binary ? CHUNK_SIZE : CONTROL_LIMIT) || this.queued + size > WINDOW * 2 || this.messages >= 128) {
|
||||
this.fail(new Error('Peer exceeded message or buffering limits.')); return;
|
||||
}
|
||||
this.queued += size; this.messages++;
|
||||
this.queue = this.queue.then(async () => {
|
||||
if (!this.closed) await this.message(data);
|
||||
}).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; });
|
||||
}
|
||||
async message(data: unknown) {
|
||||
if (data instanceof ArrayBuffer) {
|
||||
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.metadata.size) throw new Error('Unexpected or excess file data.');
|
||||
// Bound per-chunk overhead as well as payload bytes: millions of tiny
|
||||
// ArrayBuffers would otherwise defeat the in-memory size limit.
|
||||
if (data.byteLength !== Math.min(CHUNK_SIZE, this.metadata.size - this.received)) throw new Error('Invalid file chunk size.');
|
||||
if (this.writable) await this.writable.write(data);
|
||||
else this.chunks.push(data);
|
||||
if (this.closed) return;
|
||||
this.received += data.byteLength;
|
||||
this.control('ack', { bytes: this.received });
|
||||
this.onProgress(this.received, this.metadata.size);
|
||||
this.touch();
|
||||
return;
|
||||
}
|
||||
if (typeof data !== 'string') throw new Error('Unsupported transfer message.');
|
||||
const msg: unknown = JSON.parse(data);
|
||||
if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
|
||||
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
|
||||
this.peerSupportsRepeat = msg.repeat === true;
|
||||
this.peerReady = true; this.ready(); return;
|
||||
}
|
||||
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
|
||||
if (msg.type === 'meta' && !this.sending && (this.state === 'verification' || (this.state === 'done' && this.peerSupportsRepeat))) {
|
||||
const meta = validateMetadata(msg);
|
||||
this.resetFile();
|
||||
this.meta = meta;
|
||||
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
|
||||
}
|
||||
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
|
||||
this.setState('sending'); this.touch();
|
||||
void this.sendFile().catch(err => this.fail(err)); return;
|
||||
}
|
||||
if (msg.type === 'ack' && this.file && ['sending', 'awaiting-receipt'].includes(this.state)) {
|
||||
if (typeof msg.bytes !== 'number' || !Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
|
||||
(msg.bytes !== this.file.size && msg.bytes % CHUNK_SIZE !== 0)) throw new Error('Invalid receipt count.');
|
||||
this.acked = msg.bytes; this.onProgress(this.acked, this.file.size); this.wake?.(); this.touch(); return;
|
||||
}
|
||||
if (msg.type === 'end' && !this.file && this.state === 'receiving') {
|
||||
if (this.received !== this.metadata.size) throw new Error('Incomplete file.');
|
||||
this.setState('saving');
|
||||
if (this.writable) await this.writable.close();
|
||||
if (this.closed) return;
|
||||
// Treat downloads as opaque files, regardless of the sender's MIME claim.
|
||||
const blob = this.writable ? null : new Blob(this.chunks, { type: 'application/octet-stream' });
|
||||
this.chunks = [];
|
||||
this.writable = null;
|
||||
this.control('complete', { bytes: this.received });
|
||||
this.setState('done'); clearTimeout(this.timer);
|
||||
this.onComplete({ blob, meta: this.metadata }); return;
|
||||
}
|
||||
if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) {
|
||||
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata });
|
||||
if (!this.peerSupportsRepeat) this.close();
|
||||
return;
|
||||
}
|
||||
throw new Error('Unexpected transfer message.');
|
||||
}
|
||||
get canSendAnother() {
|
||||
return this.sending && this.state === 'done' && !this.closed && this.peerSupportsRepeat && this.dc.readyState === 'open';
|
||||
}
|
||||
private resetFile() {
|
||||
this.received = this.sent = this.acked = 0;
|
||||
this.chunks = [];
|
||||
this.writable = null;
|
||||
this.meta = null;
|
||||
}
|
||||
sendAnother(file: File) {
|
||||
if (!this.canSendAnother) throw new Error('Start a new connection to send another file.');
|
||||
const meta = validateMetadata({ name: file.name, size: file.size, mime: file.type || '' });
|
||||
this.resetFile();
|
||||
this.file = file;
|
||||
this.meta = meta;
|
||||
this.setState('waiting-accept');
|
||||
this.guard(() => { this.control('meta', meta); this.touch(5 * 60 * 1000); });
|
||||
}
|
||||
accept(writable: FileDestination | null = null) {
|
||||
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
|
||||
if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
|
||||
this.writable = writable;
|
||||
this.setState('receiving'); this.touch();
|
||||
this.guard(() => this.control('accept'));
|
||||
}
|
||||
async sendFile() {
|
||||
const file = this.file;
|
||||
if (!file) throw new Error('No file selected.');
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
if (this.sent - this.acked >= WINDOW) await new Promise<void>(resolve => { this.wake = resolve; });
|
||||
this.wake = null;
|
||||
if (this.closed) return;
|
||||
if (this.dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(this.dc, { signal: this.controller.signal, timeout: this.timeout });
|
||||
const buffer = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
if (this.closed) return;
|
||||
this.sent += buffer.byteLength;
|
||||
this.dc.send(buffer);
|
||||
}
|
||||
if (this.closed) return;
|
||||
this.setState('awaiting-receipt'); this.control('end'); this.touch();
|
||||
}
|
||||
fail(err: unknown) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.setState('closed'); this.onError(asError(err));
|
||||
}
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer); this.controller.abort(); this.wake?.(); this.wake = null;
|
||||
this.chunks = [];
|
||||
const writable = this.writable;
|
||||
if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {});
|
||||
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
|
||||
this.dc.close();
|
||||
this.onClose();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === 'string');
|
||||
}
|
||||
|
||||
export function asError(value: unknown, fallback = 'Connection failed.'): Error {
|
||||
return value instanceof Error ? value : new Error(fallback);
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import { isRecord, isStringArray } from './validation.ts';
|
||||
|
||||
export interface IceOptions {
|
||||
stunUrl?: string | null;
|
||||
allowTurn?: boolean;
|
||||
managedTurn?: boolean;
|
||||
turnUrl?: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
export interface NetworkSettings {
|
||||
stunChoice: 'pagequit' | 'google' | 'cloudflare' | 'none' | 'custom';
|
||||
customStun: string;
|
||||
allowTurn: boolean;
|
||||
managedTurn: boolean;
|
||||
turnUrl: string;
|
||||
username: string;
|
||||
credential: string;
|
||||
}
|
||||
|
||||
export interface WaitOptions { signal?: AbortSignal; timeout?: number }
|
||||
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
|
||||
export interface Fingerprints { local: string; remote: string }
|
||||
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
|
||||
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
|
||||
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
|
||||
|
||||
// Manual signaling; codes.ts encodes the validated descriptions for exchange.
|
||||
export const CHUNK_SIZE = 16 * 1024;
|
||||
export const MAX_BUFFERED = 1024 * 1024;
|
||||
export const MAX_SIGNAL_LENGTH = 64 * 1024;
|
||||
export const STUN_PROVIDERS = [
|
||||
{ id: 'pagequit', label: 'PageQuit', url: 'stun:stun.pagequit.net:3478' },
|
||||
{ id: 'google', label: 'Google', url: 'stun:stun.l.google.com:19302' },
|
||||
{ id: 'cloudflare', label: 'Cloudflare', url: 'stun:stun.cloudflare.com:3478' },
|
||||
{ id: 'none', label: 'None (direct connections only)', url: null },
|
||||
];
|
||||
|
||||
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' }: IceOptions = {}): { iceServers: RTCIceServer[] } {
|
||||
const iceServers: RTCIceServer[] = [];
|
||||
if (stunUrl) {
|
||||
if (!/^stuns?:[^\s/?#@]+$/i.test(stunUrl)) throw new Error('Enter a stun: or stuns: server address.');
|
||||
iceServers.push({ urls: stunUrl });
|
||||
}
|
||||
// Credentials and URLs are ignored unless this user explicitly opts in.
|
||||
if (allowTurn) {
|
||||
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
|
||||
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
|
||||
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
||||
}
|
||||
iceServers.push({ urls: turnUrl, username, credential });
|
||||
}
|
||||
return { iceServers };
|
||||
}
|
||||
|
||||
export async function fetchTurnOptions(options: IceOptions, endpoint: string, { signal, fetchImpl = fetch }: { signal?: AbortSignal; fetchImpl?: CredentialFetch } = {}): Promise<IceOptions> {
|
||||
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
|
||||
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
|
||||
const data: unknown = await response.json();
|
||||
if (!isRecord(data) || typeof data.expiresAt !== 'number' || !Number.isFinite(data.expiresAt) ||
|
||||
data.expiresAt <= Date.now() / 1000 + 30 || !Array.isArray(data.iceServers)) {
|
||||
throw new Error('Missing or expired TURN credentials.');
|
||||
}
|
||||
const turn: unknown = data.iceServers.find((server: unknown) => {
|
||||
if (!isRecord(server)) return false;
|
||||
const urls: unknown[] = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.length > 0 && urls.every(url => typeof url === 'string' && /^turns?:/i.test(url));
|
||||
});
|
||||
if (!isRecord(turn) || typeof turn.username !== 'string' || typeof turn.credential !== 'string' ||
|
||||
!(typeof turn.urls === 'string' || isStringArray(turn.urls))) {
|
||||
throw new Error('Missing or invalid TURN credentials.');
|
||||
}
|
||||
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
|
||||
iceConfiguration(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createPeerConnection(options: IceOptions) {
|
||||
return new RTCPeerConnection(iceConfiguration(options));
|
||||
}
|
||||
|
||||
export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
pc.removeEventListener('icegatheringstatechange', check);
|
||||
pc.removeEventListener('connectionstatechange', check);
|
||||
signal?.removeEventListener('abort', aborted);
|
||||
};
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const aborted = () => finish(new Error('Connection cancelled.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || pc.connectionState === 'closed') aborted();
|
||||
else if (pc.iceGatheringState === 'complete') finish();
|
||||
};
|
||||
pc.addEventListener('icegatheringstatechange', check);
|
||||
pc.addEventListener('connectionstatechange', check);
|
||||
signal?.addEventListener('abort', aborted, { once: true });
|
||||
timer = setTimeout(() => finish(new Error('Connection gathering timed out. Check the server settings and try again.')), timeout);
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
const lines = sdp.split(/\r?\n/);
|
||||
const media = lines.filter(line => line.startsWith('m='));
|
||||
if (media.length !== 1 || !/^m=application \d+ (?:UDP\/DTLS\/SCTP|DTLS\/SCTP) (?:webrtc-datachannel|\d+)$/.test(media[0])) {
|
||||
throw new Error('Only a single file data channel is supported.');
|
||||
}
|
||||
// Deliberately reject ambiguous fingerprints rather than guessing SDP scope.
|
||||
const fingerprints = lines.filter(line => line.startsWith('a=fingerprint:'));
|
||||
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 && 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(':', ' ');
|
||||
}
|
||||
|
||||
export function getFingerprints(pc: { localDescription: { sdp: string } | null; remoteDescription: { sdp: string } | null }, options?: Pick<IceOptions, 'allowTurn'>): Fingerprints {
|
||||
return {
|
||||
local: validateDescription(pc.localDescription?.sdp, options),
|
||||
remote: validateDescription(pc.remoteDescription?.sdp, options),
|
||||
};
|
||||
}
|
||||
|
||||
// Each step validates the description it produces or applies.
|
||||
export async function createOffer(pc: RTCPeerConnection, options: SignalOptions = {}) {
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return pc.localDescription.sdp;
|
||||
}
|
||||
|
||||
export async function createAnswer(pc: RTCPeerConnection, offer: string, options: SignalOptions = {}) {
|
||||
validateDescription(offer, options);
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: offer });
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return pc.localDescription.sdp;
|
||||
}
|
||||
|
||||
export function acceptAnswer(pc: RTCPeerConnection, answer: string, options?: SignalOptions) {
|
||||
validateDescription(answer, options);
|
||||
return pc.setRemoteDescription({ type: 'answer', sdp: answer });
|
||||
}
|
||||
|
||||
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
dc.removeEventListener('bufferedamountlow', check);
|
||||
dc.removeEventListener('close', check);
|
||||
dc.removeEventListener('error', failed);
|
||||
signal?.removeEventListener('abort', failed);
|
||||
};
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const failed = () => finish(new Error('Transfer interrupted.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || dc.readyState !== 'open') failed();
|
||||
else if (dc.bufferedAmount <= MAX_BUFFERED / 2) finish();
|
||||
};
|
||||
dc.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
dc.addEventListener('bufferedamountlow', check);
|
||||
dc.addEventListener('close', check);
|
||||
dc.addEventListener('error', failed);
|
||||
signal?.addEventListener('abort', failed, { once: true });
|
||||
timer = setTimeout(() => finish(new Error('Transfer stalled.')), timeout);
|
||||
check();
|
||||
});
|
||||
}
|
||||
+619
-290
@@ -1,369 +1,698 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0f1117;
|
||||
--panel: #181b24;
|
||||
--border: #2a2f3d;
|
||||
--accent: #ff9b3d;
|
||||
--accent-soft: rgba(255, 155, 61, 0.15);
|
||||
--text: #e8eaf0;
|
||||
--muted: #a0a7b8;
|
||||
--space-sm: 0.6rem;
|
||||
--space-md: 0.9rem;
|
||||
--space-lg: 1.25rem;
|
||||
--space-xl: 1.5rem;
|
||||
--space-2xl: 2rem;
|
||||
}
|
||||
|
||||
* {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
*:not(dialog) {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
}
|
||||
|
||||
#app { height: 100dvh; min-height: 420px; }
|
||||
|
||||
.skip-link {
|
||||
position: absolute;
|
||||
left: 0.9rem;
|
||||
top: 0.5rem;
|
||||
transform: translateY(-200%);
|
||||
z-index: 10;
|
||||
padding: 0.55rem 0.8rem;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
html {
|
||||
interpolate-size: allow-keywords;
|
||||
}
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
transform: none;
|
||||
body {
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.panel {
|
||||
width: 100%;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: var(--space-lg);
|
||||
img,
|
||||
picture,
|
||||
video,
|
||||
canvas,
|
||||
svg {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
input,
|
||||
button,
|
||||
textarea,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
p,
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
p {
|
||||
text-wrap: pretty;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
#app {
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
font-family: system-ui, sans-serif;
|
||||
|
||||
--color-primary: #5865f2;
|
||||
--color-primary-hover: #4752c4;
|
||||
--color-on-primary: #fff;
|
||||
--color-secondary: #eb459e;
|
||||
/* The secondary is too dark for text on the surfaces, this one keeps 4.5:1 */
|
||||
--color-secondary-text: #f278b7;
|
||||
--color-success: #23a559;
|
||||
|
||||
--color-bg: #313338;
|
||||
--color-surface: #2b2d31;
|
||||
--color-input: #1e1f22;
|
||||
--color-border: #3f4147;
|
||||
--color-text: #dbdee1;
|
||||
--color-text-muted: #949ba4;
|
||||
|
||||
--space-1: 0.25rem;
|
||||
--space-2: 0.5rem;
|
||||
--space-3: 0.75rem;
|
||||
--space-4: 1rem;
|
||||
--space-6: 1.5rem;
|
||||
--space-8: 2rem;
|
||||
|
||||
--text-sm: 0.875rem;
|
||||
--text-lg: 1.125rem;
|
||||
--text-xl: 1.25rem;
|
||||
|
||||
--radius: 0.5rem;
|
||||
--shadow: 0 1px 3px rgb(0 0 0 / 0.4), 0 1px 2px rgb(0 0 0 / 0.3);
|
||||
--transition: 150ms ease;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* Layout */
|
||||
|
||||
header,
|
||||
main,
|
||||
footer {
|
||||
max-width: 64rem;
|
||||
margin-inline: auto;
|
||||
padding-inline: var(--space-4);
|
||||
}
|
||||
|
||||
/* The columns of main, so the options line up with the Receive card, below the title on a phone */
|
||||
header {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
padding-block: var(--space-6) var(--space-4);
|
||||
}
|
||||
|
||||
header > div:first-child {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: var(--text-xl);
|
||||
}
|
||||
|
||||
/* The switches at the end, the own salt below while it's on */
|
||||
#options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-family: ui-monospace, 'Cascadia Code', monospace;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: var(--muted);
|
||||
margin: 0 0 1.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
#options > div:first-child {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
width: 100%;
|
||||
flex-wrap: wrap;
|
||||
justify-content: end;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
flex: 1;
|
||||
main {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||
align-items: start;
|
||||
gap: var(--space-4);
|
||||
padding-bottom: var(--space-8);
|
||||
}
|
||||
|
||||
button {
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.55rem 1rem;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
main > p,
|
||||
main > aside,
|
||||
main > details {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
/* Note while no STUN server would be used, quiet above the cards */
|
||||
#no-stun {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
:where(a, button, input, select, textarea):focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
/* Cards */
|
||||
|
||||
article,
|
||||
details {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--bg);
|
||||
article {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-6);
|
||||
}
|
||||
|
||||
article h2 {
|
||||
font-size: var(--text-lg);
|
||||
}
|
||||
|
||||
section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: start;
|
||||
gap: var(--space-2);
|
||||
padding-top: var(--space-4);
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
h3,
|
||||
article summary {
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.step {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
label,
|
||||
section p {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
section p[role='alert'] {
|
||||
color: var(--color-secondary-text);
|
||||
}
|
||||
|
||||
header label {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* Forms */
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
background: var(--color-input);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
color: inherit;
|
||||
transition: border-color var(--transition);
|
||||
}
|
||||
|
||||
input:focus,
|
||||
textarea:focus {
|
||||
border-color: var(--color-secondary);
|
||||
}
|
||||
|
||||
/* Like a disabled button, the switch with its label */
|
||||
input:not([role='switch']):disabled,
|
||||
label:has([role='switch']:disabled) {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
label:has([role='switch']:disabled) [role='switch'] {
|
||||
cursor: inherit;
|
||||
}
|
||||
|
||||
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
||||
input:not([type='checkbox'], [type='file']):focus-visible,
|
||||
textarea:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
::placeholder {
|
||||
color: var(--color-text-muted);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-height: 90px;
|
||||
min-height: 5rem;
|
||||
resize: vertical;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.75rem;
|
||||
word-break: break-all;
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.dropzone {
|
||||
border: 2px dashed var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 2rem;
|
||||
button {
|
||||
padding: var(--space-2) var(--space-4);
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius);
|
||||
background: var(--color-primary);
|
||||
color: var(--color-on-primary);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--transition);
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
background: var(--color-primary-hover);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--color-secondary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
[role='group'] {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* The tracker code on both sides. The sender's is read only like an input, one click selects it. */
|
||||
#send-code,
|
||||
#receive-code {
|
||||
color: var(--color-secondary-text);
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: var(--text-lg);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.15em;
|
||||
}
|
||||
|
||||
#send-code {
|
||||
flex: 1;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
background: var(--color-input);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
#send-code[data-expired] {
|
||||
text-decoration: line-through;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Copy and Generate, secondary next to the value they are for */
|
||||
|
||||
[data-copy] {
|
||||
padding: var(--space-1) var(--space-3);
|
||||
background: transparent;
|
||||
border-color: var(--color-border);
|
||||
color: var(--color-text);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
[data-copy]:hover:not(:disabled) {
|
||||
background: var(--color-border);
|
||||
}
|
||||
|
||||
/* Manual signaling, folded away below the tracker in each card */
|
||||
|
||||
article details {
|
||||
background: none;
|
||||
border: none;
|
||||
border-top: 1px solid var(--color-border);
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
article summary {
|
||||
padding: var(--space-4) 0 0;
|
||||
}
|
||||
|
||||
article details section {
|
||||
padding-top: var(--space-2);
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
/* Drop zone, the invisible file input covers the whole label. The incoming file looks alike. */
|
||||
|
||||
label:has(> [type='file']),
|
||||
#incoming {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-8) var(--space-4);
|
||||
background: var(--color-input);
|
||||
border: 2px dashed var(--color-border);
|
||||
border-radius: var(--radius);
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
transition:
|
||||
border-color var(--transition),
|
||||
background-color var(--transition);
|
||||
}
|
||||
|
||||
label:has(> [type='file']):hover,
|
||||
label[data-dragging] {
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
label[data-dragging] {
|
||||
background: color-mix(in srgb, var(--color-primary) 10%, var(--color-input));
|
||||
}
|
||||
|
||||
label:has(> [type='file']:focus-visible) {
|
||||
outline: 2px solid var(--color-secondary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
#incoming {
|
||||
border-style: solid;
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
#incoming button {
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
|
||||
[type='file'] {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dropzone.dragover {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
label strong,
|
||||
#incoming strong {
|
||||
color: var(--color-text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.progress {
|
||||
height: 10px;
|
||||
background: var(--bg);
|
||||
border-radius: 6px;
|
||||
/* A dropped folder, refused */
|
||||
#not-a-file {
|
||||
color: var(--color-secondary-text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* How the session is doing, below the file on its side. Until the transfer starts a pill passes
|
||||
through the bar, blue, or pink while it tries again after a failure. Then the transfer's progress,
|
||||
green once done, muted once stopped, pink for an error. The line below says what. */
|
||||
|
||||
[data-phase] {
|
||||
--bar: var(--color-primary);
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
[data-phase='retry'],
|
||||
[data-phase='error'] {
|
||||
--bar: var(--color-secondary);
|
||||
}
|
||||
|
||||
[data-phase='done'] {
|
||||
--bar: var(--color-success);
|
||||
}
|
||||
|
||||
[data-phase='stopped'] {
|
||||
--bar: var(--color-text-muted);
|
||||
}
|
||||
|
||||
[data-phase] p {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
font-size: var(--text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* The send session's file, above its bar once the user picked another one */
|
||||
#send-file {
|
||||
color: var(--color-text);
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* A block, a flex container has no first letter. Flex items do, they are blocks. */
|
||||
[data-phase] p[role='alert'] {
|
||||
display: block;
|
||||
color: var(--color-secondary-text);
|
||||
}
|
||||
|
||||
[data-phase] p[role='alert']::first-letter,
|
||||
[data-phase] [role='status'] > :first-child::first-letter {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* The track, the progress inside it fills it or, without a value, is the pill */
|
||||
[data-phase] > div {
|
||||
height: 0.5rem;
|
||||
border-radius: 999px;
|
||||
background: var(--color-input);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress > div {
|
||||
progress {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
transition: width 0.15s linear;
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.status {
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
progress::-webkit-progress-bar {
|
||||
background: none;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #ff6b5e;
|
||||
font-size: 0.85rem;
|
||||
progress::-webkit-progress-value {
|
||||
background: var(--bar);
|
||||
}
|
||||
|
||||
.file-chip {
|
||||
progress::-moz-progress-bar {
|
||||
background: var(--bar);
|
||||
}
|
||||
|
||||
progress:indeterminate {
|
||||
width: 25%;
|
||||
border-radius: 999px;
|
||||
background: var(--bar);
|
||||
animation: pass 2584ms linear infinite;
|
||||
}
|
||||
|
||||
progress:indeterminate::-moz-progress-bar {
|
||||
background: none;
|
||||
}
|
||||
|
||||
/* Its own width is a quarter of the track's: from just before it to just past it */
|
||||
@keyframes pass {
|
||||
from {
|
||||
translate: -100%;
|
||||
}
|
||||
|
||||
to {
|
||||
translate: 400%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
progress:indeterminate {
|
||||
translate: 150%;
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Switch, like Pico's role="switch" */
|
||||
|
||||
label:has([role='switch']) {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem 0.9rem;
|
||||
font-size: 0.9rem;
|
||||
gap: var(--space-2);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
a.download {
|
||||
color: var(--accent);
|
||||
[role='switch'] {
|
||||
appearance: none;
|
||||
width: 2.25rem;
|
||||
height: 1.25rem;
|
||||
padding: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--color-border);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
transition: background-color var(--transition);
|
||||
}
|
||||
|
||||
[role='switch']::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0.125rem auto 0.125rem 0.125rem;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 50%;
|
||||
background: var(--color-text);
|
||||
transition: translate var(--transition);
|
||||
}
|
||||
|
||||
[role='switch']:checked {
|
||||
background: var(--color-success);
|
||||
}
|
||||
|
||||
[role='switch']:checked::before {
|
||||
translate: 1rem 0;
|
||||
}
|
||||
|
||||
/* Security check callout */
|
||||
|
||||
aside {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-4) var(--space-6);
|
||||
background: color-mix(in srgb, var(--color-secondary) 8%, var(--color-surface));
|
||||
border: 1px solid var(--color-secondary);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
aside p {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
|
||||
/* Monospaced in a grid, so both codes line up byte by byte */
|
||||
aside dl {
|
||||
flex: 1 1 auto;
|
||||
display: grid;
|
||||
grid-template-columns: auto auto;
|
||||
justify-content: start;
|
||||
column-gap: var(--space-3);
|
||||
}
|
||||
|
||||
aside dt {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
aside div {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
aside button + button {
|
||||
background: transparent;
|
||||
border-color: var(--color-border);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
aside button + button:hover {
|
||||
background: var(--color-border);
|
||||
}
|
||||
|
||||
output {
|
||||
color: var(--color-secondary-text);
|
||||
font-family: ui-monospace, monospace;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fingerprint {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem 0.9rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
/* Source link, quiet below everything */
|
||||
|
||||
.fp-row {
|
||||
footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
font-size: 0.9rem;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
padding-bottom: var(--space-6);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fp-row code {
|
||||
font-family: ui-monospace, monospace;
|
||||
color: var(--accent);
|
||||
letter-spacing: 0.12em;
|
||||
footer a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
color: var(--color-text-muted);
|
||||
text-decoration: none;
|
||||
transition: color var(--transition);
|
||||
}
|
||||
|
||||
.fingerprint .status {
|
||||
margin: 0.2rem 0 0;
|
||||
footer a:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.stun-select,
|
||||
.stun-input {
|
||||
width: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.55rem 0.75rem;
|
||||
font-size: 0.95rem;
|
||||
font-family: inherit;
|
||||
footer img {
|
||||
filter: grayscale(1);
|
||||
opacity: 0.6;
|
||||
transition: opacity var(--transition);
|
||||
}
|
||||
|
||||
.stun-input {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.85rem;
|
||||
footer a:hover img {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.stun-select:focus,
|
||||
.stun-input:focus {
|
||||
border-color: var(--accent);
|
||||
/* Servers */
|
||||
|
||||
#servers > div {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||
justify-items: start;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-4) var(--space-6) var(--space-6);
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
p.stun-hint {
|
||||
margin: -0.35rem 0 0;
|
||||
font-size: 0.78rem;
|
||||
#servers section {
|
||||
justify-self: stretch;
|
||||
padding-top: 0;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.network-settings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
min-width: 0;
|
||||
padding: var(--space-sm) var(--space-md) var(--space-md);
|
||||
#servers p {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.network-settings legend { color: var(--muted); }
|
||||
.checkbox { display: flex; align-items: start; gap: var(--space-sm); }
|
||||
.fp-row { flex-direction: column; align-items: start; }
|
||||
.fp-row code { overflow-wrap: anywhere; line-height: 1.7; font-size: 0.8rem; }
|
||||
.file-chip span { overflow-wrap: anywhere; min-width: 0; }
|
||||
.incoming { display: flex; flex-direction: column; gap: 0.7rem; overflow-wrap: anywhere; }
|
||||
|
||||
.transfer-section { display: flex; flex-direction: column; gap: var(--space-md); scroll-margin-top: 1rem; min-width: 0; }
|
||||
.transfer-section:focus-visible { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 4px; }
|
||||
|
||||
.device-settings { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; border: 1px solid var(--border); border-radius: 8px; padding: var(--space-sm) var(--space-md) var(--space-md); }
|
||||
.config-details > :not(summary) { margin-block: var(--space-sm) 0; }
|
||||
.config-details fieldset .status { margin-block: 0; line-height: 1.5; }
|
||||
.device-settings input:not([type=checkbox]) { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; }
|
||||
|
||||
/* The connection shell stays in place while each workspace scrolls. */
|
||||
.app-shell { display: grid; grid-template-columns: 264px minmax(0, 1fr); height: 100%; }
|
||||
.sidebar { display: flex; flex-direction: column; gap: var(--space-lg); background: #13161e; border-right: 1px solid var(--border); padding: 1.6rem 1rem 1rem; min-height: 0; overflow-y: auto; }
|
||||
.brand { display: flex; align-items: center; gap: 0.8rem; padding: 0 0.5rem var(--space-lg); }
|
||||
.brand img { object-fit: contain; }
|
||||
.brand-name { display: block; font-family: ui-monospace, monospace; font-weight: 700; font-size: 1.45rem; letter-spacing: -0.05em; }
|
||||
.brand p { font-size: 0.75rem; color: var(--muted); margin: 0.25rem 0 0; }
|
||||
.sidebar-section-heading { display: flex; align-items: center; justify-content: space-between; padding: 0 0.65rem; }
|
||||
.sidebar-section-heading h2 { text-transform: uppercase; font-size: 0.68rem; letter-spacing: 0.12em; color: var(--muted); margin: 0; font-weight: 650; }
|
||||
.sidebar-section-heading > span { font-size: 0.72rem; color: var(--muted); }
|
||||
.connection-nav { display: flex; flex-direction: column; gap: 0.35rem; }
|
||||
.connection-item { position: relative; border: 1px solid transparent; border-radius: 9px; }
|
||||
.connection-item.selected { background: var(--accent-soft); border-color: #65472e; }
|
||||
.connection-link, .connection-edit { display: flex; flex-direction: column; align-items: stretch; justify-content: center; gap: 0.4rem; min-width: 0; width: 100%; min-height: 64px; padding: 0.55rem 4.2rem 0.55rem 0.7rem; }
|
||||
.connection-link { text-align: left; background: transparent; border: 0; border-radius: 8px; }
|
||||
.connection-link:hover:not(:disabled) { background: #ffffff08; }
|
||||
.connection-edit { padding-right: 2.4rem; }
|
||||
.connection-name { color: var(--text); font-size: 0.87rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.connection-status-line { display: flex; align-items: center; gap: 0.45rem; min-width: 0; color: var(--muted); font-size: 0.72rem; }
|
||||
.connection-status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.connection-action { position: absolute; top: 0.45rem; display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 0; background: transparent; color: var(--muted); font-size: 0.9rem; }
|
||||
.connection-action:hover:not(:disabled), .connection-action:focus-visible { color: var(--accent); }
|
||||
.edit-action { right: 2.25rem; }
|
||||
.remove-action { right: 0.35rem; }
|
||||
.remove-action:hover:not(:disabled), .remove-action:focus-visible { color: #ff9185; }
|
||||
.connection-rename-input { width: 100%; min-width: 0; border: 1px solid var(--accent); border-radius: 6px; padding: 0.28rem 0.35rem; background: var(--bg); color: var(--text); font: inherit; font-size: 0.87rem; font-weight: 600; }
|
||||
.connection-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: #7c8495; flex-shrink: 0; }
|
||||
.connection-dot.connected { background: #69d6a4; }
|
||||
.connection-dot.connecting { background: var(--accent); }
|
||||
.add-connection { display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 0.82rem; background: transparent; border-style: dashed; }
|
||||
.add-connection > span { font-size: 1.1rem; }
|
||||
.sidebar-footer { margin-top: auto; padding: var(--space-xl) 0.65rem 0.25rem; color: var(--muted); font-size: 0.72rem; line-height: 1.65; }
|
||||
.sidebar-tag { font-weight: 600; color: var(--text); }
|
||||
.sidebar-footer p { margin: 0.5rem 0 1rem; }
|
||||
.source-link { display: inline-flex; align-items: center; gap: 0.35rem; margin-top: 0.4rem; color: var(--muted); text-decoration: none; }
|
||||
.source-link:hover { color: var(--text); }
|
||||
.source-link img { filter: grayscale(1); opacity: 0.6; }
|
||||
.source-link:hover img { opacity: 0.9; }
|
||||
summary { cursor: pointer; color: var(--muted); font-size: 0.83rem; padding: 0.4rem 0; }
|
||||
summary:hover { color: var(--text); }
|
||||
summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
.privacy-details summary { font-size: 0.72rem; }
|
||||
.main-pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; }
|
||||
.workspace-scroll { flex: 1; overflow-y: auto; padding: var(--space-2xl) 2.25rem; }
|
||||
.connection-workspace { width: 100%; max-width: 720px; min-width: 0; margin-inline: auto; }
|
||||
.workspace-intro { margin-bottom: 1.4rem; }
|
||||
.workspace-intro h2 { font-size: 1.05rem; font-weight: 600; margin: 0 0 0.4rem; }
|
||||
.workspace-intro p { font-size: 0.85rem; color: var(--muted); line-height: 1.6; margin: 0; }
|
||||
.tabs { width: fit-content; padding: 4px; gap: 4px; background: #1b1f2a; border: 1px solid var(--border); border-radius: 10px; }
|
||||
.tabs button { padding: 0.45rem var(--space-xl); font-size: 0.85rem; border: none; background: transparent; }
|
||||
.tabs button.active { background: #3e3025; color: #ffb575; }
|
||||
.panel { box-shadow: 0 6px 28px #00000012; }
|
||||
.panel > .status { line-height: 1.6; margin: 0.1rem 0; }
|
||||
.panel > button { align-self: start; font-size: 0.88rem; }
|
||||
.dropzone { padding: 1.35rem 1rem; background: #141720; border-color: #414858; }
|
||||
.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; }
|
||||
.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; }
|
||||
@media (max-width: 1150px) {
|
||||
.app-shell { grid-template-columns: 230px minmax(0, 1fr); }
|
||||
.workspace-scroll { padding: var(--space-xl); }
|
||||
[aria-invalid='true'] {
|
||||
border-color: var(--color-secondary);
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
#app { height: auto; min-height: 100dvh; }
|
||||
.app-shell { display: flex; flex-direction: column; min-height: 100dvh; }
|
||||
.sidebar { display: none; border-right: 0; border-bottom: 1px solid var(--border); max-height: 60dvh; }
|
||||
.sidebar-open .sidebar { display: flex; }
|
||||
.brand { padding-bottom: 0; }
|
||||
.sidebar-footer { padding-top: 0; }
|
||||
.mobile-bar { display: flex; align-items: center; gap: 0.75rem; margin: 0.75rem 1rem 0; }
|
||||
.mobile-current { display: flex; flex-direction: column; gap: 0.3rem; flex: 1; min-width: 0; }
|
||||
.mobile-current-name { font-size: 0.95rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mobile-current-status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.sidebar-toggle { flex-shrink: 0; margin-left: auto; font-size: 0.8rem; background: transparent; padding: 0.5rem; }
|
||||
.workspace-scroll { padding: var(--space-lg) 1rem; overflow: visible; }
|
||||
.panel { padding: 1rem; }
|
||||
|
||||
/* Log */
|
||||
|
||||
summary {
|
||||
padding: var(--space-3) var(--space-6);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
pre {
|
||||
max-height: 20rem;
|
||||
overflow: auto;
|
||||
padding: var(--space-4) var(--space-6);
|
||||
border-top: 1px solid var(--color-border);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.app-dialog { width: min(460px, calc(100% - 2rem)); max-height: calc(100dvh - 2rem); margin: auto; padding: 1.5rem; border: 1px solid #414858; border-radius: 14px; color: var(--text); background: var(--panel); box-shadow: 0 24px 100px #0009; overflow-y: auto; }
|
||||
.app-dialog::backdrop { background: #080b12b8; backdrop-filter: blur(4px); }
|
||||
.dialog-header { display: flex; align-items: start; justify-content: space-between; gap: 1rem; }
|
||||
.dialog-header h2 { margin: 0; font-size: 1.15rem; font-weight: 600; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.dialog-close { flex-shrink: 0; border-color: transparent; background: transparent; color: var(--muted); padding: 0 0.4rem; font-size: 1.4rem; line-height: 1.2; }
|
||||
.dialog-body { color: var(--muted); font-size: 0.88rem; line-height: 1.7; margin-block: 1rem 1.5rem; }
|
||||
.dialog-body p { margin: 0.75rem 0; }
|
||||
.dialog-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.6rem; }
|
||||
.dialog-actions button { font-size: 0.85rem; }
|
||||
button.danger { border-color: #b84d42; background: #672f2b; color: #ffe3df; }
|
||||
button.danger:hover:not(:disabled) { border-color: #ff9185; background: #813b34; }
|
||||
@media (max-width: 700px) { .app-dialog { padding: 1.2rem; } }
|
||||
@@ -1,74 +0,0 @@
|
||||
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, 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) };
|
||||
const ref = createRef();
|
||||
const offer: Signal = { type: 'offer', ref, sdp };
|
||||
const base64url = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64url');
|
||||
async function deflate(data: Uint8Array<ArrayBuffer> | string) {
|
||||
return new Uint8Array(await new Response(new Blob([data]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer());
|
||||
}
|
||||
const raw = async (payload: unknown) => CODE_PREFIX + base64url(await deflate(JSON.stringify(payload)));
|
||||
|
||||
test('codes round-trip both types, with and without identity', async () => {
|
||||
assert.match(ref, /^[A-Za-z0-9_-]{22}$/);
|
||||
assert.notEqual(createRef(), ref);
|
||||
for (const signal of [offer, { ...offer, type: 'answer' as const }, { ...offer, identity }]) {
|
||||
const code = await encodeCode(signal);
|
||||
assert.ok(code.startsWith(CODE_PREFIX));
|
||||
assert.match(code.slice(CODE_PREFIX.length), /^[A-Za-z0-9_-]+$/);
|
||||
assert.deepEqual(await decodeCode(code), signal);
|
||||
}
|
||||
});
|
||||
|
||||
test('wrapped text and bare codes decode the same', async () => {
|
||||
const code = await encodeCode(offer);
|
||||
assert.deepEqual(await decodeCode(` ${code.slice(0, 20)}\n${code.slice(20)} `), offer);
|
||||
});
|
||||
|
||||
test('expected type and ref are enforced', async () => {
|
||||
const answer = await encodeCode({ ...offer, type: 'answer' });
|
||||
await assert.rejects(decodeCode(await encodeCode(offer), { type: 'answer' }), /not an answer/);
|
||||
await assert.rejects(decodeCode(answer, { type: 'offer' }), /not a connection code/);
|
||||
await assert.rejects(decodeCode(answer, { type: 'answer', ref: createRef() }), /different connection code/);
|
||||
assert.equal((await decodeCode(answer, { type: 'answer', ref })).type, 'answer');
|
||||
});
|
||||
|
||||
test('descriptions are validated, including relay opt-in', async () => {
|
||||
const relayed = await encodeCode({ ...offer, sdp: sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n' });
|
||||
await assert.rejects(decodeCode(relayed), /explicitly enable TURN/);
|
||||
assert.equal((await decodeCode(relayed, { allowTurn: true })).type, 'offer');
|
||||
await assert.rejects(encodeCode({ ...offer, identity: { key: '04', nonce: '' } }), /device identity/);
|
||||
await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref, sdp: 'v=0' })), /data channel/);
|
||||
});
|
||||
|
||||
test('malformed, old and unexpected payloads are rejected', async () => {
|
||||
for (const text of ['', 'bad!', CODE_PREFIX, `${CODE_PREFIX}a`, `${CODE_PREFIX}not+base64`, `${CODE_PREFIX}AAAA`, CODE_PREFIX + base64url(new Uint8Array([0xff, 0xfe]))]) {
|
||||
await assert.rejects(decodeCode(text), /Invalid connection code/, text);
|
||||
}
|
||||
await assert.rejects(decodeCode(btoa(JSON.stringify({ version: 4, sdp }))), /current HellCon version/);
|
||||
await assert.rejects(decodeCode(await raw({ version: 2, type: 'offer', ref, sdp })), /current HellCon version/);
|
||||
await assert.rejects(decodeCode(await raw([1])), /current HellCon version/);
|
||||
await assert.rejects(decodeCode(await raw({ version: 3, type: 'pranswer', ref, sdp })), /Invalid connection code/);
|
||||
await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref: 'short', sdp })), /Invalid connection code/);
|
||||
await assert.rejects(decodeCode(await raw({ version: 3, type: 'offer', ref, sdp, identity })), /Invalid connection code/);
|
||||
await assert.rejects(decodeCode(await raw({ version: 4, type: 'offer', ref, sdp })), /device identity/);
|
||||
await assert.rejects(decodeCode(CODE_PREFIX + base64url(await deflate(new Uint8Array([0x7b, 0xff, 0x7d])))), /Invalid connection code/);
|
||||
await assert.rejects(decodeCode(42), /too large/);
|
||||
});
|
||||
|
||||
test('oversized codes and decompression bombs are rejected', async () => {
|
||||
await assert.rejects(decodeCode(CODE_PREFIX + 'A'.repeat(MAX_CODE_LENGTH)), /too large/);
|
||||
await assert.rejects(decodeCode('x'.repeat(MAX_INPUT_LENGTH + 1)), /too large/);
|
||||
// 32 MiB of zeros deflate to about 32 KiB, which fits the code length limit.
|
||||
const bomb = CODE_PREFIX + base64url(await deflate(new Uint8Array(32 * 1024 * 1024)));
|
||||
assert.ok(bomb.length < MAX_CODE_LENGTH);
|
||||
const started = Date.now();
|
||||
await assert.rejects(decodeCode(bomb), /too large/);
|
||||
assert.ok(Date.now() - started < 2000);
|
||||
// Base64 text of random bytes stays incompressible enough to exceed the limit.
|
||||
await assert.rejects(encodeCode({ ...offer, sdp: sdp + 'a=x:' + randomBytes(60000).toString('base64') }), /too large/);
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { ConnectionDiagnostics, summarizeCandidates, summarizeStats } from '../src/lib/connection-diagnostics.ts';
|
||||
|
||||
test('candidate summaries keep types and end marker, never addresses or SDP secrets', () => {
|
||||
const sdp = 'a=ice-pwd:private-password\r\na=fingerprint:sha-256 SECRET\r\n' +
|
||||
'a=candidate:private-id 1 udp 123 192.0.2.20 5000 typ host\r\n' +
|
||||
'a=candidate:other-id 1 udp 123 example.local 5000 typ host\r\n' +
|
||||
'a=candidate:another-id 1 udp 123 2001:db8::1 5000 typ srflx\r\n' +
|
||||
'a=candidate:last-id 1 udp 123 192.0.2.22 5000 typ private-value\r\na=end-of-candidates\r\n';
|
||||
assert.equal(summarizeCandidates(sdp), 'host=2 srflx=1 prflx=0 relay=0 unknown=1 end=yes');
|
||||
assert.equal(summarizeCandidates(undefined), 'host=0 srflx=0 prflx=0 relay=0 unknown=0 end=no');
|
||||
});
|
||||
|
||||
test('stats use only allowlisted types, pair states and nonnegative integer counters', () => {
|
||||
const stats = new Map([
|
||||
['private-local-id', { type: 'local-candidate', candidateType: 'srflx', protocol: 'udp', address: '192.0.2.20', usernameFragment: 'private-user' }],
|
||||
['private-remote-id', { type: 'remote-candidate', candidateType: 'host', protocol: 'private-protocol', address: '192.0.2.21' }],
|
||||
['private-pair-id', { id: 'private-pair-id', type: 'candidate-pair', localCandidateId: 'private-local-id', remoteCandidateId: 'private-remote-id', state: 'failed', nominated: false, requestsSent: 8, requestsReceived: 0, responsesReceived: -1, responsesSent: 'private-text' }],
|
||||
['transport', { type: 'transport', selectedCandidatePairId: 'private-pair-id' }],
|
||||
]);
|
||||
const lines = summarizeStats(stats);
|
||||
assert.equal(lines[3], 'pair srflx/udp → host/unknown failed selected=true nominated=false requestsSent=8 requestsReceived=0 responsesSent=? responsesReceived=?');
|
||||
assert.doesNotMatch(lines.join('\n'), /private|192\.0\.2/);
|
||||
});
|
||||
|
||||
class Peer extends EventTarget {
|
||||
connectionState = 'failed';
|
||||
iceConnectionState = 'failed';
|
||||
iceGatheringState = 'complete';
|
||||
closed = false;
|
||||
getStats: () => Promise<Map<string, Record<string, unknown>>> = async () => new Map();
|
||||
}
|
||||
const diagnose = (peer: Peer) => new ConnectionDiagnostics(peer as unknown as RTCPeerConnection, () => {});
|
||||
|
||||
test('final stats are collected before close, close is called once, and listeners stop', async () => {
|
||||
const peer = new Peer();
|
||||
let resolve!: (stats: Map<string, Record<string, unknown>>) => void;
|
||||
peer.getStats = () => {
|
||||
assert.equal(peer.closed, false);
|
||||
return new Promise(done => { resolve = done; });
|
||||
};
|
||||
const diagnostics = diagnose(peer);
|
||||
let closes = 0;
|
||||
const close = () => { peer.closed = true; closes++; };
|
||||
const finishing = diagnostics.finish(close);
|
||||
assert.equal(diagnostics.finish(close), finishing);
|
||||
assert.equal(closes, 0);
|
||||
resolve(new Map());
|
||||
await finishing;
|
||||
assert.equal(closes, 1);
|
||||
assert.ok(diagnostics.lines.some(line => line.endsWith('pairs=0')));
|
||||
const saved = [...diagnostics.lines];
|
||||
peer.dispatchEvent(new Event('connectionstatechange'));
|
||||
assert.deepEqual(diagnostics.lines, saved);
|
||||
});
|
||||
|
||||
test('rejected and hung stats cannot prevent peer cleanup or leak error details', async () => {
|
||||
for (const getStats of [async () => { throw new Error('private credential'); }, () => new Promise<Map<string, Record<string, unknown>>>(() => {})]) {
|
||||
const peer = new Peer(); peer.getStats = getStats;
|
||||
const diagnostics = diagnose(peer);
|
||||
await diagnostics.finish(() => { peer.closed = true; });
|
||||
assert.equal(peer.closed, true);
|
||||
assert.match(diagnostics.lines.join('\n'), /stats unavailable/);
|
||||
assert.doesNotMatch(diagnostics.lines.join('\n'), /private credential/);
|
||||
}
|
||||
});
|
||||
|
||||
test('event history remains bounded', () => {
|
||||
const peer = new Peer(); const diagnostics = diagnose(peer);
|
||||
for (let i = 0; i < 100; i++) peer.dispatchEvent(new Event('iceconnectionstatechange'));
|
||||
assert.equal(diagnostics.lines.length, 80);
|
||||
});
|
||||
|
||||
|
||||
test('checking snapshots retain live pairs before failure removes them', async t => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const peer = new Peer();
|
||||
peer.connectionState = 'connecting'; peer.iceConnectionState = 'checking';
|
||||
let calls = 0;
|
||||
peer.getStats = async () => { calls++; return new Map([
|
||||
['pair', { type: 'candidate-pair', state: 'in-progress', requestsSent: 5, responsesReceived: 0 }],
|
||||
['transport', { type: 'transport', dtlsState: 'new', privateValue: 'secret' }],
|
||||
]); };
|
||||
const diagnostics = diagnose(peer);
|
||||
t.mock.timers.tick(3000);
|
||||
await Promise.resolve(); await Promise.resolve();
|
||||
assert.equal(calls, 1);
|
||||
assert.match(diagnostics.lines.join('\n'), /requestsSent=5.*responsesReceived=0/);
|
||||
assert.match(diagnostics.lines.join('\n'), /transport dtls=new/);
|
||||
assert.doesNotMatch(diagnostics.lines.join('\n'), /secret/);
|
||||
peer.iceConnectionState = 'failed';
|
||||
peer.dispatchEvent(new Event('iceconnectionstatechange'));
|
||||
peer.getStats = async () => { calls++; return new Map(); };
|
||||
await diagnostics.finish(() => { peer.closed = true; });
|
||||
t.mock.timers.tick(12000);
|
||||
assert.equal(calls, 2);
|
||||
assert.match(diagnostics.lines.join('\n'), /requestsSent=5/);
|
||||
assert.ok(diagnostics.lines.at(-1)?.endsWith('pairs=0'));
|
||||
});
|
||||
|
||||
test('DTLS diagnostics allowlist values and never retain transport details', () => {
|
||||
const lines = summarizeStats(new Map([['transport-secret', { type: 'transport', dtlsState: 'private-value', remoteCertificateId: 'secret' }]]));
|
||||
assert.ok(lines.includes('transport dtls=unknown'));
|
||||
assert.doesNotMatch(lines.join('\n'), /private|secret/);
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { emptyConnection, updateConnection } from '../src/lib/connections.ts';
|
||||
|
||||
test('renaming and pairing preserve a slot identity', () => {
|
||||
const initial = emptyConnection(2);
|
||||
const renamed = updateConnection(initial, { name: ' Work laptop ' });
|
||||
const remembering = updateConnection(renamed, { rememberDevice: true });
|
||||
const paired = updateConnection(remembering, { peerKey: '04' + 'a'.repeat(128) });
|
||||
assert.equal(initial.name, 'Con 2');
|
||||
assert.equal(initial.rememberDevice, false);
|
||||
assert.equal(paired.rememberDevice, true);
|
||||
assert.equal(updateConnection(paired, { peerKey: '' }).rememberDevice, true, 'Forgetting a device keeps the opt-in');
|
||||
assert.equal(paired.id, initial.id);
|
||||
assert.equal(paired.name, 'Work laptop');
|
||||
assert.equal('history' in paired, false);
|
||||
assert.throws(() => updateConnection(paired, { name: ' ' }));
|
||||
assert.throws(() => updateConnection(paired, { name: 'a'.repeat(81) }));
|
||||
assert.throws(() => updateConnection(paired, { peerKey: 'invalid' }));
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const source = readFileSync(new URL('../public/download/worker.js', import.meta.url), 'utf8');
|
||||
function worker() {
|
||||
const listeners: Record<string, (event: any) => void> = {};
|
||||
const scope = 'https://example.test/app/download/';
|
||||
const messages: Array<{ type: string; message?: string; url?: string }> = [];
|
||||
const port = { postMessage: (message: typeof messages[number]) => messages.push(message), close() {}, onmessage: null as null | ((event: any) => void) };
|
||||
new Function('self', source)({ registration: { scope }, addEventListener(type: string, listener: (event: any) => void) { listeners[type] = listener; } });
|
||||
function start(stream: ReadableStream, size: number) {
|
||||
listeners.message({ data: { type: 'download', id: 'a'.repeat(32), name: "report 'test'.bin", size, stream }, ports: [port] });
|
||||
assert.equal(messages[0]?.type, 'ready');
|
||||
}
|
||||
async function fetch(url = messages[0]?.url) {
|
||||
let response: Response | undefined;
|
||||
listeners.fetch({ request: new Request(url!), respondWith(value: Response) { response = value; } });
|
||||
assert.ok(response);
|
||||
return response;
|
||||
}
|
||||
return { start, fetch, messages, port };
|
||||
}
|
||||
|
||||
test('download worker streams exact bytes, uses attachment headers, and consumes URLs once', async () => {
|
||||
const w = worker();
|
||||
const stream = new TransformStream();
|
||||
w.start(stream.readable, 3);
|
||||
const response = await w.fetch();
|
||||
assert.equal(response.headers.get('Content-Length'), '3');
|
||||
assert.match(response.headers.get('Content-Disposition')!, /attachment; filename\*=UTF-8''report%20%27test%27.bin/);
|
||||
assert.equal(response.headers.get('Cache-Control'), 'no-store');
|
||||
assert.equal((await w.fetch()).status, 404);
|
||||
const bytes = response.arrayBuffer();
|
||||
const writer = stream.writable.getWriter();
|
||||
await writer.write(Uint8Array.of(1, 2, 3));
|
||||
assert.equal(w.messages.some(message => message.type === 'complete'), false);
|
||||
await writer.close();
|
||||
assert.deepEqual(new Uint8Array(await bytes), Uint8Array.of(1, 2, 3));
|
||||
assert.equal(w.messages.at(-1)?.type, 'complete');
|
||||
});
|
||||
|
||||
test('download backpressure blocks writes until the browser reads', async () => {
|
||||
const w = worker();
|
||||
const stream = new TransformStream();
|
||||
w.start(stream.readable, 1);
|
||||
const response = await w.fetch();
|
||||
let written = false;
|
||||
const writer = stream.writable.getWriter();
|
||||
const write = writer.write(Uint8Array.of(7)).then(() => { written = true; });
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
assert.equal(written, false);
|
||||
const bytes = response.arrayBuffer();
|
||||
await write; await writer.close(); await bytes;
|
||||
});
|
||||
|
||||
for (const size of [0, 2]) test(`download rejects byte count mismatch (declared ${size})`, async () => {
|
||||
const w = worker();
|
||||
w.start(new ReadableStream({ start(controller) { controller.enqueue(Uint8Array.of(7)); controller.close(); } }), size);
|
||||
const response = await w.fetch();
|
||||
await assert.rejects(response.arrayBuffer());
|
||||
assert.equal(w.messages.at(-1)?.type, 'error');
|
||||
assert.equal(w.messages.some(message => message.type === 'complete'), false);
|
||||
});
|
||||
|
||||
test('browser cancellation cancels the source and never reports completion', async () => {
|
||||
const w = worker();
|
||||
let canceled = false;
|
||||
w.start(new ReadableStream({ cancel() { canceled = true; } }), 100);
|
||||
const response = await w.fetch();
|
||||
await response.body!.cancel();
|
||||
assert.equal(canceled, true);
|
||||
assert.equal(w.messages.at(-1)?.type, 'error');
|
||||
});
|
||||
|
||||
test('app cancellation errors the browser response and cancels pending source reads', async () => {
|
||||
const w = worker();
|
||||
let canceled = false;
|
||||
w.start(new ReadableStream({ cancel() { canceled = true; } }), 100);
|
||||
const response = await w.fetch();
|
||||
const read = response.arrayBuffer();
|
||||
w.port.onmessage!({ data: { type: 'abort' } });
|
||||
await assert.rejects(read, /canceled/);
|
||||
assert.equal(canceled, true);
|
||||
assert.equal(w.messages.at(-1)?.type, 'error');
|
||||
});
|
||||
|
||||
test('download worker accepts sizes above 64 GiB without allocating the file', async () => {
|
||||
const w = worker();
|
||||
const size = 64 * 1024 ** 3 + 1;
|
||||
w.start(new ReadableStream(), size);
|
||||
const response = await w.fetch();
|
||||
assert.equal(response.headers.get('Content-Length'), String(size));
|
||||
await response.body!.cancel();
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { iceMiddleware } from '../dev/ice-server.ts';
|
||||
import { fetchTurnOptions } from '../src/lib/webrtc.ts';
|
||||
|
||||
interface Credentials {
|
||||
expiresAt: number;
|
||||
iceServers: [{ urls: string }, { urls: string[]; username: string; credential: string }];
|
||||
}
|
||||
interface ResponseResult {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body?: Credentials;
|
||||
next?: boolean;
|
||||
}
|
||||
function request(handler: ReturnType<typeof iceMiddleware>, { method = 'GET', url = '/api/ice-servers', headers = { host: '127.0.0.1:5173' } }: { method?: string; url?: string; headers?: Record<string, string> } = {}) {
|
||||
const result: ResponseResult = { status: 200, headers: {} };
|
||||
handler({ method, url, headers }, {
|
||||
setHeader(key, value) { result.headers[key] = value; },
|
||||
writeHead(status, headers) { result.status = status; Object.assign(result.headers, headers); },
|
||||
end(body) { result.body = body ? JSON.parse(body) : undefined; },
|
||||
}, () => { result.next = true; });
|
||||
return result;
|
||||
}
|
||||
|
||||
test('temporary credentials match coturn HMAC, expire in an hour and never expose the secret', () => {
|
||||
const secret = 'test-only-secret';
|
||||
const handler = iceMiddleware({ TURN_SECRET: secret });
|
||||
const first = request(handler), second = request(handler);
|
||||
assert.equal(first.headers['Cache-Control'], 'no-store');
|
||||
assert.ok(first.body); assert.ok(second.body);
|
||||
const { expiresAt, iceServers } = first.body;
|
||||
const turn = iceServers[1];
|
||||
assert.ok(Math.abs(expiresAt - Date.now() / 1000 - 3600) < 2);
|
||||
assert.ok(turn.username.startsWith(`${expiresAt}:`));
|
||||
assert.notEqual(turn.username, second.body.iceServers[1].username);
|
||||
assert.equal(turn.credential, createHmac('sha1', secret).update(turn.username).digest('base64'));
|
||||
assert.deepEqual(turn.urls, ['turn:127.0.0.1:3478?transport=udp', 'turn:127.0.0.1:3478?transport=tcp']);
|
||||
assert.ok(!JSON.stringify(first.body).includes(secret));
|
||||
});
|
||||
|
||||
test('development endpoint rejects cross-site issuance and unsupported methods', () => {
|
||||
assert.throws(() => iceMiddleware({}), /TURN_SECRET/);
|
||||
const handler = iceMiddleware({ TURN_SECRET: 'test' });
|
||||
assert.equal(request(handler, { method: 'POST' }).status, 405);
|
||||
assert.equal(request(handler, { headers: { 'sec-fetch-site': 'cross-site' } }).status, 403);
|
||||
assert.equal(request(handler, { headers: { host: 'localhost', origin: 'http://elsewhere' } }).status, 403);
|
||||
assert.equal(request(handler, { url: '/other' }).next, true);
|
||||
});
|
||||
|
||||
test('managed credentials require opt-in, refresh each connection, and fail closed', async () => {
|
||||
let calls = 0;
|
||||
const handler = iceMiddleware({ TURN_SECRET: 'test' });
|
||||
const fetchImpl = async () => { calls++; return { ok: true, json: async () => request(handler).body }; };
|
||||
await fetchTurnOptions({ managedTurn: true }, '/api/ice-servers', { fetchImpl });
|
||||
await fetchTurnOptions({ allowTurn: true, managedTurn: false }, '/api/ice-servers', { fetchImpl });
|
||||
assert.equal(calls, 0);
|
||||
const options = { allowTurn: true, managedTurn: true, stunUrl: null };
|
||||
const first = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
|
||||
const second = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
|
||||
assert.equal(calls, 2);
|
||||
assert.notEqual(first.username, second.username);
|
||||
assert.equal(first.stunUrl, null, 'User STUN choice must be preserved');
|
||||
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: false, json: async () => null }) }), /Could not obtain/);
|
||||
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: true, json: async () => ({ expiresAt: 1, iceServers: [] }) }) }), /expired/);
|
||||
const controller = new AbortController(); controller.abort();
|
||||
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { signal: controller.signal, fetchImpl: async (_url, { signal }) => { signal?.throwIfAborted(); throw new Error('Expected abort'); } }), { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test('managed credentials reject malformed response shapes and non-string credentials', async () => {
|
||||
const expiresAt = Date.now() / 1000 + 3600;
|
||||
const turn = { urls: 'turn:localhost:3478', username: 'user', credential: 'password' };
|
||||
for (const body of [
|
||||
null,
|
||||
[],
|
||||
{ expiresAt, iceServers: {} },
|
||||
{ expiresAt, iceServers: [null] },
|
||||
{ expiresAt, iceServers: [{ ...turn, urls: [null] }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, urls: [] }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, username: 123 }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, credential: {} }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, urls: 'turn:bad host' }] },
|
||||
]) {
|
||||
await assert.rejects(fetchTurnOptions({ allowTurn: true, managedTurn: true }, '/api/ice-servers', {
|
||||
fetchImpl: async () => ({ ok: true, json: async () => body }),
|
||||
}), /credentials|TURN opt-in/);
|
||||
}
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createIdentity, hello, signIdentity, verifyIdentity, parseHello, type IdentityContext } from '../src/lib/identity.ts';
|
||||
const fingerprint = (byte: string) => Array(32).fill(byte).join(' ');
|
||||
async function setup() {
|
||||
const first = await createIdentity(), second = await createIdentity();
|
||||
const context: IdentityContext = { offer: hello(first), answer: hello(second), offerFingerprint: fingerprint('AA'), answerFingerprint: fingerprint('BB') };
|
||||
return { first, second, context };
|
||||
}
|
||||
test('device proof binds both keys, fresh nonces, roles, and both DTLS fingerprints', async () => {
|
||||
const { first, second, context } = await setup();
|
||||
const proof = await signIdentity(first, context, true);
|
||||
await verifyIdentity(proof, context, true);
|
||||
await verifyIdentity(await signIdentity(second, context, false), context, false);
|
||||
await assert.rejects(verifyIdentity(proof, context, false));
|
||||
for (const changed of [
|
||||
{ ...context, offer: hello(first) }, { ...context, answer: hello(second) },
|
||||
{ ...context, offer: hello(second) }, { ...context, answer: hello(first) },
|
||||
{ ...context, offerFingerprint: fingerprint('CC') }, { ...context, answerFingerprint: fingerprint('CC') },
|
||||
]) await assert.rejects(verifyIdentity(proof, changed, true));
|
||||
const imposter = await createIdentity();
|
||||
await assert.rejects(signIdentity(imposter, context, true));
|
||||
await assert.rejects(verifyIdentity('00'.repeat(64), context, true));
|
||||
});
|
||||
test('identity input is bounded', async () => {
|
||||
const identity = await createIdentity();
|
||||
assert.throws(() => parseHello({ key: identity.publicKey, nonce: 'bad' }));
|
||||
assert.throws(() => parseHello({ key: 'ff'.repeat(65), nonce: '00'.repeat(32) }));
|
||||
});
|
||||
test('device private keys cannot be extracted and still sign after storage cloning', async () => {
|
||||
const { first, context } = await setup();
|
||||
const stored = structuredClone(first);
|
||||
assert.equal(stored.privateKey.extractable, false);
|
||||
await assert.rejects(crypto.subtle.exportKey('jwk', stored.privateKey));
|
||||
await verifyIdentity(await signIdentity(stored, context, true), context, true);
|
||||
});
|
||||
@@ -1,119 +0,0 @@
|
||||
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'); }
|
||||
});
|
||||
@@ -1,172 +0,0 @@
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { FileSession, QUEUE_LIMIT, type SessionCallbacks, type QueueItem } from '../src/lib/session.ts';
|
||||
import type { TransferChannel, TransferResult, TransferState } from '../src/lib/transfer.ts';
|
||||
|
||||
class Channel extends EventTarget implements TransferChannel {
|
||||
binaryType: BinaryType = 'arraybuffer';
|
||||
bufferedAmountLowThreshold = 0;
|
||||
bufferedAmount = 0;
|
||||
readyState: RTCDataChannelState = 'open';
|
||||
onopen: TransferChannel['onopen'] = null;
|
||||
onmessage: TransferChannel['onmessage'] = null;
|
||||
onclose: TransferChannel['onclose'] = null;
|
||||
onerror: TransferChannel['onerror'] = null;
|
||||
peer: Channel | null = null;
|
||||
frames: (string | ArrayBuffer)[] = [];
|
||||
send(data: string | ArrayBuffer) { this.frames.push(data); queueMicrotask(() => this.peer?.onmessage?.(new MessageEvent('message', { data }))); }
|
||||
close() { this.readyState = 'closed'; this.dispatchEvent(new Event('close')); }
|
||||
}
|
||||
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, 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 };
|
||||
}
|
||||
function pair(t: TestContext) {
|
||||
const a = new Channel(), b = new Channel(); a.peer = b; b.peer = a;
|
||||
const first = side(a, true), second = side(b, false);
|
||||
t.after(() => { first.session.close(); second.session.close(); });
|
||||
return { first, second };
|
||||
}
|
||||
|
||||
test('queues remain private until both peers verify, then require per-file acceptance', async t => {
|
||||
const { first, second } = pair(t);
|
||||
first.session.add([file('one'), file('two', 0)]);
|
||||
first.session.verify(); await tick();
|
||||
assert.equal(first.channel.frames.length, 1); assert.equal(second.state.receive, '');
|
||||
second.session.verify(); await until(() => second.state.receive === 'choose-storage');
|
||||
assert.equal(first.state.send, 'waiting-accept');
|
||||
second.session.accept(); await until(() => first.state.results.length === 1 && second.state.receive === 'choose-storage');
|
||||
assert.equal(first.state.send, 'waiting-accept');
|
||||
second.session.accept(); await until(() => first.state.results.length === 2);
|
||||
assert.deepEqual(second.state.results.map(item => item.result.meta.name), ['one', 'two']);
|
||||
assert.equal(second.state.results[1]!.result.blob!.size, 0);
|
||||
assert.deepEqual(first.state.errors, []); assert.deepEqual(second.state.errors, []);
|
||||
});
|
||||
|
||||
test('simultaneous bidirectional queues have isolated bytes, receipts and destinations', async t => {
|
||||
const { first, second } = pair(t);
|
||||
first.session.add([file('a', 40000), file('b')]); second.session.add([file('c', 20000), file('d', 0)]);
|
||||
first.session.verify(); second.session.verify();
|
||||
for (let index = 0; index < 2; index++) {
|
||||
await until(() => first.state.receive === 'choose-storage' && second.state.receive === 'choose-storage');
|
||||
first.session.accept(); second.session.accept();
|
||||
await until(() => first.state.results.length >= (index + 1) * 2 && second.state.results.length >= (index + 1) * 2);
|
||||
}
|
||||
for (const side of [first, second]) {
|
||||
for (const { result } of side.state.results.filter(item => item.direction === 'receive')) {
|
||||
assert.ok(new Uint8Array(await result.blob!.arrayBuffer()).every(byte => byte === 42));
|
||||
}
|
||||
assert.deepEqual(side.state.errors, []);
|
||||
}
|
||||
assert.deepEqual(first.state.results.filter(item => item.direction === 'receive').map(item => item.result.meta.name), ['c', 'd']);
|
||||
});
|
||||
|
||||
test('remove pending and decline offered files without ending the session', async t => {
|
||||
const { first, second } = pair(t);
|
||||
first.session.add([file('decline'), file('remove'), file('keep')]);
|
||||
first.session.remove(first.state.queue[1]!.id);
|
||||
first.session.verify(); second.session.verify();
|
||||
await until(() => second.state.receive === 'choose-storage'); second.session.decline();
|
||||
await until(() => first.state.declined.length === 1 && second.state.receive === 'choose-storage');
|
||||
second.session.accept(); await until(() => first.state.results.length === 1);
|
||||
assert.equal(first.state.results[0]!.result.meta.name, 'keep');
|
||||
assert.deepEqual(first.state.declined, ['decline']); assert.equal(first.state.closed, false);
|
||||
});
|
||||
|
||||
test('queue limit is atomic and cancellation aborts both active disk destinations', async t => {
|
||||
const { first, second } = pair(t);
|
||||
assert.throws(() => first.session.add(Array.from({ length: QUEUE_LIMIT + 1 }, () => file('too-many'))), /Queue up to/);
|
||||
assert.equal(first.state.queue.length, 0);
|
||||
first.session.add([file('a')]); second.session.add([file('b')]);
|
||||
first.session.verify(); second.session.verify();
|
||||
await until(() => first.state.receive === 'choose-storage' && second.state.receive === 'choose-storage');
|
||||
let aborted = 0;
|
||||
const destination = () => {
|
||||
let release: (() => void) | undefined;
|
||||
return { write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() { assert.fail('Cancelled destination must not close'); }, async abort() { aborted++; release?.(); } };
|
||||
};
|
||||
first.session.accept(destination()); second.session.accept(destination()); await tick();
|
||||
first.session.close(); second.session.close(); await until(() => aborted === 2);
|
||||
assert.equal(first.state.results.length, 0); assert.equal(second.state.results.length, 0);
|
||||
});
|
||||
|
||||
test('reused file IDs and stale receipts fail closed', async t => {
|
||||
for (const stale of ['start', 'frame']) {
|
||||
const { first, second } = pair(t);
|
||||
first.session.add([file('one', 0)]); first.session.verify(); second.session.verify();
|
||||
await until(() => second.state.receive === 'choose-storage'); second.session.accept();
|
||||
await until(() => first.state.results.length === 1);
|
||||
const target = stale === 'start' ? second : first;
|
||||
target.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: stale, id: 1, data: JSON.stringify({ v: 2, type: 'complete', bytes: 0 }) }) }));
|
||||
await until(() => target.state.closed);
|
||||
assert.equal(target.state.closed, true); assert.equal(target.state.errors.length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('unsolicited offers before verification and excess binary payload fail closed', async t => {
|
||||
const { first, second } = pair(t);
|
||||
first.channel.onmessage?.(new MessageEvent('message', { data: JSON.stringify({ v: 3, type: 'start', id: 2 }) }));
|
||||
second.channel.onmessage?.(new MessageEvent('message', { data: new ArrayBuffer(100000) }));
|
||||
await until(() => first.state.closed && second.state.closed);
|
||||
assert.equal(first.state.closed, true); assert.equal(second.state.closed, true);
|
||||
});
|
||||
|
||||
test('identity proofs gate metadata even when a remembered contact requests automatic verification', async t => {
|
||||
const { first, second } = pair(t);
|
||||
let release!: () => void;
|
||||
const pending = new Promise<void>(resolve => { release = resolve; });
|
||||
first.session.authenticate({ sign: async () => 'sender-proof', verify: async proof => { assert.equal(proof, 'receiver-proof'); await pending; } });
|
||||
second.session.authenticate({ sign: async () => 'receiver-proof', verify: async proof => { assert.equal(proof, 'sender-proof'); await pending; } });
|
||||
first.session.add([file('private-name')]); first.session.verify(); second.session.verify();
|
||||
await tick();
|
||||
assert.equal(first.state.ready, false); assert.equal(second.state.ready, false);
|
||||
assert.doesNotMatch(first.channel.frames.join(''), /private-name/);
|
||||
release(); await until(() => second.state.receive === 'choose-storage');
|
||||
second.session.accept(); await until(() => first.state.results.length === 1);
|
||||
assert.deepEqual(first.state.errors, []); assert.deepEqual(second.state.errors, []);
|
||||
});
|
||||
|
||||
test('invalid or missing identity proof closes the session without releasing file metadata', async t => {
|
||||
const { first, second } = pair(t);
|
||||
first.session.authenticate({ sign: async () => 'proof', verify: async () => { throw new Error('Device proof failed'); } });
|
||||
first.session.add([file('private-name')]); first.session.verify(); second.session.verify();
|
||||
await until(() => first.state.closed);
|
||||
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/);
|
||||
});
|
||||
@@ -1,245 +0,0 @@
|
||||
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,278 +0,0 @@
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import type { TransferChannel, TransferOptions, TransferResult } from '../src/lib/transfer.ts';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Transfer, MEMORY_LIMIT, validateMetadata } from '../src/lib/transfer.ts';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED } from '../src/lib/webrtc.ts';
|
||||
|
||||
class Channel extends EventTarget implements TransferChannel {
|
||||
binaryType: BinaryType = 'arraybuffer';
|
||||
bufferedAmountLowThreshold = 0;
|
||||
peer: Channel | null = null;
|
||||
onopen: TransferChannel['onopen'] = null;
|
||||
onmessage: TransferChannel['onmessage'] = null;
|
||||
onclose: TransferChannel['onclose'] = null;
|
||||
onerror: (() => void) | null = null;
|
||||
readyState: RTCDataChannelState = 'open';
|
||||
bufferedAmount = 0;
|
||||
frames: (string | ArrayBuffer)[] = [];
|
||||
send(data: string | ArrayBuffer) {
|
||||
if (this.readyState !== 'open') throw new Error('closed');
|
||||
this.frames.push(data);
|
||||
queueMicrotask(() => this.peer?.onmessage?.(new MessageEvent('message', { data })));
|
||||
}
|
||||
close() { this.readyState = 'closed'; this.dispatchEvent(new Event('close')); }
|
||||
}
|
||||
const tick = () => new Promise<void>(resolve => setImmediate(resolve));
|
||||
async function until(check: () => boolean) {
|
||||
for (let i = 0; i < 500; i++) { if (check()) return; await tick(); }
|
||||
assert.fail('Condition did not become true');
|
||||
}
|
||||
const message = (transfer: Transfer, type: string, data: Record<string, unknown> = {}) => transfer.enqueue(JSON.stringify({ v: 2, type, ...data }));
|
||||
const meta = (size = 1) => ({ name: 'example.txt', size, mime: 'text/plain' });
|
||||
function receiver(t: TestContext, options: TransferOptions = {}) {
|
||||
const dc = new Channel();
|
||||
const errors: string[] = [];
|
||||
const r = new Transfer(dc, { onError: err => errors.push(err.message), ...options });
|
||||
t.after(() => r.close());
|
||||
return { r, dc, errors };
|
||||
}
|
||||
async function prepared(t: TestContext, size = 1, options: TransferOptions = {}) {
|
||||
const result = receiver(t, options);
|
||||
result.r.verify(); message(result.r, 'ready'); message(result.r, 'meta', meta(size));
|
||||
await result.r.queue;
|
||||
assert.equal(result.r.state, 'choose-storage');
|
||||
return result;
|
||||
}
|
||||
function pair(t: TestContext, size = CHUNK_SIZE * 80 + 3, receiverOptions: TransferOptions = {}) {
|
||||
const a = new Channel(), b = new Channel(); a.peer = b; b.peer = a;
|
||||
const source = new Uint8Array(size); source.fill(123);
|
||||
const file = new File([source], 'payload.bin');
|
||||
const errors: string[] = [];
|
||||
const sender = new Transfer(a, { file, onError: err => errors.push(err.message) });
|
||||
const receiver = new Transfer(b, { onError: err => errors.push(err.message), ...receiverOptions });
|
||||
t.after(() => { sender.close(); receiver.close(); });
|
||||
return { sender, receiver, a, b, source, errors };
|
||||
}
|
||||
|
||||
test('no filename or contents before both explicit verification confirmations', async t => {
|
||||
const { sender, receiver, a } = pair(t);
|
||||
await tick(); assert.equal(a.frames.length, 0);
|
||||
sender.verify(); await tick();
|
||||
assert.deepEqual(a.frames.map(frame => { assert.equal(typeof frame, 'string'); return JSON.parse(frame as string); }).map(m => m.type), ['ready']);
|
||||
receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
assert.deepEqual(a.frames.map(frame => { assert.equal(typeof frame, 'string'); return JSON.parse(frame as string); }).map(m => m.type), ['ready', 'meta']);
|
||||
assert.equal(sender.sent, 0);
|
||||
});
|
||||
|
||||
test('verified, accepted memory transfer preserves bytes and requires receipt ACK', async t => {
|
||||
let result: TransferResult | undefined;
|
||||
const { sender, receiver, source, errors } = pair(t, undefined, { onComplete: value => { result = value; } });
|
||||
sender.verify(); receiver.verify();
|
||||
await until(() => receiver.state === 'choose-storage'); receiver.accept();
|
||||
await until(() => sender.state === 'done');
|
||||
assert.deepEqual(errors, []);
|
||||
assert.ok(result?.blob);
|
||||
assert.deepEqual(new Uint8Array(await result.blob.arrayBuffer()), source);
|
||||
assert.equal(sender.acked, source.length);
|
||||
assert.equal(result.blob.type, 'application/octet-stream');
|
||||
});
|
||||
|
||||
test('empty file still requires acceptance and completion ACK', async t => {
|
||||
const { sender, receiver } = pair(t, 0);
|
||||
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
assert.equal(sender.state, 'waiting-accept');
|
||||
receiver.accept(); await until(() => sender.state === 'done');
|
||||
});
|
||||
|
||||
test('disk transfer waits for storage close before acknowledging completion', async t => {
|
||||
let release: (() => void) | undefined, saved = 0;
|
||||
const { sender, receiver, source } = pair(t);
|
||||
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
receiver.accept({ async write(bytes) { saved += bytes.byteLength; }, close() { return new Promise<void>(resolve => { release = resolve; }); }, async abort() {} });
|
||||
await until(() => receiver.state === 'saving');
|
||||
assert.equal(sender.state, 'awaiting-receipt'); assert.equal(saved, source.length);
|
||||
assert.ok(release); release(); await until(() => sender.state === 'done');
|
||||
});
|
||||
|
||||
test('slow storage bounds the sender to its acknowledged window', async t => {
|
||||
let release: (() => void) | undefined;
|
||||
const { sender, receiver } = pair(t);
|
||||
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
receiver.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
|
||||
await until(() => sender.sent === MAX_BUFFERED);
|
||||
await tick(); assert.equal(sender.acked, 0); assert.equal(sender.sent, MAX_BUFFERED);
|
||||
receiver.close(); sender.close(); release?.();
|
||||
});
|
||||
|
||||
for (const [name, input] of [
|
||||
['malformed JSON', '{broken'],
|
||||
['null JSON', 'null'],
|
||||
['binary data before verification', new ArrayBuffer(1)],
|
||||
['oversized binary message', new ArrayBuffer(CHUNK_SIZE + 1)],
|
||||
['oversized control message', ' '.repeat(2049)],
|
||||
['metadata before verification', JSON.stringify({ v: 2, type: 'meta', ...meta() })],
|
||||
['unsupported message object', {}],
|
||||
]) {
|
||||
test(`rejects ${name}`, async t => {
|
||||
const { r, errors } = receiver(t); r.enqueue(input); await r.queue;
|
||||
assert.equal(r.closed, true); assert.equal(errors.length, 1);
|
||||
});
|
||||
}
|
||||
|
||||
test('rejects duplicate metadata without retaining bytes from another file', async t => {
|
||||
const { r } = await prepared(t); r.accept(); r.enqueue(new ArrayBuffer(1));
|
||||
message(r, 'meta', meta()); await r.queue;
|
||||
assert.equal(r.closed, true); assert.equal(r.chunks.length, 0);
|
||||
});
|
||||
|
||||
test('rejects excess bytes and premature end', async t => {
|
||||
const first = await prepared(t); first.r.accept(); first.r.enqueue(new ArrayBuffer(2)); await first.r.queue;
|
||||
assert.equal(first.r.closed, true);
|
||||
const second = await prepared(t, 2); second.r.accept(); second.r.enqueue(new ArrayBuffer(1)); message(second.r, 'end'); await second.r.queue;
|
||||
assert.equal(second.r.closed, true);
|
||||
});
|
||||
|
||||
test('completed files cannot be extended by later frames', async t => {
|
||||
let completes = 0;
|
||||
const { r } = await prepared(t, 1, { onComplete: () => completes++ });
|
||||
r.accept(); r.enqueue(new ArrayBuffer(1)); message(r, 'end'); await r.queue;
|
||||
assert.equal(r.state, 'done'); r.enqueue(new ArrayBuffer(1)); await r.queue;
|
||||
assert.equal(r.closed, true); assert.equal(completes, 1);
|
||||
});
|
||||
|
||||
test('post-completion transport errors preserve the received file (Firefox shutdown)', async t => {
|
||||
let result: TransferResult | undefined;
|
||||
const { r, dc, errors } = await prepared(t, 1, { onComplete: value => { result = value; } });
|
||||
r.accept(); r.enqueue(Uint8Array.of(123).buffer); message(r, 'end'); await r.queue;
|
||||
assert.equal(r.state, 'done');
|
||||
dc.onerror?.();
|
||||
assert.equal(r.state, 'done'); assert.equal(r.closed, true);
|
||||
assert.deepEqual(errors, []);
|
||||
assert.ok(result?.blob);
|
||||
assert.deepEqual(new Uint8Array(await result.blob.arrayBuffer()), Uint8Array.of(123));
|
||||
});
|
||||
|
||||
test('transport errors before receipt completion remain fatal', async t => {
|
||||
const { r, dc, errors } = await prepared(t, 1);
|
||||
r.accept(); r.enqueue(new ArrayBuffer(1)); await r.queue;
|
||||
dc.onerror?.();
|
||||
assert.equal(r.state, 'closed'); assert.equal(r.chunks.length, 0);
|
||||
assert.deepEqual(errors, ['Data channel failed.']);
|
||||
});
|
||||
|
||||
test('memory limit requires an explicit disk destination for larger files', async t => {
|
||||
const { r } = await prepared(t, MEMORY_LIMIT + 1);
|
||||
assert.throws(() => r.accept(), /direct-to-disk/);
|
||||
assert.equal(r.state, 'choose-storage');
|
||||
});
|
||||
|
||||
test('metadata rejects invalid sizes, misleading names and invalid types', () => {
|
||||
for (const size of [-1, 0.5, '10', NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) assert.throws(() => validateMetadata({ ...meta(), size }));
|
||||
for (const name of ['', '../secret', 'a\\b', 'bad\u202efile.exe', 'a'.repeat(256)]) assert.throws(() => validateMetadata({ ...meta(), name }));
|
||||
assert.throws(() => validateMetadata({ ...meta(), mime: {} }));
|
||||
});
|
||||
|
||||
test('cancellation aborts pending disk writes and drops retained buffers', async t => {
|
||||
let aborted = false;
|
||||
let release: (() => void) | undefined;
|
||||
const { r } = await prepared(t);
|
||||
r.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { aborted = true; release?.(); } });
|
||||
r.enqueue(new ArrayBuffer(1)); await tick(); r.close(); await r.queue;
|
||||
assert.equal(aborted, true); assert.equal(r.chunks.length, 0); assert.equal(r.received, 0);
|
||||
});
|
||||
|
||||
test('peer flooding exceeds bounded queue and aborts storage', async t => {
|
||||
let release: (() => void) | undefined;
|
||||
const { r } = await prepared(t, MEMORY_LIMIT);
|
||||
r.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
|
||||
r.enqueue(new ArrayBuffer(CHUNK_SIZE)); await tick();
|
||||
for (let i = 0; i < 130; i++) r.enqueue(new ArrayBuffer(CHUNK_SIZE));
|
||||
assert.equal(r.closed, true); release?.(); await r.queue;
|
||||
});
|
||||
|
||||
test('stalled transfers time out rather than reporting completion', async t => {
|
||||
const { r, errors } = await prepared(t, 1, { timeout: 10 });
|
||||
r.accept(); await new Promise<void>(resolve => setTimeout(resolve, 30));
|
||||
assert.equal(r.closed, true); assert.match(errors[0], /timed out/);
|
||||
});
|
||||
|
||||
test('storage failure never sends successful receipt', async t => {
|
||||
const { r, dc } = await prepared(t);
|
||||
r.accept({ async write() { throw new Error('Disk full'); }, async close() {}, async abort() {} });
|
||||
r.enqueue(new ArrayBuffer(1)); message(r, 'end'); await r.queue;
|
||||
assert.equal(r.closed, true); assert.equal(dc.frames.some(frame => typeof frame === 'string' && JSON.parse(frame).type === 'complete'), false);
|
||||
});
|
||||
|
||||
test('tiny chunks cannot bypass the memory cap through per-chunk overhead', async t => {
|
||||
const { r, errors } = await prepared(t, CHUNK_SIZE * 2);
|
||||
r.accept(); r.enqueue(new ArrayBuffer(1)); await r.queue;
|
||||
assert.equal(r.closed, true); assert.match(errors[0], /chunk size/);
|
||||
});
|
||||
|
||||
test('forged completion or invalid byte acknowledgments cannot report success', async t => {
|
||||
const first = pair(t);
|
||||
first.sender.verify(); first.receiver.verify();
|
||||
await until(() => first.receiver.state === 'choose-storage');
|
||||
message(first.sender, 'complete', { bytes: first.source.length }); await first.sender.queue;
|
||||
assert.equal(first.sender.state, 'closed');
|
||||
const second = pair(t);
|
||||
second.sender.verify(); second.receiver.verify();
|
||||
await until(() => second.receiver.state === 'choose-storage');
|
||||
// Accept without allowing the real receiver to process file data, then forge an ACK.
|
||||
second.b.onmessage = null;
|
||||
message(second.sender, 'accept');
|
||||
await until(() => second.sender.sent >= CHUNK_SIZE);
|
||||
message(second.sender, 'ack', { bytes: 1 }); await second.sender.queue;
|
||||
assert.equal(second.sender.state, 'closed');
|
||||
});
|
||||
|
||||
test('metadata accepts files above 64 GiB while preserving exact byte counts', () => {
|
||||
for (const size of [64 * 1024 ** 3 + 1, 1024 ** 4, Number.MAX_SAFE_INTEGER]) {
|
||||
assert.equal(validateMetadata({ ...meta(), size }).size, size);
|
||||
}
|
||||
});
|
||||
|
||||
test('consecutive files reuse verification, reset counts, and require separate acceptance', async t => {
|
||||
const results: TransferResult[] = [];
|
||||
const { sender, receiver, a, errors } = pair(t, 33, { onComplete: result => results.push(result) });
|
||||
sender.verify(); receiver.verify();
|
||||
await until(() => receiver.state === 'choose-storage'); receiver.accept();
|
||||
await until(() => sender.state === 'done');
|
||||
assert.equal(sender.canSendAnother, true);
|
||||
for (const bytes of [new Uint8Array(0), Uint8Array.of(1, 2, 3)]) {
|
||||
sender.sendAnother(new File([bytes], 'next.bin'));
|
||||
await until(() => receiver.state === 'choose-storage');
|
||||
assert.equal(sender.sent, 0); assert.equal(sender.acked, 0); assert.equal(receiver.received, 0);
|
||||
assert.throws(() => sender.sendAnother(new File([], 'early.bin')), /new connection/);
|
||||
receiver.accept(); await until(() => sender.state === 'done');
|
||||
assert.deepEqual(new Uint8Array(await results.at(-1)!.blob!.arrayBuffer()), bytes);
|
||||
}
|
||||
assert.equal(results.length, 3);
|
||||
assert.equal(a.frames.filter(frame => typeof frame === 'string' && JSON.parse(frame).type === 'ready').length, 1);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('legacy readiness retains single-file sender behavior', async t => {
|
||||
const { sender, b } = pair(t, 0);
|
||||
b.onmessage = null;
|
||||
sender.verify(); message(sender, 'ready'); await sender.queue;
|
||||
message(sender, 'accept'); await sender.queue;
|
||||
message(sender, 'complete', { bytes: 0 }); await sender.queue;
|
||||
assert.equal(sender.state, 'done'); assert.equal(sender.closed, true);
|
||||
assert.equal(sender.canSendAnother, false);
|
||||
});
|
||||
|
||||
test('next disk transfer never reuses or aborts the completed destination', async t => {
|
||||
let writes = 0, closes = 0, aborts = 0;
|
||||
const { sender, receiver } = pair(t, 1);
|
||||
sender.verify(); receiver.verify();
|
||||
await until(() => receiver.state === 'choose-storage');
|
||||
receiver.accept({ async write() { writes++; }, async close() { closes++; }, async abort() { aborts++; } });
|
||||
await until(() => sender.state === 'done');
|
||||
sender.sendAnother(new File([Uint8Array.of(9)], 'next.bin'));
|
||||
await until(() => receiver.state === 'choose-storage');
|
||||
receiver.accept({ async write() { throw new Error('Disk full'); }, async close() { assert.fail('Must not close failed storage'); }, async abort() {} });
|
||||
await until(() => receiver.closed);
|
||||
assert.equal(writes, 1); assert.equal(closes, 1); assert.equal(aborts, 0);
|
||||
assert.notEqual(sender.state, 'done');
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { iceConfiguration, validateDescription, getFingerprints, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.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`;
|
||||
|
||||
test('TURN is absent by default and dormant credentials cannot enable it', () => {
|
||||
assert.deepEqual(iceConfiguration(), { iceServers: [] });
|
||||
const settings = { stunUrl: 'stun:example.com:3478', turnUrl: 'turn:relay.example', username: 'user', credential: 'secret' };
|
||||
assert.equal(iceConfiguration(settings).iceServers.length, 1);
|
||||
assert.equal(iceConfiguration({ ...settings, allowTurn: true }).iceServers.length, 2);
|
||||
assert.throws(() => iceConfiguration({ stunUrl: 'turn:relay.example' }));
|
||||
assert.throws(() => iceConfiguration({ allowTurn: true }));
|
||||
});
|
||||
|
||||
test('remote relay candidates require local explicit opt-in', () => {
|
||||
const relayed = sdp + 'a=candidate:1 1 udp 10 192.0.2.1 5000 typ relay raddr 0.0.0.0 rport 0\r\n';
|
||||
assert.throws(() => validateDescription(relayed), /explicitly enable TURN/);
|
||||
assert.equal(validateDescription(relayed, { allowTurn: true }), validateDescription(sdp));
|
||||
});
|
||||
|
||||
test('fingerprints show all 32 bytes and reject ambiguous descriptions', () => {
|
||||
const expected = fingerprint.toUpperCase().replaceAll(':', ' ');
|
||||
assert.equal(validateDescription(sdp), expected);
|
||||
assert.deepEqual(getFingerprints({ localDescription: { sdp }, remoteDescription: { sdp } }), { local: expected, remote: expected });
|
||||
assert.throws(() => validateDescription(sdp + `a=fingerprint:sha-256 ${fingerprint}\r\n`));
|
||||
assert.throws(() => validateDescription(sdp.replace(fingerprint, 'AA:BB:CC:DD:EE')));
|
||||
assert.throws(() => validateDescription(sdp + 'm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n'));
|
||||
});
|
||||
|
||||
test('descriptions are bounded and printable', () => {
|
||||
assert.throws(() => validateDescription(sdp + 'a'.repeat(MAX_SIGNAL_LENGTH)), /Invalid connection description/);
|
||||
assert.throws(() => validateDescription(sdp + 'a=x:\u00e9\r\n'), /Invalid connection description/);
|
||||
assert.throws(() => validateDescription(42), /Invalid connection description/);
|
||||
});
|
||||
|
||||
class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; }
|
||||
|
||||
test('ICE gathering waits for completion, rejects timeout, and supports cancellation', async () => {
|
||||
const pc = new Peer();
|
||||
const completed = waitForIceComplete(pc, { timeout: 100 });
|
||||
pc.iceGatheringState = 'complete'; pc.dispatchEvent(new Event('icegatheringstatechange')); await completed;
|
||||
await assert.rejects(waitForIceComplete(new Peer(), { timeout: 5 }), /timed out/);
|
||||
const controller = new AbortController();
|
||||
const cancelled = waitForIceComplete(new Peer(), { signal: controller.signal }); controller.abort();
|
||||
await assert.rejects(cancelled, /cancelled/);
|
||||
});
|
||||
|
||||
test('buffer wait resolves when already drained and rejects close or cancellation', async () => {
|
||||
const channel = new class extends EventTarget {
|
||||
readyState: RTCDataChannelState = 'open';
|
||||
bufferedAmount = 0;
|
||||
bufferedAmountLowThreshold = 0;
|
||||
}();
|
||||
await waitForBufferDrain(channel);
|
||||
channel.bufferedAmount = MAX_BUFFERED + 1;
|
||||
const wait = waitForBufferDrain(channel); channel.readyState = 'closed'; channel.dispatchEvent(new Event('close'));
|
||||
await assert.rejects(wait, /interrupted/);
|
||||
channel.readyState = 'open'; const controller = new AbortController();
|
||||
const cancelled = waitForBufferDrain(channel, { signal: controller.signal }); controller.abort();
|
||||
await assert.rejects(cancelled, /interrupted/);
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
*
|
||||
!package.json
|
||||
!package-lock.json
|
||||
!server.mjs
|
||||
!healthcheck.mjs
|
||||
!test.mjs
|
||||
@@ -1,24 +0,0 @@
|
||||
# Official Node image; update the digest deliberately alongside tracker checks.
|
||||
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS dependencies
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
# Only the server entry point is used. Native client/optional accelerators and
|
||||
# package lifecycle scripts are unnecessary for WebSocket tracker operation.
|
||||
RUN npm ci --omit=dev --omit=optional --ignore-scripts --no-audit --no-fund \
|
||||
&& npm cache clean --force
|
||||
|
||||
FROM dependencies AS test
|
||||
COPY server.mjs healthcheck.mjs test.mjs ./
|
||||
USER node
|
||||
CMD ["node", "--test", "test.mjs"]
|
||||
|
||||
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS runtime
|
||||
ENV NODE_ENV=production PORT=8000 DEBUG=""
|
||||
WORKDIR /app
|
||||
COPY --from=dependencies /app/node_modules ./node_modules
|
||||
COPY package.json server.mjs healthcheck.mjs ./
|
||||
USER node
|
||||
EXPOSE 8000
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["node", "healthcheck.mjs"]
|
||||
CMD ["node", "server.mjs"]
|
||||
@@ -1,126 +0,0 @@
|
||||
# HellCon WebTorrent tracker container
|
||||
|
||||
Our Dockerfile builds directly from the official Node image and the upstream
|
||||
`bittorrent-tracker` npm package. The Node base is pinned by digest, the tracker
|
||||
by version (11.2.3), and transitive dependencies by `package-lock.json`. There
|
||||
is no third-party tracker image, Trystero dependency or browser package change.
|
||||
|
||||
The tracker container is implemented. HellCon's automatic reconnect UI and
|
||||
client adapter are still [planned](../docs/webtorrent-reconnect.md); starting
|
||||
this service does not change the app's current manual-code connection flow.
|
||||
|
||||
## Local development
|
||||
|
||||
Start Docker, then run from the repository root:
|
||||
|
||||
```sh
|
||||
bun run tracker:up
|
||||
bun run test:tracker
|
||||
docker compose -f compose.tracker.yaml logs --tail=30 tracker
|
||||
bun run tracker:down
|
||||
```
|
||||
|
||||
The service listens at `ws://127.0.0.1:8000`. Choose a different host port with
|
||||
`TRACKER_PORT=8001 bun run tracker:up`. Compose builds our Dockerfile and waits for
|
||||
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, 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
|
||||
limits (including pipelined frames), idle timeouts, origins, untrusted and
|
||||
trusted forwarded IP headers and IPv6 prefix grouping. Tests do not depend on public trackers. They establish tracker
|
||||
interoperability, not a complete browser reconnect or Internet NAT test.
|
||||
|
||||
If you started Docker only for these checks, stop it afterward:
|
||||
|
||||
```sh
|
||||
sudo systemctl stop docker.service docker.socket containerd.service
|
||||
```
|
||||
|
||||
## VPS deployment
|
||||
|
||||
Use the same Dockerfile and `compose.tracker.yaml`. The service binds its host
|
||||
port to loopback; an HTTPS reverse proxy on the host terminates TLS and forwards
|
||||
WebSocket upgrades to port 8000. A Caddy example for a dedicated hostname:
|
||||
|
||||
```caddyfile
|
||||
tracker.example.com {
|
||||
reverse_proxy 127.0.0.1:8000
|
||||
}
|
||||
```
|
||||
|
||||
Clients then use `wss://tracker.example.com`. Keep access logging disabled for
|
||||
this endpoint, including any logging configured elsewhere. If the proxy is
|
||||
containerized, use a shared private Docker network and the service name instead
|
||||
of the proxy container's loopback address.
|
||||
|
||||
Set `TRACKER_ALLOWED_ORIGINS=https://your-app.example` for browser origin checks.
|
||||
These checks are not client authentication. The wrapper rate-limits the socket's
|
||||
source IP by default. For a proxy deployment, set `TRACKER_TRUSTED_PROXY_IPS` to
|
||||
the exact source addresses the tracker sees from your proxy. The wrapper uses
|
||||
the rightmost `X-Forwarded-For` entry, which must be the address your proxy saw;
|
||||
proxies that replace the header (Caddy's default) or append to it both work.
|
||||
Docker bridge addresses can differ from `127.0.0.1`. Without this configuration, all proxied
|
||||
clients share the proxy IP's limits. Never expose the backend directly while
|
||||
trusting arbitrary forwarded headers.
|
||||
|
||||
Production restart behavior is an explicit operator choice. For example, add a
|
||||
Compose override containing `services: {tracker: {restart: unless-stopped}}` and
|
||||
pass it after `-f compose.tracker.yaml`. This does not change local development's
|
||||
no-restart policy. This repository does not deploy DNS, TLS or the proxy for you.
|
||||
|
||||
## Configuration
|
||||
|
||||
Pass these environment variables to the container. The Compose file exposes
|
||||
the origin/proxy settings through the `TRACKER_` variables above; use an override
|
||||
file for the other container settings.
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `PORT` | `8000` | Internal HTTP/WebSocket port; keep Compose mapping in sync |
|
||||
| `ANNOUNCE_INTERVAL_SECONDS` | `5` | Interval advertised to WebSocket clients |
|
||||
| `MAX_PAYLOAD_BYTES` | `131072` | Maximum WebSocket message size |
|
||||
| `MAX_CONNECTIONS` | `200` | Global WebSocket connection cap |
|
||||
| `MAX_CONNECTIONS_PER_IP` | `8` | Connections per effective source IP; IPv6 per /64 |
|
||||
| `MESSAGES_PER_MINUTE` | `120` | Handshake attempts and incoming messages per IP or /64 |
|
||||
| `MAX_SWARMS` | `1000` | Discovery identifiers admitted at once |
|
||||
| `MAX_PEERS_PER_SWARM` | `32` | Upstream LRU peer-cache bound; excess peers evict older entries |
|
||||
| `PEER_TTL_SECONDS` | `300` | Idle socket timeout and peer cache lifetime |
|
||||
| `ALLOWED_ORIGINS` | empty | Comma-separated browser origins; empty permits all |
|
||||
| `TRUSTED_PROXY_IPS` | empty | Exact proxy source IPs allowed to supply forwarded addresses |
|
||||
|
||||
The container runs as the unprivileged Node user. Compose applies a read-only
|
||||
filesystem, drops capabilities, prevents privilege escalation and bounds CPU,
|
||||
memory and process count. No persistent volume is required. Stale sockets,
|
||||
expired swarm memberships, empty swarms and expired rate buckets are cleaned
|
||||
periodically. `/healthz` returns 204; other ordinary HTTP routes return 404.
|
||||
UDP and HTTP tracker APIs,
|
||||
public statistics and WebSocket scrape requests are disabled.
|
||||
|
||||
The wrapper emits a startup line and generic fatal server errors, not peer IDs,
|
||||
IPs, payloads or upstream warning text. Leave `DEBUG` empty. The operator can
|
||||
still observe connection metadata; this is not an anonymity service.
|
||||
|
||||
## Updating
|
||||
|
||||
Update `tracker/package.json` deliberately, regenerate the lockfile, and rerun
|
||||
`bun run test:tracker` before rebuilding the runtime image. With npm available:
|
||||
|
||||
```sh
|
||||
npm install --package-lock-only --ignore-scripts --prefix tracker
|
||||
```
|
||||
|
||||
Alternatively run npm inside the official Node image with this directory mounted
|
||||
as its workdir. The image build uses `npm ci --omit=dev --omit=optional
|
||||
--ignore-scripts`; native client components and optional accelerators are not
|
||||
needed by the server entry point. The wrapper uses pinned upstream connection
|
||||
hooks, so review those hooks when upgrading the tracker. Update the official
|
||||
Node image digest in both Dockerfile stages for base-image security updates.
|
||||
|
||||
Sources: [upstream tracker](https://github.com/webtorrent/bittorrent-tracker),
|
||||
[official Node container](https://github.com/nodejs/docker-node).
|
||||
@@ -1,4 +0,0 @@
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${process.env.PORT || 8000}/healthz`, { signal: AbortSignal.timeout(2000) });
|
||||
process.exit(response.status === 204 ? 0 : 1);
|
||||
} catch { process.exit(1); }
|
||||
Generated
-1055
File diff suppressed because it is too large.
Load diff
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"name": "hellcon-tracker",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node server.mjs",
|
||||
"test": "node --test test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"bittorrent-tracker": "11.2.3"
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
import { isIP } from 'node:net';
|
||||
import Server from 'bittorrent-tracker/server';
|
||||
|
||||
function integer(name, fallback, max = 1_000_000) {
|
||||
const value = Number(process.env[name] ?? fallback);
|
||||
if (!Number.isSafeInteger(value) || value < 1 || value > max) throw new Error(`Invalid ${name}`);
|
||||
return value;
|
||||
}
|
||||
const port = integer('PORT', 8000, 65535);
|
||||
const interval = integer('ANNOUNCE_INTERVAL_SECONDS', 5, 600);
|
||||
const maxPayload = integer('MAX_PAYLOAD_BYTES', 128 * 1024);
|
||||
const maxConnections = integer('MAX_CONNECTIONS', 200);
|
||||
const maxPerIp = integer('MAX_CONNECTIONS_PER_IP', 8);
|
||||
const maxMessages = integer('MESSAGES_PER_MINUTE', 120);
|
||||
const maxSwarms = integer('MAX_SWARMS', 1000);
|
||||
const maxPeers = integer('MAX_PEERS_PER_SWARM', 32);
|
||||
const peerAge = integer('PEER_TTL_SECONDS', 300);
|
||||
const list = name => (process.env[name] || '').split(',').map(item => item.trim()).filter(Boolean);
|
||||
const normalizeIp = ip => ip?.replace(/^::ffff:/, '') || '';
|
||||
const origins = new Set(list('ALLOWED_ORIGINS'));
|
||||
const proxies = new Set(list('TRUSTED_PROXY_IPS').map(normalizeIp));
|
||||
const clientsPerIp = new Map();
|
||||
const rates = new Map();
|
||||
const admittedSwarms = new Set();
|
||||
|
||||
function allowRequest(ip) {
|
||||
const now = Date.now();
|
||||
let bucket = rates.get(ip);
|
||||
if (!bucket || now >= bucket.until) {
|
||||
bucket = { count: 0, until: now + 60_000 };
|
||||
rates.set(ip, bucket);
|
||||
}
|
||||
return ++bucket.count <= maxMessages;
|
||||
}
|
||||
function clientIp(req) {
|
||||
const remote = normalizeIp(req.socket.remoteAddress);
|
||||
const forwarded = req.headers['x-forwarded-for'];
|
||||
if (proxies.has(remote) && typeof forwarded === 'string') {
|
||||
// The trusted proxy's observed address is last; earlier entries are client-supplied.
|
||||
const last = forwarded.split(',').at(-1).trim();
|
||||
if (isIP(last)) return normalizeIp(last);
|
||||
}
|
||||
return remote;
|
||||
}
|
||||
// IPv6 hosts commonly control a whole /64, so limits apply per prefix.
|
||||
function limitKey(ip) {
|
||||
if (isIP(ip) !== 6) return ip;
|
||||
const [head, tail] = ip.replace(/%.*$/, '').split('::');
|
||||
// An embedded IPv4 suffix fills the last two groups, never the prefix.
|
||||
const groups = part => part ? part.split(':').flatMap(group => group.includes('.') ? ['0', '0'] : [group]) : [];
|
||||
const start = groups(head), end = groups(tail);
|
||||
const all = tail === undefined ? start : [...start, ...Array(8 - start.length - end.length).fill('0'), ...end];
|
||||
return all.slice(0, 4).map(group => parseInt(group, 16).toString(16)).join(':') + '::/64';
|
||||
}
|
||||
const binaryId = value => typeof value === 'string' && value.length === 20 && !/[^\x00-\xff]/.test(value);
|
||||
const description = (value, type) => value && value.type === type && typeof value.sdp === 'string' && value.sdp.length <= maxPayload;
|
||||
|
||||
// These hooks are tied to the pinned upstream release. Keep the integration
|
||||
// tests when upgrading: upstream owns routing, this wrapper bounds its input.
|
||||
class Tracker extends Server {
|
||||
onWebSocketConnection(socket, opts) {
|
||||
const ip = socket.upgradeReq.hellconIp;
|
||||
socket.hellconIp = ip;
|
||||
socket.hellconSeen = Date.now();
|
||||
// Upstream records joined swarms only after async routing, so pipelined
|
||||
// frames would all pass a check against socket.infoHashes.
|
||||
socket.hellconHashes = new Set();
|
||||
clientsPerIp.set(ip, (clientsPerIp.get(ip) || 0) + 1);
|
||||
socket.once('close', () => {
|
||||
const remaining = (clientsPerIp.get(ip) || 1) - 1;
|
||||
if (remaining) clientsPerIp.set(ip, remaining);
|
||||
else clientsPerIp.delete(ip);
|
||||
});
|
||||
super.onWebSocketConnection(socket, opts);
|
||||
}
|
||||
|
||||
_onWebSocketRequest(socket, opts, raw) {
|
||||
if (!allowRequest(socket.hellconIp)) { socket.close(1008, 'Rate limit'); return; }
|
||||
let data;
|
||||
try { data = JSON.parse(raw); } catch { socket.close(1008, 'Invalid JSON'); return; }
|
||||
// Scraping can enumerate private discovery identifiers. No scrape API is
|
||||
// exposed, including over WebSocket when HTTP statistics are disabled.
|
||||
if (!data || data.action !== 'announce' || !binaryId(data.info_hash) || !binaryId(data.peer_id) ||
|
||||
(data.event && !['started', 'stopped', 'completed', 'update', 'paused'].includes(data.event)) ||
|
||||
(data.offers !== undefined && (!Array.isArray(data.offers) || data.offers.length > 8 ||
|
||||
data.offers.some(item => !item || !binaryId(item.offer_id) || !description(item.offer, 'offer')))) ||
|
||||
(data.answer !== undefined && (!description(data.answer, 'answer') || !binaryId(data.offer_id) || !binaryId(data.to_peer_id)))) {
|
||||
socket.close(1008, 'Invalid announce'); return;
|
||||
}
|
||||
if (socket.peerId && socket.peerId !== Buffer.from(data.peer_id, 'latin1').toString('hex')) {
|
||||
socket.close(1008, 'Peer ID changed'); return;
|
||||
}
|
||||
const hash = Buffer.from(data.info_hash, 'latin1').toString('hex');
|
||||
if (!socket.hellconHashes.has(hash)) {
|
||||
if (socket.hellconHashes.size >= 4) { socket.close(1008, 'Too many swarms'); return; }
|
||||
socket.hellconHashes.add(hash);
|
||||
}
|
||||
socket.hellconSeen = Date.now();
|
||||
super._onWebSocketRequest(socket, opts, raw);
|
||||
}
|
||||
}
|
||||
|
||||
const server = new Tracker({
|
||||
http: false, udp: false, stats: false, trustProxy: false,
|
||||
// Upstream divides the configured interval by five for WebSocket responses.
|
||||
interval: interval * 5000,
|
||||
peersCacheLength: maxPeers,
|
||||
peersCacheTtl: peerAge * 1000,
|
||||
ws: {
|
||||
clientTracking: true,
|
||||
maxPayload,
|
||||
verifyClient({ req, origin }) {
|
||||
const ip = limitKey(clientIp(req));
|
||||
req.hellconIp = ip;
|
||||
return (!origins.size || origins.has(origin)) &&
|
||||
server.ws.clients.size < maxConnections && (clientsPerIp.get(ip) || 0) < maxPerIp && allowRequest(ip);
|
||||
},
|
||||
},
|
||||
filter(hash, params, done) {
|
||||
if (!admittedSwarms.has(hash) && admittedSwarms.size >= maxSwarms) {
|
||||
done(new Error('Tracker capacity reached')); return;
|
||||
}
|
||||
admittedSwarms.add(hash);
|
||||
done(null);
|
||||
},
|
||||
});
|
||||
|
||||
server.http.on('request', (req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/healthz') {
|
||||
res.writeHead(204, { 'Cache-Control': 'no-store' }); res.end();
|
||||
}
|
||||
});
|
||||
// Never log raw upstream errors: they can contain attacker-controlled fields.
|
||||
server.on('warning', () => {});
|
||||
server.on('error', () => { console.error('Tracker server error'); shutdown(1); });
|
||||
|
||||
const cleanup = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const socket of server.ws.clients) {
|
||||
if (now - socket.hellconSeen > peerAge * 1000) socket.terminate();
|
||||
}
|
||||
for (const hash of admittedSwarms) {
|
||||
const swarm = server.torrents[hash];
|
||||
// Upstream's LRU expires peers only when read; peeking evicts stale entries
|
||||
// through its synthetic 'stopped' handling before the emptiness check.
|
||||
swarm?.peers.keys.forEach(key => swarm.peers.peek(key));
|
||||
if (!swarm || !swarm.peers.keys.length) {
|
||||
delete server.torrents[hash]; admittedSwarms.delete(hash);
|
||||
}
|
||||
}
|
||||
for (const [ip, bucket] of rates) if (now >= bucket.until) rates.delete(ip);
|
||||
}, Math.min(10_000, peerAge * 1000));
|
||||
cleanup.unref();
|
||||
|
||||
let stopping = false;
|
||||
function shutdown(code = 0) {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
clearInterval(cleanup);
|
||||
const deadline = setTimeout(() => process.exit(code), 3000);
|
||||
deadline.unref();
|
||||
for (const socket of server.ws.clients) socket.terminate();
|
||||
server.close(() => process.exit(code));
|
||||
}
|
||||
process.on('SIGTERM', () => shutdown());
|
||||
process.on('SIGINT', () => shutdown());
|
||||
server.listen(port, '0.0.0.0', () => console.log(`WebSocket tracker listening on port ${port}`));
|
||||
@@ -1,284 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { randomBytes, webcrypto } from 'node:crypto';
|
||||
import { createConnection, createServer } from 'node:net';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { test } from 'node:test';
|
||||
|
||||
const id = () => randomBytes(20).toString('latin1');
|
||||
|
||||
async function start(t, env = {}) {
|
||||
const reservation = createServer();
|
||||
await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve));
|
||||
const port = reservation.address().port;
|
||||
await new Promise(resolve => reservation.close(resolve));
|
||||
const child = spawn(process.execPath, ['server.mjs'], {
|
||||
cwd: import.meta.dirname,
|
||||
env: { ...process.env, PORT: String(port), ...env },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
let output = '';
|
||||
child.stdout.on('data', data => { output += data; });
|
||||
child.stderr.on('data', data => { output += data; });
|
||||
const exited = new Promise(resolve => child.once('exit', (code, signal) => resolve({ code, signal })));
|
||||
t.after(async () => {
|
||||
child.kill('SIGTERM');
|
||||
const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
|
||||
const result = await exited;
|
||||
clearTimeout(timer);
|
||||
assert.deepEqual(result, { code: 0, signal: null }, output);
|
||||
assert.match(output, /^WebSocket tracker listening on port \d+\n$/);
|
||||
});
|
||||
const http = `http://127.0.0.1:${port}`;
|
||||
for (let n = 0; n < 100; n++) {
|
||||
if (child.exitCode !== null) throw new Error(output);
|
||||
try {
|
||||
if ((await fetch(http + '/healthz')).status === 204) return { http, ws: `ws://127.0.0.1:${port}` };
|
||||
} catch { /* startup */ }
|
||||
await delay(25);
|
||||
}
|
||||
throw new Error('Tracker did not become healthy: ' + output);
|
||||
}
|
||||
|
||||
async function connect(t, url) {
|
||||
const socket = new WebSocket(url);
|
||||
const frames = [];
|
||||
socket.addEventListener('message', event => frames.push(JSON.parse(event.data)));
|
||||
const closed = new Promise(resolve => socket.addEventListener('close', resolve, { once: true }));
|
||||
t.after(async () => { socket.close(); await closed; });
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.addEventListener('open', resolve, { once: true });
|
||||
socket.addEventListener('error', () => reject(new Error('WebSocket connection failed')), { once: true });
|
||||
});
|
||||
return {
|
||||
socket, closed,
|
||||
send(data) { socket.send(JSON.stringify(data)); },
|
||||
async next(predicate) {
|
||||
for (let n = 0; n < 200; n++) {
|
||||
const index = frames.findIndex(predicate);
|
||||
if (index >= 0) return frames.splice(index, 1)[0];
|
||||
if (socket.readyState === WebSocket.CLOSED) throw new Error('Socket closed before expected frame');
|
||||
await delay(10);
|
||||
}
|
||||
throw new Error('Expected tracker frame did not arrive');
|
||||
},
|
||||
};
|
||||
}
|
||||
const announce = (peer, hash, extra = {}) => ({
|
||||
action: 'announce', info_hash: hash, peer_id: peer, uploaded: 0, downloaded: 0,
|
||||
left: 1, numwant: 0, offers: [], ...extra,
|
||||
});
|
||||
|
||||
for (const offererFirst of [false, true]) {
|
||||
test(`encrypted signaling survives tracker routing, offerer arrives ${offererFirst ? 'first' : 'second'}`, { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t);
|
||||
const first = await connect(t, endpoint.ws);
|
||||
const second = await connect(t, endpoint.ws);
|
||||
const hash = id(), offerId = id(), sender = id(), receiver = id();
|
||||
const key = await webcrypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
// A maximum-size connection code plus envelope metadata must fit after
|
||||
// encryption/base64, even though its sdp field is deliberately opaque.
|
||||
const plaintext = JSON.stringify({ version: 1, code: 'a'.repeat(64 * 1024), nonce: randomBytes(32).toString('hex') });
|
||||
const iv = randomBytes(12);
|
||||
const cipher = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, Buffer.from(plaintext));
|
||||
const encrypted = Buffer.concat([iv, Buffer.from(cipher)]).toString('base64url');
|
||||
const offered = { type: 'offer', sdp: encrypted };
|
||||
const offerFrame = announce(sender, hash, { offers: [{ offer_id: offerId, offer: offered }], numwant: 1 });
|
||||
if (offererFirst) {
|
||||
first.send(offerFrame);
|
||||
const alone = await first.next(frame => frame.interval);
|
||||
assert.equal(alone.complete + alone.incomplete, 1);
|
||||
}
|
||||
second.send(announce(receiver, hash));
|
||||
await second.next(frame => frame.interval);
|
||||
first.send(offerFrame);
|
||||
const offer = await second.next(frame => frame.offer);
|
||||
assert.deepEqual(offer.offer, offered);
|
||||
assert.equal(offer.peer_id, sender);
|
||||
assert.equal(offer.info_hash, hash);
|
||||
assert.equal(offer.offer_id, offerId);
|
||||
const wire = Buffer.from(offer.offer.sdp, 'base64url');
|
||||
const decrypted = await webcrypto.subtle.decrypt({ name: 'AES-GCM', iv: wire.subarray(0, 12) }, key, wire.subarray(12));
|
||||
assert.equal(Buffer.from(decrypted).toString(), plaintext);
|
||||
const answer = { type: 'answer', sdp: encrypted };
|
||||
second.send(announce(receiver, hash, { answer, offer_id: offerId, to_peer_id: sender }));
|
||||
const response = await first.next(frame => frame.answer);
|
||||
assert.deepEqual(response.answer, answer);
|
||||
assert.equal(response.peer_id, receiver);
|
||||
const counts = await first.next(frame => frame.interval);
|
||||
assert.equal(counts.interval, 5);
|
||||
assert.equal(counts.complete + counts.incomplete, 2);
|
||||
second.socket.close();
|
||||
await second.closed;
|
||||
first.send(announce(sender, hash));
|
||||
const afterClose = await first.next(frame => frame.interval);
|
||||
assert.equal(afterClose.complete + afterClose.incomplete, 1);
|
||||
});
|
||||
}
|
||||
|
||||
test('health is public; HTTP APIs, WebSocket scrape and malformed frames are disabled', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t);
|
||||
for (const path of ['/stats', '/stats.json', '/announce', '/scrape']) {
|
||||
assert.equal((await fetch(endpoint.http + path)).status, 404);
|
||||
}
|
||||
for (const payload of [{ action: 'scrape' }, { action: 'announce', info_hash: 'bad' }, null]) {
|
||||
const client = await connect(t, endpoint.ws);
|
||||
client.send(payload);
|
||||
assert.equal((await client.closed).code, 1008);
|
||||
}
|
||||
const badJson = await connect(t, endpoint.ws);
|
||||
badJson.socket.send('{');
|
||||
assert.equal((await badJson.closed).code, 1008);
|
||||
const oversized = await connect(t, endpoint.ws);
|
||||
oversized.socket.send('x'.repeat(128 * 1024 + 1));
|
||||
assert.equal((await oversized.closed).code, 1009);
|
||||
assert.equal((await fetch(endpoint.http + '/healthz')).status, 204);
|
||||
});
|
||||
|
||||
test('swarm capacity and message rate are bounded', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t, { MAX_SWARMS: '1', MESSAGES_PER_MINUTE: '4' });
|
||||
const client = await connect(t, endpoint.ws);
|
||||
const peer = id(), hash = id();
|
||||
client.send(announce(peer, hash));
|
||||
await client.next(frame => frame.interval);
|
||||
client.send(announce(peer, id()));
|
||||
assert.equal((await client.next(frame => frame['failure reason']))['failure reason'], 'Tracker capacity reached');
|
||||
client.send(announce(peer, hash));
|
||||
await client.next(frame => frame.interval);
|
||||
client.send(announce(peer, hash));
|
||||
assert.equal((await client.closed).code, 1008);
|
||||
});
|
||||
|
||||
// Node's WebSocket accepts non-standard headers, which browsers cannot set.
|
||||
const attempt = (t, url, origin, forwarded) => new Promise(resolve => {
|
||||
const headers = {};
|
||||
if (origin) headers.Origin = origin;
|
||||
if (forwarded) headers['X-Forwarded-For'] = forwarded;
|
||||
const socket = new WebSocket(url, { headers });
|
||||
socket.addEventListener('open', () => resolve(socket), { once: true });
|
||||
socket.addEventListener('error', () => resolve(null), { once: true });
|
||||
t.after(() => socket.close());
|
||||
});
|
||||
const closeOf = socket => new Promise(resolve => socket.addEventListener('close', ({ code, reason }) => resolve({ code, reason }), { once: true }));
|
||||
|
||||
// WebSocket clients cannot force several frames into one TCP write, so this
|
||||
// speaks just enough RFC 6455 to pipeline masked text frames.
|
||||
function pipeline(t, url, messages) {
|
||||
const { hostname, port } = new URL(url);
|
||||
const socket = createConnection(Number(port), hostname);
|
||||
t.after(() => socket.destroy());
|
||||
const frame = text => {
|
||||
const payload = Buffer.from(text);
|
||||
const length = payload.length < 126 ? [payload.length] : [126, payload.length >> 8, payload.length & 0xff];
|
||||
// A zero masking key leaves the payload unchanged.
|
||||
return Buffer.concat([Buffer.from([0x81, 0x80 | length[0], ...length.slice(1)]), Buffer.alloc(4), payload]);
|
||||
};
|
||||
socket.write(`GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||
`Sec-WebSocket-Key: ${randomBytes(16).toString('base64')}\r\nSec-WebSocket-Version: 13\r\n\r\n`);
|
||||
return new Promise((resolve, reject) => {
|
||||
let buffer = Buffer.alloc(0), upgraded = false;
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => reject(new Error('Socket closed without a close frame')));
|
||||
socket.on('data', data => {
|
||||
buffer = Buffer.concat([buffer, data]);
|
||||
if (!upgraded) {
|
||||
const end = buffer.indexOf('\r\n\r\n');
|
||||
if (end < 0) return;
|
||||
if (!buffer.toString('latin1', 0, end).startsWith('HTTP/1.1 101')) { reject(new Error('Upgrade refused')); return; }
|
||||
upgraded = true;
|
||||
buffer = buffer.subarray(end + 4);
|
||||
socket.write(Buffer.concat(messages.map(message => frame(JSON.stringify(message)))));
|
||||
}
|
||||
// Server frames are unmasked; tracker replies stay below 64 KiB.
|
||||
while (buffer.length >= 2) {
|
||||
let length = buffer[1] & 0x7f, start = 2;
|
||||
if (length === 126) {
|
||||
if (buffer.length < 4) return;
|
||||
length = buffer.readUInt16BE(2); start = 4;
|
||||
}
|
||||
if (buffer.length < start + length) return;
|
||||
if ((buffer[0] & 0x0f) === 8) {
|
||||
resolve({ code: buffer.readUInt16BE(start), reason: buffer.toString('utf8', start + 2, start + length) });
|
||||
socket.destroy(); return;
|
||||
}
|
||||
buffer = buffer.subarray(start + length);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('origin and per-IP connection checks apply; untrusted forwarded IPs cannot bypass the limit', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t, { ALLOWED_ORIGINS: 'https://other.example , https://hellcon.example', MAX_CONNECTIONS_PER_IP: '1' });
|
||||
assert.equal(await attempt(t, endpoint.ws, 'https://evil.example', '192.0.2.1'), null);
|
||||
const accepted = await attempt(t, endpoint.ws, 'https://hellcon.example', '192.0.2.1');
|
||||
assert.ok(accepted);
|
||||
assert.equal(await attempt(t, endpoint.ws, 'https://hellcon.example', '192.0.2.2'), null);
|
||||
});
|
||||
|
||||
test('trusted proxies supply the rightmost forwarded IP; IPv6 limits apply per /64', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t, { TRUSTED_PROXY_IPS: ' ::ffff:127.0.0.1 ', MAX_CONNECTIONS_PER_IP: '1' });
|
||||
const connect = forwarded => attempt(t, endpoint.ws, undefined, forwarded);
|
||||
assert.ok(await connect('198.51.100.7, 192.0.2.1'));
|
||||
// Spoofed leftmost entries do not create a fresh limit bucket.
|
||||
assert.equal(await connect('198.51.100.8, 192.0.2.1'), null);
|
||||
assert.ok(await connect('192.0.2.2'));
|
||||
assert.ok(await connect('2001:db8::1'));
|
||||
assert.equal(await connect('2001:db8:0:0:ffff::2'), null);
|
||||
assert.equal(await connect('2001:DB8:0000::1.2.3.4'), null);
|
||||
assert.ok(await connect('2001:db8:0:1::1'));
|
||||
});
|
||||
|
||||
test('a socket keeps one peer ID and joins at most four swarms, even with pipelined frames', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t);
|
||||
const sequential = await attempt(t, endpoint.ws);
|
||||
const replies = [];
|
||||
sequential.addEventListener('message', event => replies.push(JSON.parse(event.data)));
|
||||
const peer = id(), hashes = [id(), id(), id(), id()];
|
||||
for (const hash of [...hashes, hashes[0]]) sequential.send(JSON.stringify(announce(peer, hash)));
|
||||
for (let n = 0; replies.filter(frame => frame.interval).length < 5; n++) {
|
||||
assert.ok(n < 200, 'Expected five announce replies');
|
||||
await delay(10);
|
||||
}
|
||||
const fifth = closeOf(sequential);
|
||||
sequential.send(JSON.stringify(announce(peer, id())));
|
||||
assert.deepEqual(await fifth, { code: 1008, reason: 'Too many swarms' });
|
||||
|
||||
const batchPeer = id();
|
||||
const batch = Array.from({ length: 8 }, () => announce(batchPeer, id()));
|
||||
assert.deepEqual(await pipeline(t, endpoint.ws, batch), { code: 1008, reason: 'Too many swarms' });
|
||||
|
||||
const changing = await attempt(t, endpoint.ws);
|
||||
const changed = closeOf(changing);
|
||||
const hash = id();
|
||||
changing.send(JSON.stringify(announce(id(), hash)));
|
||||
changing.send(JSON.stringify(announce(id(), hash)));
|
||||
assert.deepEqual(await changed, { code: 1008, reason: 'Peer ID changed' });
|
||||
});
|
||||
|
||||
test('memberships a live socket stops refreshing expire after the peer TTL', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t, { PEER_TTL_SECONDS: '1' });
|
||||
const active = await connect(t, endpoint.ws);
|
||||
const peer = id(), kept = id(), abandoned = id();
|
||||
active.send(announce(peer, kept));
|
||||
active.send(announce(peer, abandoned));
|
||||
await active.next(frame => frame.interval);
|
||||
await active.next(frame => frame.interval);
|
||||
const keepAlive = setInterval(() => active.send(announce(peer, kept)), 250);
|
||||
t.after(() => clearInterval(keepAlive));
|
||||
await delay(2500);
|
||||
const late = await connect(t, endpoint.ws);
|
||||
late.send(announce(id(), abandoned));
|
||||
const counts = await late.next(frame => frame.interval);
|
||||
assert.equal(counts.complete + counts.incomplete, 1);
|
||||
assert.equal(active.socket.readyState, WebSocket.OPEN);
|
||||
});
|
||||
|
||||
test('idle sockets are terminated after the peer TTL', { timeout: 15000 }, async t => {
|
||||
const endpoint = await start(t, { PEER_TTL_SECONDS: '1' });
|
||||
const client = await connect(t, endpoint.ws);
|
||||
client.send(announce(id(), id()));
|
||||
await client.next(frame => frame.interval);
|
||||
const started = Date.now();
|
||||
assert.equal((await client.closed).code, 1006);
|
||||
assert.ok(Date.now() - started < 3000);
|
||||
});
|
||||
+10
-9
@@ -1,19 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"types": ["node", "vite/client"],
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["vite/client"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"skipLibCheck": true
|
||||
"skipLibCheck": true,
|
||||
"allowJs": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "dev/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "vite.config.ts"]
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "playwright.config.ts", "e2e.spec.ts"]
|
||||
}
|
||||
+26
-14
@@ -1,18 +1,30 @@
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
/// <reference types="vitest/config" />
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { iceMiddleware } from './dev/ice-server.ts';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
// Relative paths let the hosted build work from any static subdirectory.
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env };
|
||||
return {
|
||||
base: './',
|
||||
server: { host: '127.0.0.1' },
|
||||
plugins: [vue(), {
|
||||
name: 'local-turn-credentials',
|
||||
configureServer(server) {
|
||||
if (env.VITE_ICE_ENDPOINT === '/api/ice-servers') server.middlewares.use(iceMiddleware(env));
|
||||
const DEV_STYLE_SRC = "style-src 'self'";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
// index.html's Content-Security-Policy allows no inline styles, the dev server injects the CSS
|
||||
// through JavaScript. A nonce lets only those style elements through, so the dev server enforces
|
||||
// the same policy as the production build, which links the CSS as files.
|
||||
{
|
||||
name: 'dev-csp',
|
||||
apply: 'serve',
|
||||
config: () => ({ html: { cspNonce: 'dev' } }),
|
||||
transformIndexHtml(html) {
|
||||
if (!html.includes(DEV_STYLE_SRC)) throw new Error(`dev-csp: index.html has no "${DEV_STYLE_SRC}"`);
|
||||
return html.replace(DEV_STYLE_SRC, `${DEV_STYLE_SRC} 'nonce-dev'`);
|
||||
},
|
||||
}],
|
||||
};
|
||||
},
|
||||
],
|
||||
// The dev server would inline small images like gitea.svg as data: URLs, which index.html's
|
||||
// Content-Security-Policy blocks. The production build links them as files either way.
|
||||
build: { assetsInlineLimit: 0 },
|
||||
// Relative links, so the build works under any path, not only at the root of a host.
|
||||
base: './',
|
||||
// Playwright runs e2e.spec.ts and backend/, which Vitest would pick up too.
|
||||
test: { include: ['src/**/*.test.ts'] },
|
||||
});
|
||||
Reference in new issue
Block a user