Compare commits
55
Commits
e3af2de051
...
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 | ||
|
|
9f3f21884f | ||
|
|
acba97a7e1 | ||
|
|
3659956967 | ||
|
|
a5935a8324 | ||
|
|
f320bfb541 | ||
|
|
4323a8b774 | ||
|
|
019267cc34 | ||
|
|
43ee7f119f | ||
|
|
8bd37ac8b1 | ||
|
|
da2999ed5d | ||
|
|
4cf2ff5211 | ||
|
|
1b76c7ce01 |
No files matched your search
@@ -1,6 +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
|
|
||||||
@@ -3,3 +3,4 @@ dist
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
test-results
|
||||||
-139
@@ -1,139 +0,0 @@
|
|||||||
# Changelog
|
|
||||||
|
|
||||||
## [0.0.5] - Draft (unreleased)
|
|
||||||
|
|
||||||
### Added
|
|
||||||
|
|
||||||
- Add a messenger-style workspace with a connections sidebar, editable slot
|
|
||||||
names, session status, and a persistent activity timeline per connection.
|
|
||||||
- Preserve live sessions and file selections while switching slots. Save names,
|
|
||||||
paired-device associations, and the last 50 transfer results locally; keep
|
|
||||||
manual reconnection with fresh codes. Add collapsible mobile navigation.
|
|
||||||
- Add opt-in hosted device identities and saved contacts, with fresh mutual
|
|
||||||
signatures bound to both connection fingerprints before remembered verification.
|
|
||||||
- Add contact removal and identity reset.
|
|
||||||
Identity-enabled signaling uses v4; temporary v3 sessions remain available.
|
|
||||||
- Keep verified sessions open for “Send another file”, with separate acceptance
|
|
||||||
and storage for each file.
|
|
||||||
- Preserve the previous memory download until the next file is accepted.
|
|
||||||
- Add bounded queues (32 files per side), sending in both directions, per-file
|
|
||||||
progress and results, queue removal, and incoming-file decline.
|
|
||||||
- Add explicit Disconnect and live Send/Receive navigation. The initial receiver
|
|
||||||
can use Send to add files without reconnecting. Disconnect
|
|
||||||
aborts unfinished writes while preserving the last completed memory download.
|
|
||||||
- Document the hosted-first, serverless UX roadmap.
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
|
|
||||||
- Each connection now remembers its own device instead of picking from a global
|
|
||||||
contact list. Opt in per connection; after manual fingerprint comparison,
|
|
||||||
“Remember this device for …” (ticked by default) pairs the verified peer.
|
|
||||||
A changed key is only replaced on explicit choice. Saved contacts are no
|
|
||||||
longer read.
|
|
||||||
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers
|
|
||||||
must update; v2 codes are rejected before connection setup.
|
|
||||||
- New device identity private keys are non-extractable.
|
|
||||||
- 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.
|
|
||||||
|
|
||||||
### 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,390 +1,176 @@
|
|||||||
# HellCon
|
# HellCon
|
||||||
|
|
||||||
Current version: **0.0.5** (draft). See the [changelog](CHANGELOG.md) for release notes
|
Send a file straight from one browser to another. No account, no upload, no app to install, and no
|
||||||
and compatibility changes.
|
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. No accounts, signaling
|
## How to send a file
|
||||||
backend, or server-side file storage. You exchange connection codes manually.
|
|
||||||
Direct connections are the default. TURN relaying is optional and requires
|
|
||||||
explicit opt-in by both people; no relay is configured automatically.
|
|
||||||
|
|
||||||
## Connections workspace
|
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.
|
||||||
|
|
||||||
The sidebar holds your connections, starting with **Con 1**. Use **Add connection**
|
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
|
||||||
for another empty slot. Edit the name directly in the header; it saves when you
|
tab was doing.
|
||||||
leave the field or press Enter. Empty names revert to the previous name.
|
|
||||||
Use **Remove** beside the name to open a confirmation dialog. Confirming removal
|
|
||||||
ends that slot's sessions in open tabs and forgets its remembered device;
|
|
||||||
downloaded files and your device identity remain. Removing the last slot leaves a fresh **Con 1**.
|
|
||||||
Each slot has its own setup, live session, and activity timeline. Switching slots
|
|
||||||
keeps active transfers and selected files alive while this tab stays open.
|
|
||||||
On small screens, **Show connections** opens the sidebar.
|
|
||||||
|
|
||||||
Connection names, remembered devices, and the last 50 transfer results
|
Both sides need the same protocol, shown at the bottom of the page. A HellCon hosted elsewhere may
|
||||||
per slot are saved in this browser. History includes filenames, sizes, directions,
|
run another one, the receiver then finds no sender, or with **Manual** says the sender runs another
|
||||||
times, and completion/decline/interruption results. It does not save file contents,
|
protocol.
|
||||||
connection codes, or relay credentials. **Reset** clears the current session but
|
|
||||||
keeps the slot and history. Closing or reloading the page ends live sessions and
|
|
||||||
discards selected files; reconnect by exchanging fresh codes. The sidebar reports
|
|
||||||
this tab's session status, not remote device presence.
|
|
||||||
|
|
||||||
Each slot can remember one device. Under **Remembered device**, create the
|
### Without a tracker
|
||||||
browser's device identity once, then opt each slot in. After the first manual
|
|
||||||
fingerprint comparison, **Remember this device for …** (ticked by default) pairs
|
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
|
||||||
the verified peer with that slot; later sessions on it authenticate the peer
|
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
|
||||||
automatically. The slot name is the device's name. **Forget device** unpairs it.
|
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
|
||||||
The same device may be paired with several slots. Clearing site data removes saved
|
**Connect**. The offer and answer contain your network addresses, so only share them with the person
|
||||||
connections and trust. Storage failures are shown explicitly; temporary sessions
|
you're sending to. Both sides then compare the security check (see below) and click **Codes match**.
|
||||||
remain available. Up to 100 connection slots are supported.
|
|
||||||
|
## The security check
|
||||||
|
|
||||||
|
Before anything is transferred, both sides make sure they are connected directly to each other and
|
||||||
|
not to someone who placed themselves in between.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
- your **You** must be their **Peer**, and
|
||||||
|
- your **Peer** must be their **You**.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
|
|
||||||
1. The person starting the connection selects one or more files and configures STUN (PageQuit by default, Google,
|
The file travels over a direct, encrypted WebRTC connection between the two browsers. To set that up,
|
||||||
Cloudflare, a custom provider, or None). They create a code and send it
|
the browsers need two things:
|
||||||
privately to the intended receiver through an authenticated channel. Normal
|
|
||||||
messenger copy/paste is supported; there is no need to transcribe codes.
|
|
||||||
2. The receiver pastes the code, creates an answer, and sends it back. The sender
|
|
||||||
pastes the answer. Gathering waits for completion, up to 30 seconds; a timeout
|
|
||||||
fails rather than quietly exporting incomplete connection information.
|
|
||||||
3. **Both people compare both full SHA-256 certificate fingerprints** over a
|
|
||||||
channel whose authenticity and integrity they trust, such as in person.
|
|
||||||
Your fingerprint must equal their “Their fingerprint”, and vice versa.
|
|
||||||
Compare every byte. Cancel on any mismatch. Both people must explicitly
|
|
||||||
confirm before the app sends the filename, size, MIME metadata, or contents.
|
|
||||||
On later connections, a remembered device’s fresh proof can replace manual
|
|
||||||
comparison (see Remembered devices below).
|
|
||||||
4. The receiver sees the filename and size and clicks **Accept file**. Files of
|
|
||||||
every size stream into the browser's download manager using a same-origin
|
|
||||||
service worker (HTTPS or localhost). This requires transferable streams and
|
|
||||||
service-worker support; Chromium and Brave have been tested with 120 MiB
|
|
||||||
files. Allow the download and keep the receiving tab open. File contents are
|
|
||||||
not uploaded to the web host. Without streaming support, the browser's native
|
|
||||||
save picker asks where to write the file. 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. Even capped memory transfers
|
|
||||||
may be too large on a memory-constrained device.
|
|
||||||
5. The sender waits for a receipt acknowledgment. For disk transfers, the receiver
|
|
||||||
sends this only after its writable stream closes successfully; for streaming
|
|
||||||
downloads, after handing all bytes to the browser; for memory transfers,
|
|
||||||
after constructing the complete download. A streaming receipt does not prove
|
|
||||||
the download manager successfully saved the file: check its final status in
|
|
||||||
Downloads. This also does not prove a human saved a memory download, nor that
|
|
||||||
a malicious receiver told the truth. Streamed transfers have no app-defined size cap; browser, filesystem, and
|
|
||||||
available storage limits apply. Byte counts must remain safe JavaScript integers
|
|
||||||
(at most 2^53 − 1 bytes). Files above 120 MiB have not been tested end to end.
|
|
||||||
|
|
||||||
Once both people verify, either person can add files without new codes or another
|
- **Finding each other.** The code puts both browsers into the same group on a public
|
||||||
fingerprint comparison. Each side can queue up to 32 files (including its active
|
[WebTorrent](https://webtorrent.io/) tracker, which only passes the connection details back and
|
||||||
outgoing file). Each direction transfers one file at a time; sending and receiving
|
forth. They are encrypted with the code, so the tracker can't read them, and neither can anyone
|
||||||
can happen simultaneously. Each file has its own progress, receipt and explicit
|
else in the group without the code. It never sees the file. With the manual exchange you play the
|
||||||
receiver acceptance. **Remove** drops a waiting local queue item; **Decline file**
|
tracker yourself.
|
||||||
rejects an incoming offer and lets the sender's queue continue.
|
- **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.
|
||||||
|
|
||||||
**Disconnect** ends the entire session, drops waiting files and aborts unfinished
|
On the receiving side, HellCon hands the incoming data to the browser's own download manager while
|
||||||
disk writes. To cancel an already active transfer, disconnect; cancelling only an
|
it arrives. That's why files larger than your memory work too, and why the download shows up in
|
||||||
active file is not supported. A completed memory transfer stays available via **Save again** after
|
your browser's download list.
|
||||||
disconnect, until the next acceptance replaces it. **Reset** discards it and
|
|
||||||
returns to setup. Before connecting, Send/Receive chooses who starts the connection. Once
|
|
||||||
verified, these controls navigate to the sending and receiving sections without
|
|
||||||
reconnecting. The initial receiver can click **Send**, then **Add files to send**.
|
|
||||||
|
|
||||||
Keep both tabs open. Switching browser tabs or apps does not explicitly cancel
|
HellCon uses no relay server. If both sides are behind very strict networks, e.g. some company or
|
||||||
the session, although browsers and mobile operating systems can suspend pages.
|
mobile networks, a direct connection may not be possible. And a connection that works isn't
|
||||||
Pending verification/acceptance expires after five minutes; stalled transfers
|
necessarily direct: the other side may name a relay of its own, and a STUN server that reports a
|
||||||
expire after one minute. Idle verified sessions stay open. Lost connections need
|
wrong address can put itself in between. Either only passes on encrypted data. The security check
|
||||||
fresh codes. File transfers use protocol **v3**; pre-v3 connection codes are
|
makes sure the connection ends at the two of you.
|
||||||
rejected before connecting.
|
|
||||||
|
|
||||||
If an answer is rejected as invalid, correct the pasted answer and click Connect
|
## Privacy
|
||||||
again; the sender keeps its existing offer while it is still awaiting an answer.
|
|
||||||
After a connection actually closes or fails, use Reset and exchange a **new offer
|
|
||||||
and new answer**. Old codes refer to the closed connection and cannot reopen it.
|
|
||||||
Reset returns the page to its initial ready state. For a local test, open two
|
|
||||||
separate browser tabs or windows; use Disconnect before changing the setup role. Use the specific error shown in red to diagnose
|
|
||||||
failures; if a configured STUN server is unreachable, try None for a local test.
|
|
||||||
|
|
||||||
### Connection diagnostics and first-version comparison
|
- 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).
|
||||||
|
|
||||||
Expand **Connection diagnostics** to copy the last 80 timed events. The log
|
## Settings
|
||||||
retains local/remote candidate type counts, candidate-pair states, selected
|
|
||||||
route types, DTLS transport states, and ICE check request/response counters after failure.
|
|
||||||
Four snapshots during ICE checking preserve evidence before failed pairs disappear. Final stats
|
|
||||||
are requested before closing the peer, with a 300 ms cleanup bound. A `?` means
|
|
||||||
the browser did not supply a counter; it does not mean zero. Addresses, raw SDP,
|
|
||||||
candidate IDs, credentials, server URLs and filenames are excluded.
|
|
||||||
|
|
||||||
Same-machine success does not establish cross-device connectivity. Error 701
|
Under **Servers** you can change which STUN servers and trackers your browser uses, one address per
|
||||||
alone does not establish the cause of a failed connection. A receiver shutdown
|
line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults**
|
||||||
after both sides report completion can be normal sender cleanup.
|
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.
|
||||||
|
|
||||||
The comparison with the first commit and controlled test results are recorded in
|
The code goes to the tracker mixed with a salt, which changes with the clock every 6 minutes (by UTC):
|
||||||
[the investigation notes](docs/connection-investigation.md). Run the isolated
|
guessing codes ahead of time pays off for 6 minutes at most. The code's last character tells the
|
||||||
ICE experiment with `node scripts/compare-ice.mjs firefox` or replace `firefox`
|
receiver which 6 minutes it was made in, so the two clocks may be up to 3 hours apart. Someone could
|
||||||
with `chromium`. This uses local browser peers and deliberately unusable offer
|
still guess ahead for a particular 6 minutes. If that worries you, turn on **Use own salt** on both
|
||||||
ports plus a 20-second answer delay; it is **not a cross-device test**. Add
|
sides and enter the same salt, agreed on any way you like. **Generate** makes a random one. Nobody
|
||||||
`--normal-candidates` to preserve the real candidate ports. No firewall changes,
|
can guess ahead for a salt they don't know.
|
||||||
TURN credentials or public STUN service are required.
|
|
||||||
|
|
||||||
## Remembered devices
|
Nothing of this is kept, a reload brings back the defaults.
|
||||||
|
|
||||||
On the hosted app, expand **Remembered device** and choose **Create device
|
## Host your own
|
||||||
identity** on both browsers; this also enables **Use my device identity on this
|
|
||||||
connection** for the current slot. Exchange codes and compare both full
|
|
||||||
fingerprints for the first pairing. Leave **Remember this device for …** ticked
|
|
||||||
before confirming, and the verified peer is paired with this connection.
|
|
||||||
|
|
||||||
Later sessions on that connection need no extra steps: HellCon checks fresh
|
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
|
||||||
signed proofs bound to both device keys and both connection fingerprints. A
|
|
||||||
matching paired key replaces manual fingerprint comparison; file acceptance is
|
|
||||||
still required. A changed or missing identity requires manual comparison and
|
|
||||||
only replaces the paired device if you tick **Replace the paired device**.
|
|
||||||
Connection names stay local. Public identities in codes can link sessions.
|
|
||||||
|
|
||||||
Use **Forget device** to unpair a connection, or explicitly delete your identity.
|
|
||||||
Clearing site data loses saved trust and requires pairing again. Browser-stored
|
|
||||||
keys remain usable by trusted app code and are not protection against a malicious
|
|
||||||
host. Each connection keeps its own opt-in; new connections start without it.
|
|
||||||
Storage failure leaves temporary connections available.
|
|
||||||
|
|
||||||
Identity-enabled codes use signaling version **4** and require the new build.
|
|
||||||
Temporary codes retain version **3**. If only one peer enables identity, the
|
|
||||||
current build uses manual comparison without remembering that connection.
|
|
||||||
See [the identity protocol and storage](docs/device-identities.md).
|
|
||||||
|
|
||||||
## Network privacy and optional TURN
|
|
||||||
|
|
||||||
STUN discovers externally reachable addresses. Its operator can see your public
|
|
||||||
IP address and request metadata, but STUN does not relay file contents. Lookups,
|
|
||||||
retries and connectivity checks may involve multiple packets. Choosing None
|
|
||||||
avoids contacting a configured STUN provider; direct connectivity depends on
|
|
||||||
addresses, routing, browser policy and firewalls, not simply whether peers share
|
|
||||||
one network. A VPN is not automatically a guarantee against address disclosure.
|
|
||||||
|
|
||||||
Connection codes are **Base64-encoded, not encrypted**. They contain SDP,
|
|
||||||
including candidate addresses, temporary ICE credentials and certificate
|
|
||||||
fingerprints. Peers and anyone who sees these codes (including the messaging
|
|
||||||
service used to exchange them) may learn connection details. Local addresses may
|
|
||||||
be obscured by the browser, but this app does not provide anonymity. Treat codes
|
|
||||||
as private session information; do not publish them.
|
|
||||||
|
|
||||||
Restrictive NATs or firewalls can prevent direct connections. There is no silent
|
|
||||||
TURN retry. To permit a relay, both people must explicitly check **Allow a TURN
|
|
||||||
relay**, supply their authorized TURN URL, username and password, and generate
|
|
||||||
new codes. Otherwise TURN URLs are rejected in the STUN field and codes with
|
|
||||||
relay candidates are rejected. Enabling TURN allows the browser to contact that
|
|
||||||
relay during gathering and select a relay route when needed. This does not force
|
|
||||||
relay-only routing or hide your IP from the peer. A remote peer can independently
|
|
||||||
proxy their own traffic; the opt-in controls this app's configuration and the
|
|
||||||
relay candidates it accepts, not arbitrary software run by the other person.
|
|
||||||
|
|
||||||
When a credential endpoint is configured (including the local development setup
|
|
||||||
below), **Use the configured relay with temporary credentials** replaces manual
|
|
||||||
credential entry. The app fetches fresh credentials for each new connection,
|
|
||||||
only after TURN opt-in. The issued relay address, username and masked password
|
|
||||||
appear in read-only fields while the connection is active. Uncheck it to use a
|
|
||||||
different relay manually.
|
|
||||||
|
|
||||||
TURN credentials stay in the current component's memory; the app does not persist
|
|
||||||
them or include them in codes. The relay receives its authentication exchange and
|
|
||||||
can observe addresses, timing and traffic volume, and may charge for bandwidth.
|
|
||||||
Resetting, cancelling or ending a connection clears TURN consent;
|
|
||||||
check the option again before creating another relayed connection.
|
|
||||||
File traffic remains DTLS encrypted through the relay. The web host, DNS resolver,
|
|
||||||
and code-exchange service are also relevant third parties.
|
|
||||||
|
|
||||||
## Security model and limits
|
|
||||||
|
|
||||||
Data channels use **SCTP over DTLS**, which provides transport confidentiality and
|
|
||||||
integrity. This is not DTLS-SRTP (the media transport). DTLS authenticates the
|
|
||||||
certificate in the connection description; an independently authenticated full
|
|
||||||
fingerprint comparison binds that certificate to the intended peer. Comparing
|
|
||||||
fingerprints through a channel an attacker can rewrite provides no such assurance.
|
|
||||||
|
|
||||||
You must trust your browser, device, and **the JavaScript you load**. A compromised
|
|
||||||
host or build can steal plaintext or falsify the verification display. Serve the
|
|
||||||
production build over HTTPS, or run a verified build you control on localhost.
|
|
||||||
HTTPS protects delivery against network tampering, not against a malicious host.
|
|
||||||
The app does not upload files to its web host in this implementation; that is a
|
|
||||||
property of this code, not a guarantee against a host serving different code.
|
|
||||||
|
|
||||||
The protocol accepts one ordered, reliable data channel, 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. It rejects unexpected
|
|
||||||
states, excess data and duplicate metadata. An acknowledged 1 MiB send window per transfer
|
|
||||||
and a bounded receive queue limit buffering during disk writes. Files are treated
|
|
||||||
as opaque downloads; metadata is not rendered as HTML. Encryption does not make
|
|
||||||
a file safe to open. These limits reduce denial-of-service exposure but do not
|
|
||||||
eliminate browser, device, network, or malicious-peer risks.
|
|
||||||
|
|
||||||
For deployment, serve `dist/` as static files over HTTPS. Do not expose the Vite
|
|
||||||
dev or preview server as the production service. Configure hosting headers such
|
|
||||||
as `Content-Security-Policy` (including `frame-ancestors 'none'`),
|
|
||||||
`X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. A baseline
|
|
||||||
CSP for this build is `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'`. Inline styles are currently used for progress and
|
|
||||||
Vue visibility. Test headers on the actual host; CSP is defense in depth and is
|
|
||||||
not a substitute for trusting the host or a portable WebRTC egress filter.
|
|
||||||
`robots.txt` and indexing metadata are crawler requests, not access control.
|
|
||||||
|
|
||||||
Deploy the complete `dist/` directory, including `download/worker.js`, served
|
|
||||||
with a JavaScript MIME type. The download worker has scope `download/` only:
|
|
||||||
it does not control the app page, cache the app, or proxy normal web requests.
|
|
||||||
It serves single-use, randomly named download URLs from incoming browser
|
|
||||||
streams, with bounded buffering. The default CSP above permits this; custom
|
|
||||||
policies must permit same-origin workers and frames. No third-party helper,
|
|
||||||
download backend, or additional hosting service is required. Closing/resetting
|
|
||||||
an unfinished transfer aborts it; interrupted transfers must restart.
|
|
||||||
|
|
||||||
## Build and self-host
|
|
||||||
|
|
||||||
From a clone of the repository, run `bun install --frozen-lockfile` and
|
|
||||||
`bun run build`. Serve the whole `dist/` directory, including `assets/` and
|
|
||||||
`download/`, using a static web server over HTTPS. For local build inspection,
|
|
||||||
run `bun run preview` and open the printed localhost URL.
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
### Local WebTorrent tracker
|
|
||||||
|
|
||||||
The repository includes [our tracker Dockerfile](tracker/Dockerfile) and a
|
|
||||||
separate [Compose service](compose.tracker.yaml), built from the official Node
|
|
||||||
image and a locked upstream `bittorrent-tracker` release. With Docker running:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
bun run tracker:up # build and start ws://127.0.0.1:8000
|
pnpm install
|
||||||
bun run test:tracker # integration checks inside the test image
|
pnpm build
|
||||||
bun run tracker:down
|
|
||||||
```
|
```
|
||||||
|
|
||||||
See [tracker setup and deployment](tracker/README.md) for configuration and VPS
|
Then serve the `dist/` folder, with these requirements:
|
||||||
use. The tracker container is ready for development; automatic reconnect in
|
|
||||||
the browser is still [planned](docs/webtorrent-reconnect.md). Current app
|
|
||||||
connections continue to use manual codes.
|
|
||||||
|
|
||||||
### Local STUN/TURN environment (Linux)
|
- **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.
|
||||||
|
|
||||||
Keep Vite on the host for hot reload; only coturn runs in Docker. Both bind to
|
Recommended, as response headers, a `<meta>` can't set them (`index.html` sets
|
||||||
loopback, so use two browser tabs on this machine. No DNS, certificates, firewall
|
`Referrer-Policy: no-referrer` and the rest of its Content-Security-Policy itself, which keeps out
|
||||||
changes or production services are needed. Nothing is enabled at boot, and the
|
scripts and styles from elsewhere but allows connections to any tracker):
|
||||||
container has no automatic restart policy.
|
|
||||||
|
|
||||||
```sh
|
```
|
||||||
# Start Docker only when needed (if it isn't already running).
|
Content-Security-Policy: frame-ancestors 'none'
|
||||||
sudo systemctl start docker.service
|
X-Frame-Options: DENY
|
||||||
# If you just joined the docker group, log in again or run: newgrp docker
|
X-Content-Type-Options: nosniff
|
||||||
bun install --frozen-lockfile
|
|
||||||
bun run dev:setup # creates ignored .env.development, without overwriting it
|
|
||||||
bun run turn:up
|
|
||||||
bun run dev # open the printed localhost URL in two tabs
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Pick a file in the sender tab, choose Receive in the other, and check **Allow a
|
The first two keep other sites from framing HellCon and laying their own page over its buttons,
|
||||||
TURN relay** in both tabs. Leave **Use the configured relay with temporary
|
`X-Frame-Options` for older browsers.
|
||||||
credentials** checked. Exchange codes and compare fingerprints as usual. Reset,
|
|
||||||
failure or disconnect clears consent, so check it again for each connection.
|
|
||||||
STUN defaults to the local server; TURN remains opt-in, with direct routes preferred.
|
|
||||||
|
|
||||||
```sh
|
Your own tracker and STUN server are optional, any public ones work. `backend/` has both as Docker
|
||||||
bun run test # protocol and temporary-credential unit tests
|
Compose services: a tracker that only does what HellCon needs, with an Origin allowlist and limits,
|
||||||
bun run test:turn # real Chromium file transfer, forced TURN/UDP
|
and coturn as STUN server. `backend/compose.yaml` says how to set them up.
|
||||||
bun run test:turn --tcp # same test, TURN/TCP only
|
|
||||||
bun run build
|
|
||||||
bun run test:browser # direct-path browser regressions and axe accessibility checks
|
|
||||||
docker compose --env-file .env.development logs --tail=50 coturn
|
|
||||||
```
|
|
||||||
|
|
||||||
The TURN checks start and stop their own Vite server and isolated browser profiles;
|
If you change how HellCon talks to the other side, e.g. the code, the encryption or the messages,
|
||||||
coturn must already be running. They obtain real temporary credentials, force
|
give `PROTOCOL` in `src/core.ts` a name of your own, e.g. `yourname/1`, and count up from there.
|
||||||
relay-only routing, assert selected relay candidates on both ends, verify exact
|
|
||||||
received bytes and receipts, and exercise cancellation and reconnection. TCP here
|
|
||||||
means browser-to-TURN transport; relay-to-peer traffic is UDP. These same-machine
|
|
||||||
checks do not test Internet NATs or a remote server's firewall.
|
|
||||||
|
|
||||||
Stop Vite with Ctrl-C, then:
|
## Not planned
|
||||||
|
|
||||||
```sh
|
These were considered and decided against, please don't ask for them without a new reason. HellCon
|
||||||
bun run turn:down
|
is copy and paste a code, with public trackers and STUN servers. Anything that puts state in the URL,
|
||||||
# Optional: stop Docker too, after finishing any other containers.
|
needs infrastructure of its own or only helps small files doesn't pay off.
|
||||||
sudo systemctl stop docker.service docker.socket containerd.service
|
|
||||||
```
|
|
||||||
|
|
||||||
`.env.development` contains the private shared `TURN_SECRET`, server-side
|
- **The code in a share link:** the code would end up in the browser history and wherever links get
|
||||||
`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` settings.
|
handled, for one click less.
|
||||||
See [.env.example](.env.example). The secret never enters the client bundle.
|
- **Another code alphabet,** e.g. one that ignores case or uses words: most people copy and paste
|
||||||
Compose passes it directly to coturn; no config-file environment substitution is
|
the code anyway.
|
||||||
assumed. If changing the port, update both `TURN_PORT` and `VITE_STUN_URL`, then
|
- **Saving without the service worker,** holding the file in memory instead: useless for files of
|
||||||
rerun `turn:up` and restart Vite. The image is pinned to a concrete release;
|
several GB.
|
||||||
loopback listeners and UDP relay ports 49160–49200 are defined in [compose.yaml](compose.yaml).
|
- **TURN servers or a relay-only mode:** too much infrastructure to host and test.
|
||||||
Loopback peer access is explicitly allowed for these local tests.
|
- **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.
|
||||||
|
|
||||||
The credential endpoint is **development-only**, implemented as Vite middleware.
|
## Known limitations
|
||||||
It isn't included in `dist/` or `vite preview`. Production builds ignore
|
|
||||||
`.env.development` and retain the existing static/manual configuration. To reuse
|
|
||||||
the client integration later, set `VITE_ICE_ENDPOINT` and `VITE_STUN_URL` when
|
|
||||||
building and implement the same JSON endpoint behind your production access
|
|
||||||
policy. [dev/ice-server.ts](dev/ice-server.ts) contains the HMAC issuance logic.
|
|
||||||
There are no accounts or room sessions in this app to authorize production
|
|
||||||
credential issuance automatically. Don't expose this development endpoint or
|
|
||||||
reuse the loopback-permitting Compose configuration as a public relay.
|
|
||||||
|
|
||||||
Credentials expire after one hour; each new code exchange fetches fresh ones.
|
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
|
||||||
Automatic renewal during long transfers is not implemented because this app
|
but Firefox keeps showing the download as in progress until you cancel it.
|
||||||
uses manual signaling. Keep development transfers below that duration; expired
|
- **Chromium:** notices a vanished sender only after about 16 seconds.
|
||||||
or failed sessions need fresh codes.
|
- 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
|
||||||
Configuration references: [coturn Docker usage](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md)
|
background. Receiving keeps going.
|
||||||
and [coturn configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf).
|
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
|
||||||
|
work, and HellCon tells you so.
|
||||||
### Existing checks and static build
|
|
||||||
|
|
||||||
Use Bun for dependency installation and Node.js 22.18+ for the scripts and tests.
|
|
||||||
All application code, Vue scripts, development middleware, and checks use strict
|
|
||||||
TypeScript. `vue-tsc` checks both TypeScript and Vue templates, and runs before
|
|
||||||
every production build. TypeScript stays on 5.9 until Vue's checker supports the
|
|
||||||
TypeScript 7 compiler.
|
|
||||||
|
|
||||||
Vite 8 supplies VoidZero's Rolldown bundler and Oxc transforms. The only added
|
|
||||||
development dependencies are TypeScript, `vue-tsc`, and Node types. Node runs
|
|
||||||
the TypeScript tests directly; no separate test framework or TS loader is needed.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
bun install --frozen-lockfile
|
|
||||||
bun run dev
|
|
||||||
bun run typecheck
|
|
||||||
bun run test
|
|
||||||
bun run build
|
|
||||||
bun run test:browser # local Chromium integration checks against dist/
|
|
||||||
bun run test:browser --connections # sidebar, persistence, live switching, and mobile layout
|
|
||||||
bun run test:download # real hosted downloads, including 120 MiB, with native picker disabled
|
|
||||||
bun run test:cross-browser # Brave sender → Firefox receiver
|
|
||||||
bun run preview # local build inspection only
|
|
||||||
bun audit
|
|
||||||
```
|
|
||||||
|
|
||||||
The lockfile pins dependencies. Review dependency updates and advisories before
|
|
||||||
publishing a build. Protocol regression tests cover verification gating, malformed
|
|
||||||
messages, size limits, cancellation, receipt acknowledgment, and relay opt-in.
|
|
||||||
The browser check requires Chromium at `/usr/bin/chromium` (override with
|
|
||||||
`CHROMIUM_PATH`); it uses an isolated temporary profile and a loopback server.
|
|
||||||
Run `CHROMIUM_PATH=/usr/bin/brave bun run test:download` for the streaming
|
|
||||||
download check in Brave. Worker tests cover byte counts, backpressure, single-use
|
|
||||||
URLs, and browser/app cancellation; integration checks verify the actual saved bytes.
|
|
||||||
The cross-browser check uses Brave and Firefox at `/usr/bin/brave` and
|
|
||||||
`/usr/bin/firefox` (override with `BRAVE_PATH` and `FIREFOX_PATH`). It checks
|
|
||||||
that the received file remains downloadable after the sender disconnects.
|
|
||||||
Pass `--reverse` to test Firefox → Brave, or `--default-network` to use PageQuit
|
|
||||||
STUN instead of the local test's default None. These checks use temporary
|
|
||||||
browser profiles and do not modify your normal browser settings.
|
|
||||||
|
|
||||||
This is experimental software, not independently audited or battle-tested.
|
|
||||||
Browser compatibility, network connectivity and storage availability vary.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT — see `LICENSE`.
|
MIT, see [LICENSE](LICENSE).
|
||||||
|
|
||||||
## UX roadmap
|
|
||||||
|
|
||||||
See [the hosted-first UX roadmap](docs/ux-roadmap.md) for repeat transfers, file
|
|
||||||
queues and bidirectional sessions, remembered devices, invitations, and guided setup.
|
|
||||||
@@ -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,87 +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 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,125 +0,0 @@
|
|||||||
# Serverless UX roadmap
|
|
||||||
|
|
||||||
The app runs over HTTPS or on localhost. The current build uses manual signaling.
|
|
||||||
The next planned addition is [WebTorrent tracker reconnect](webtorrent-reconnect.md):
|
|
||||||
a configurable default or custom tracker exchanges encrypted connection codes for
|
|
||||||
paired devices, without a Trystero dependency. This replaces the custom rendezvous
|
|
||||||
proposal and the earlier blanket exclusion of a signaling backend. Peer presence,
|
|
||||||
offline wake-up and silent TURN fallback remain outside scope. The reconnect
|
|
||||||
feature is planned, not implemented; the sections below describe current behavior.
|
|
||||||
|
|
||||||
## 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, transfer controls, and persistent activity timeline. 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, paired devices, and up to 50 transfer
|
|
||||||
results per slot. Each result includes its direction, filename, size, timestamp,
|
|
||||||
and completion/decline/interruption status. File contents and connection codes
|
|
||||||
are never stored. Slot mutations are transactional and other tabs refresh their
|
|
||||||
lists after changes. Storage failures show an explicit warning.
|
|
||||||
|
|
||||||
Disconnect and Reset retain history. 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; a rolling list retains the last 50 results.
|
|
||||||
|
|
||||||
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. Shareable invitations
|
|
||||||
|
|
||||||
For HTTPS, encode fresh offers in URL fragments with an explicit Share/Copy link
|
|
||||||
action and an import preview. Keep connection details out of query strings and
|
|
||||||
server paths. Fragments still expose their contents to link recipients and any
|
|
||||||
service carrying the full link; explain that invitations are private. Clear the
|
|
||||||
fragment after import. Provide a similarly convenient answer handoff; an answer
|
|
||||||
exchange remains necessary. Keep pasteable codes as the universal fallback.
|
|
||||||
|
|
||||||
Bound and validate payloads, handle stale/incompatible links, and test practical
|
|
||||||
URL limits across messengers and mobile browsers. Do not promise a short link
|
|
||||||
without a storage service. Consider compressed payloads and QR only after checking
|
|
||||||
real payload sizes and decoding limits.
|
|
||||||
|
|
||||||
## 5. Guided connection flow
|
|
||||||
|
|
||||||
Present one primary next action across Choose files → Share invitation → 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.
|
|
||||||
@@ -1,271 +0,0 @@
|
|||||||
# WebTorrent tracker reconnect (planned, not implemented)
|
|
||||||
|
|
||||||
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. Browser pairing, settings and automatic reconnect remain planned.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
||||||
## 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="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet" />
|
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet" />
|
||||||
<meta name="googlebot" 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" />
|
<link rel="icon" type="image/png" href="./HellNet_alt.png" />
|
||||||
<title>HellCon — P2P File Share</title>
|
<title>HellCon</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
+22
-22
@@ -1,38 +1,38 @@
|
|||||||
{
|
{
|
||||||
"name": "hellcon",
|
"name": "hellcon",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.5",
|
"version": "1.0.2",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"dev:setup": "node scripts/dev-setup.ts",
|
"build": "vue-tsc && vite build",
|
||||||
"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",
|
|
||||||
"test:turn": "node scripts/browser-check.ts --turn",
|
|
||||||
"build": "vue-tsc --noEmit && vite build",
|
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"test": "node --test tests/*.test.ts",
|
"typecheck": "vue-tsc",
|
||||||
"test:browser": "node scripts/browser-check.ts",
|
"lint": "biome check",
|
||||||
"test:download": "node scripts/browser-check.ts --stream-download",
|
"format": "biome check --write",
|
||||||
"test:cross-browser": "node scripts/cross-browser-check.ts",
|
"test": "vitest run && playwright test",
|
||||||
"typecheck": "vue-tsc --noEmit"
|
"test:unit": "vitest",
|
||||||
|
"test:e2e": "playwright test",
|
||||||
|
"test:install": "playwright install chromium firefox",
|
||||||
|
"test:large": "LARGE=1 playwright test -g large"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"vue": "^3.5.44"
|
"vue": "^3.5.45"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^26.6.5",
|
"@biomejs/biome": "2.6.3",
|
||||||
"@vitejs/plugin-vue": "^6.0.10",
|
"@playwright/test": "^1.65.0",
|
||||||
"axe-core": "^4.14.0",
|
"@types/node": "^26.6.6",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.11",
|
||||||
"typescript": "~6.0.3",
|
"typescript": "~6.0.3",
|
||||||
"vite": "^8.3.4",
|
"vite": "^8.3.8",
|
||||||
"vue-tsc": "^3.3.13"
|
"vitest": "^5.1.0",
|
||||||
|
"vue-tsc": "^3.3.14",
|
||||||
|
"ws": "8.23.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"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',
|
|
||||||
} }));
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<svg version="1.1" id="main_outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
|
||||||
|
y="0px" viewBox="0 0 640 640" style="enable-background:new 0 0 640 640;" xml:space="preserve">
|
||||||
|
<g>
|
||||||
|
<path id="teabag" style="fill:#FFFFFF" d="M395.9,484.2l-126.9-61c-12.5-6-17.9-21.2-11.8-33.8l61-126.9c6-12.5,21.2-17.9,33.8-11.8
|
||||||
|
c17.2,8.3,27.1,13,27.1,13l-0.1-109.2l16.7-0.1l0.1,117.1c0,0,57.4,24.2,83.1,40.1c3.7,2.3,10.2,6.8,12.9,14.4
|
||||||
|
c2.1,6.1,2,13.1-1,19.3l-61,126.9C423.6,484.9,408.4,490.3,395.9,484.2z"/>
|
||||||
|
<g>
|
||||||
|
<g>
|
||||||
|
<path style="fill:#609926" d="M622.7,149.8c-4.1-4.1-9.6-4-9.6-4s-117.2,6.6-177.9,8c-13.3,0.3-26.5,0.6-39.6,0.7c0,39.1,0,78.2,0,117.2
|
||||||
|
c-5.5-2.6-11.1-5.3-16.6-7.9c0-36.4-0.1-109.2-0.1-109.2c-29,0.4-89.2-2.2-89.2-2.2s-141.4-7.1-156.8-8.5
|
||||||
|
c-9.8-0.6-22.5-2.1-39,1.5c-8.7,1.8-33.5,7.4-53.8,26.9C-4.9,212.4,6.6,276.2,8,285.8c1.7,11.7,6.9,44.2,31.7,72.5
|
||||||
|
c45.8,56.1,144.4,54.8,144.4,54.8s12.1,28.9,30.6,55.5c25,33.1,50.7,58.9,75.7,62c63,0,188.9-0.1,188.9-0.1s12,0.1,28.3-10.3
|
||||||
|
c14-8.5,26.5-23.4,26.5-23.4s12.9-13.8,30.9-45.3c5.5-9.7,10.1-19.1,14.1-28c0,0,55.2-117.1,55.2-231.1
|
||||||
|
C633.2,157.9,624.7,151.8,622.7,149.8z M125.6,353.9c-25.9-8.5-36.9-18.7-36.9-18.7S69.6,321.8,60,295.4
|
||||||
|
c-16.5-44.2-1.4-71.2-1.4-71.2s8.4-22.5,38.5-30c13.8-3.7,31-3.1,31-3.1s7.1,59.4,15.7,94.2c7.2,29.2,24.8,77.7,24.8,77.7
|
||||||
|
S142.5,359.9,125.6,353.9z M425.9,461.5c0,0-6.1,14.5-19.6,15.4c-5.8,0.4-10.3-1.2-10.3-1.2s-0.3-0.1-5.3-2.1l-112.9-55
|
||||||
|
c0,0-10.9-5.7-12.8-15.6c-2.2-8.1,2.7-18.1,2.7-18.1L322,273c0,0,4.8-9.7,12.2-13c0.6-0.3,2.3-1,4.5-1.5c8.1-2.1,18,2.8,18,2.8
|
||||||
|
l110.7,53.7c0,0,12.6,5.7,15.3,16.2c1.9,7.4-0.5,14-1.8,17.2C474.6,363.8,425.9,461.5,425.9,461.5z"/>
|
||||||
|
<path style="fill:#609926" d="M326.8,380.1c-8.2,0.1-15.4,5.8-17.3,13.8c-1.9,8,2,16.3,9.1,20c7.7,4,17.5,1.8,22.7-5.4
|
||||||
|
c5.1-7.1,4.3-16.9-1.8-23.1l24-49.1c1.5,0.1,3.7,0.2,6.2-0.5c4.1-0.9,7.1-3.6,7.1-3.6c4.2,1.8,8.6,3.8,13.2,6.1
|
||||||
|
c4.8,2.4,9.3,4.9,13.4,7.3c0.9,0.5,1.8,1.1,2.8,1.9c1.6,1.3,3.4,3.1,4.7,5.5c1.9,5.5-1.9,14.9-1.9,14.9
|
||||||
|
c-2.3,7.6-18.4,40.6-18.4,40.6c-8.1-0.2-15.3,5-17.7,12.5c-2.6,8.1,1.1,17.3,8.9,21.3c7.8,4,17.4,1.7,22.5-5.3
|
||||||
|
c5-6.8,4.6-16.3-1.1-22.6c1.9-3.7,3.7-7.4,5.6-11.3c5-10.4,13.5-30.4,13.5-30.4c0.9-1.7,5.7-10.3,2.7-21.3
|
||||||
|
c-2.5-11.4-12.6-16.7-12.6-16.7c-12.2-7.9-29.2-15.2-29.2-15.2s0-4.1-1.1-7.1c-1.1-3.1-2.8-5.1-3.9-6.3c4.7-9.7,9.4-19.3,14.1-29
|
||||||
|
c-4.1-2-8.1-4-12.2-6.1c-4.8,9.8-9.7,19.7-14.5,29.5c-6.7-0.1-12.9,3.5-16.1,9.4c-3.4,6.3-2.7,14.1,1.9,19.8
|
||||||
|
C343.2,346.5,335,363.3,326.8,380.1z"/>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.5 KiB |
+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,638 +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 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');
|
|
||||||
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' };
|
|
||||||
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 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);
|
|
||||||
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', 'invalid-answer!'); await click(sender, 'Connect');
|
|
||||||
await wait(sender, () => !!document.querySelector('[role=alert]'));
|
|
||||||
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 button = [...document.querySelectorAll<HTMLButtonElement>('.connection-link')].find(item => item.querySelector('.connection-name')?.textContent === name);
|
|
||||||
if (!button) throw new Error('Missing connection: ' + name);
|
|
||||||
button.click();
|
|
||||||
}, name);
|
|
||||||
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'));
|
|
||||||
};
|
|
||||||
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false }, sender);
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1');
|
|
||||||
await checkAccessibility(sender, 'Connections desktop');
|
|
||||||
await screenshot(sender, 'connections-desktop');
|
|
||||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
|
|
||||||
await input(sender, '#connection-name', 'Work laptop');
|
|
||||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').blur());
|
|
||||||
await wait(sender, () => document.querySelector('.connection-name')?.textContent === 'Work laptop');
|
|
||||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
|
|
||||||
await input(sender, '#connection-name', ' ');
|
|
||||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').blur());
|
|
||||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').value), 'Work laptop');
|
|
||||||
await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('#connection-name').focus());
|
|
||||||
await input(sender, '#connection-name', '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, () => window.__hellcon.element<HTMLInputElement>('#connection-name').value), 'Work laptop');
|
|
||||||
assert.equal(await evaluate(sender, () => document.activeElement?.id === 'connection-name'), false);
|
|
||||||
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('.title-line h1')?.textContent === 'Con 2');
|
|
||||||
assert.equal(await evaluate(sender, () => !!document.querySelector('.fingerprint')), false);
|
|
||||||
await click(receiver, 'Accept file');
|
|
||||||
await wait(sender, () => document.querySelector('.connection-link .connection-preview')?.textContent === 'browser-test.bin');
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0, 'Hidden session activity must stay in its own slot');
|
|
||||||
await selectConnection(sender, 'Work laptop');
|
|
||||||
await wait(sender, () => document.querySelector('.session-badge')?.textContent?.includes('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.querySelectorAll('.activity-item').length === 2);
|
|
||||||
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.querySelectorAll('.activity-item').length), 2, 'Reset must preserve slot history');
|
|
||||||
await checkAccessibility(sender, 'Connections with history');
|
|
||||||
await screenshot(sender, 'connections-history');
|
|
||||||
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.querySelectorAll('.activity-item').length === 2);
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Work laptop');
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelector('.session-badge')?.textContent), 'Ready to connect');
|
|
||||||
await selectConnection(sender, 'Con 2');
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0);
|
|
||||||
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 and separate histories across reload; switching preserves live transfers and drafts; Reset preserves 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');
|
|
||||||
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, 'Remove');
|
|
||||||
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 click(sender, 'Show connections');
|
|
||||||
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>('.header-action').focus());
|
|
||||||
await click(other, 'Remove');
|
|
||||||
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('header-action')), true, 'Dialog restores focus to the opener');
|
|
||||||
await click(other, 'Remove');
|
|
||||||
await click(other, 'Keep connection');
|
|
||||||
assert.equal(await evaluate(other, () => document.querySelectorAll('.connection-link').length), 4);
|
|
||||||
await click(other, 'Remove'); 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(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('.title-line h1')?.textContent);
|
|
||||||
await click(sender, 'Remove'); 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('.title-line h1')?.textContent), oldName);
|
|
||||||
}
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelector('.title-line h1')?.textContent), 'Con 1');
|
|
||||||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0);
|
|
||||||
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.');
|
|
||||||
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.equal(JSON.parse(atob(offer)).version, 4);
|
|
||||||
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.');
|
|
||||||
|
|
||||||
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(JSON.parse(atob(temporary)).version, 3);
|
|
||||||
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 {
|
|
||||||
const offer = await api.createOfferCode(a);
|
|
||||||
let sdp = api.decodeSignal(offer);
|
|
||||||
// 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 = await api.createAnswerCode(b, api.encodeSignal(sdp));
|
|
||||||
log('answer ready');
|
|
||||||
await new Promise(r=>setTimeout(r,20000));
|
|
||||||
log('apply answer');
|
|
||||||
await api.acceptAnswerCode(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.');
|
|
||||||
}
|
|
||||||
+622
-161
@@ -1,173 +1,634 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
|
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
|
||||||
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
|
import {
|
||||||
import AppDialog from './components/AppDialog.vue';
|
answerOffer,
|
||||||
import EditableName from './components/EditableName.vue';
|
type Check,
|
||||||
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionActivity, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts';
|
settings as coreSettings,
|
||||||
import { asError } from './lib/validation.ts';
|
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`;
|
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
|
||||||
const connections = ref<SavedConnection[]>([]), selected = ref('');
|
// defaults.
|
||||||
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
|
const settings = reactive(coreSettings);
|
||||||
const current = computed(() => connections.value.find(item => item.id === selected.value));
|
|
||||||
const sidebarOpen = ref(false), adding = ref(false);
|
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
|
||||||
const confirmingRemoval = ref(false), removing = ref(false);
|
const ownSalt = reactive({ on: false, text: '' });
|
||||||
const error = ref(''), removalError = ref('');
|
// Empty is no salt, Share and Receive wait for one.
|
||||||
const heading = ref<HTMLElement | null>(null);
|
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
|
||||||
let persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
|
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
|
||||||
let updates: BroadcastChannel | undefined;
|
// From the code's alphabet, 16 characters are about 95 bits.
|
||||||
function select(id: string) {
|
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
|
||||||
selected.value = id; confirmingRemoval.value = false; sidebarOpen.value = false;
|
|
||||||
void nextTick(() => heading.value?.focus());
|
// 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
|
||||||
function applyRecords(records: SavedConnection[]) {
|
// contacts nobody before an offer, but typing makes one per keystroke, so each line is checked once.
|
||||||
connections.value = records;
|
const stunChecks = new Map<string, boolean>();
|
||||||
for (const id of Object.keys(states.value)) if (!records.some(item => item.id === id)) delete states.value[id];
|
function isStun(url: string) {
|
||||||
if (!records.some(item => item.id === selected.value)) select(records[0]!.id);
|
if (!stunChecks.has(url)) {
|
||||||
}
|
|
||||||
function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') {
|
|
||||||
if (connections.value.some(item => item.id === id)) states.value[id] = state;
|
|
||||||
}
|
|
||||||
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; }
|
|
||||||
}
|
|
||||||
onMounted(async () => {
|
|
||||||
try { connections.value = await loadConnections(); }
|
|
||||||
catch (err) {
|
|
||||||
persistent = false; connections.value = [emptyConnection()];
|
|
||||||
error.value = `${asError(err).message} Connections and activity will only last for this tab.`;
|
|
||||||
}
|
|
||||||
selected.value = connections.value[0]!.id;
|
|
||||||
if (typeof BroadcastChannel !== 'undefined') {
|
|
||||||
updates = new BroadcastChannel('hellcon-connections');
|
|
||||||
updates.onmessage = () => { void refresh(); };
|
|
||||||
}
|
|
||||||
window.addEventListener('focus', refresh);
|
|
||||||
});
|
|
||||||
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; }
|
|
||||||
}
|
|
||||||
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 {
|
try {
|
||||||
const records = await saveConnection(id, change);
|
new RTCPeerConnection({ iceServers: [{ urls: url }] }).close();
|
||||||
if (pending === 1) applyRecords(records);
|
stunChecks.set(url, /^stuns?:/i.test(url));
|
||||||
updates?.postMessage('changed');
|
} catch {
|
||||||
} catch (err) {
|
stunChecks.set(url, false);
|
||||||
// Keep this tab's activity usable without pretending it reached storage.
|
}
|
||||||
error.value = `${asError(err).message} Your latest changes may be lost when this tab closes.`;
|
}
|
||||||
refreshRequested = true;
|
return stunChecks.get(url)!;
|
||||||
} finally { pending--; if (!pending && refreshRequested) void refresh(); }
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
function record(id: string, activity: ConnectionActivity) { update(id, { activity }); }
|
|
||||||
// Connection setup re-reads the record so trust forgotten in another tab is
|
// public/ in the build, which works under any path, see vite.config.ts.
|
||||||
// never reused from this tab's copy. A failed read stops setup.
|
const BASE = import.meta.env.BASE_URL;
|
||||||
async function trust(id: string) {
|
|
||||||
await writes;
|
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
|
||||||
const records = persistent ? await loadConnections() : connections.value;
|
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
|
||||||
const record = records.find(item => item.id === id);
|
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
|
||||||
if (!record) throw new Error('This connection is no longer saved. Reload the page.');
|
const secure = location.protocol === 'https:';
|
||||||
if (persistent && !pending && !removing.value) applyRecords(records);
|
const isLocal = (hostname: string) =>
|
||||||
return record;
|
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 });
|
||||||
}
|
}
|
||||||
async function remove() {
|
|
||||||
if (!current.value || removing.value || adding.value) return;
|
const stunServers = serverList('stunServers', isStun);
|
||||||
const id = current.value.id;
|
const trackers = serverList('trackers', isTracker);
|
||||||
removing.value = true; removalError.value = '';
|
|
||||||
|
function onResetServers() {
|
||||||
|
stunServers.text = DEFAULT_STUN_SERVERS.join('\n');
|
||||||
|
trackers.text = DEFAULT_TRACKERS.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onConfirm() {
|
||||||
|
confirmed.value = true;
|
||||||
|
check.value?.confirm();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
try {
|
||||||
await writes;
|
await navigator.clipboard.writeText(text);
|
||||||
const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id);
|
} catch {
|
||||||
applyRecords(records.length ? records : [emptyConnection()]);
|
events.log('copy failed, the browser blocked the clipboard');
|
||||||
confirmingRemoval.value = false;
|
copied.value = { text, ok: false };
|
||||||
updates?.postMessage('changed');
|
const element = document.getElementById(id);
|
||||||
} catch (err) { removalError.value = asError(err).message; }
|
if (element instanceof HTMLTextAreaElement) {
|
||||||
finally { removing.value = false; if (refreshRequested) void refresh(); }
|
element.focus();
|
||||||
|
element.select();
|
||||||
|
} else if (element) getSelection()?.selectAllChildren(element);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener('visibilitychange', holdWakeLock);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<a class="skip-link" href="#main-content">Skip to main content</a>
|
<header>
|
||||||
<div class="app-shell" :class="{ 'sidebar-open': sidebarOpen }">
|
<div>
|
||||||
<aside id="connections-sidebar" class="sidebar" aria-label="Connections sidebar">
|
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
|
||||||
<header class="brand">
|
<h1>HellCon</h1>
|
||||||
<img :src="logoUrl" width="38" height="38" alt="" />
|
</div>
|
||||||
<div><span class="brand-name">HellCon</span><p>Direct file sharing</p></div>
|
<div id="options">
|
||||||
</header>
|
<div>
|
||||||
<div class="sidebar-section-heading"><h2>Connections</h2><span>{{ connections.length }}</span></div>
|
<label>
|
||||||
<nav class="connection-nav" aria-label="Connections">
|
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||||
<button v-for="item in connections" :key="item.id" class="connection-link" :class="{ selected: selected === item.id }"
|
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
||||||
:aria-current="selected === item.id ? 'page' : undefined" @click="select(item.id)">
|
Use STUN
|
||||||
<span class="connection-avatar" aria-hidden="true">{{ item.name.slice(0, 1).toUpperCase() }}</span>
|
</label>
|
||||||
<span class="connection-label"><span class="connection-name">{{ item.name }}</span><span class="connection-preview">{{ item.history.at(-1)?.name || (item.peerKey ? 'Remembered device' : 'No activity yet') }}</span></span>
|
<label>
|
||||||
<span class="connection-dot" :class="states[item.id] || 'ready'" :aria-label="statusLabel(item.id)"></span>
|
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||||
</button>
|
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
|
||||||
</nav>
|
Use own salt
|
||||||
<button class="add-connection" :disabled="adding || removing || !connections.length || connections.length >= CONNECTION_LIMIT" @click="add"><span aria-hidden="true">+</span> Add connection</button>
|
</label>
|
||||||
<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, identities, and history.</p>
|
|
||||||
</details>
|
|
||||||
</footer>
|
|
||||||
</aside>
|
|
||||||
<main id="main-content" class="main-pane" tabindex="-1">
|
|
||||||
<header class="connection-header">
|
|
||||||
<button class="sidebar-toggle" :aria-expanded="sidebarOpen" aria-controls="connections-sidebar" @click="sidebarOpen = !sidebarOpen">{{ sidebarOpen ? 'Hide connections' : 'Show connections' }}</button>
|
|
||||||
<template v-if="current">
|
|
||||||
<div class="connection-title">
|
|
||||||
<p class="eyebrow">Connection</p>
|
|
||||||
<div class="title-line">
|
|
||||||
<h1 ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
|
|
||||||
<EditableName :key="current.id" :name="current.name" :disabled="removing" @rename="update(current!.id, { name: $event })" />
|
|
||||||
<button class="header-action" :disabled="adding || removing" @click="removalError = ''; confirmingRemoval = true"><span class="header-action-icon" aria-hidden="true">✕</span> Remove</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<span class="session-badge" :class="states[current.id] || 'ready'"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span>{{ statusLabel(current.id) }}</span>
|
|
||||||
</template>
|
|
||||||
</header>
|
|
||||||
<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" @status="setStatus" @activity="record" @update="update" />
|
|
||||||
</KeepAlive>
|
|
||||||
</template>
|
|
||||||
<p v-if="!current" class="status">Opening your connections…</p>
|
|
||||||
</div>
|
</div>
|
||||||
</main>
|
<div v-if="ownSalt.on" role="group">
|
||||||
</div>
|
<input
|
||||||
<AppDialog v-model="confirmingRemoval" :title="`Remove ${current?.name || 'connection'}?`" :busy="removing">
|
id="salt"
|
||||||
<p>This ends its session and deletes its saved activity and remembered device. Saved files and your device identity are kept.</p>
|
v-model="ownSalt.text"
|
||||||
<p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p>
|
aria-label="Own salt"
|
||||||
<p v-if="removalError" class="error" role="alert">{{ removalError }}</p>
|
placeholder="Same salt on both sides"
|
||||||
<template #actions="{ close }">
|
:aria-invalid="saltMissing"
|
||||||
<button :disabled="removing" autofocus @click="close">Keep connection</button>
|
:disabled="saltLocked"
|
||||||
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
|
autocapitalize="off"
|
||||||
</template>
|
autocomplete="off"
|
||||||
</AppDialog>
|
autocorrect="off"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
|
||||||
|
Generate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<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>
|
</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,64 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { ref } from 'vue';
|
|
||||||
import TransferPanel from './TransferPanel.vue';
|
|
||||||
import type { SavedConnection, ConnectionActivity, ConnectionUpdate } from '../lib/connections.ts';
|
|
||||||
const props = defineProps<{ connection: SavedConnection; loadTrust: (id: string) => Promise<SavedConnection> }>();
|
|
||||||
const emit = defineEmits<{
|
|
||||||
status: [id: string, state: 'ready' | 'connecting' | 'connected'];
|
|
||||||
activity: [id: string, item: ConnectionActivity];
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
function sizeLabel(size: number) {
|
|
||||||
if (size < 1024) return `${size} B`;
|
|
||||||
const index = Math.min(5, Math.floor(Math.log(size) / Math.log(1024)));
|
|
||||||
return `${(size / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'][index]}`;
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="connection-workspace">
|
|
||||||
<div class="session-column">
|
|
||||||
<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)"
|
|
||||||
@session-change="sessionActive = $event; status()" @connected-change="connected = $event; direction = mode; status()"
|
|
||||||
@activity="emit('activity', connection.id, $event)" @update="emit('update', connection.id, $event)" />
|
|
||||||
</div>
|
|
||||||
<aside class="activity-panel" aria-labelledby="activity-heading">
|
|
||||||
<div class="activity-heading"><h2 id="activity-heading">Activity</h2><span>{{ connection.history.length }}</span></div>
|
|
||||||
<div v-if="!connection.history.length" class="empty-activity">
|
|
||||||
<span class="empty-activity-icon" aria-hidden="true">↔</span>
|
|
||||||
<h3>A fresh connection</h3>
|
|
||||||
<p>Files you share here will appear in this timeline.</p>
|
|
||||||
<p class="activity-note">History stays in this browser. File contents aren’t kept here.</p>
|
|
||||||
</div>
|
|
||||||
<ol v-else class="activity-list" aria-label="Recent file results">
|
|
||||||
<li v-for="item in [...connection.history].reverse()" :key="item.id" class="activity-item">
|
|
||||||
<span class="activity-icon" aria-hidden="true">{{ item.direction === 'send' ? '↗' : '↙' }}</span>
|
|
||||||
<div>
|
|
||||||
<p class="activity-filename">{{ item.name }}</p>
|
|
||||||
<p class="activity-meta">{{ item.direction === 'send' ? 'Outgoing' : 'Incoming' }} · {{ sizeLabel(item.size) }}</p>
|
|
||||||
<p class="activity-result">{{ item.result === 'complete' ? 'Transfer complete' : item.result === 'declined' ? 'Declined' : 'Interrupted' }}</p>
|
|
||||||
<time :datetime="new Date(item.time).toISOString()">{{ new Date(item.time).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) }}</time>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
</ol>
|
|
||||||
<p v-if="connection.history.length" class="activity-note">Last 50 transfers · Saved in this browser</p>
|
|
||||||
</aside>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
@@ -1,79 +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 }>();
|
|
||||||
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: '' }); }
|
|
||||||
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">
|
|
||||||
<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>
|
|
||||||
<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,24 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { ref, watch } from 'vue';
|
|
||||||
const props = defineProps<{ name: string; disabled?: boolean }>();
|
|
||||||
const emit = defineEmits<{ rename: [name: string] }>();
|
|
||||||
const draft = ref(props.name), editing = ref(false);
|
|
||||||
watch(() => props.name, value => { if (!editing.value) draft.value = value; });
|
|
||||||
function save() {
|
|
||||||
editing.value = false;
|
|
||||||
const name = draft.value.trim();
|
|
||||||
draft.value = name || props.name;
|
|
||||||
if (name && name !== props.name) emit('rename', name);
|
|
||||||
}
|
|
||||||
function finish(event: KeyboardEvent) { (event.target as HTMLInputElement).blur(); }
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="editable-name">
|
|
||||||
<label class="sr-only" for="connection-name">Connection name</label>
|
|
||||||
<input id="connection-name" v-model="draft" :size="Math.max(5, Math.min(draft.length + 2, 24))" :disabled="disabled" maxlength="80" autocomplete="off" spellcheck="false"
|
|
||||||
aria-describedby="connection-name-hint" @focus="editing = true" @blur="save" @keydown.enter.prevent="finish" />
|
|
||||||
<span class="name-edit-icon" aria-hidden="true">✎</span>
|
|
||||||
<span id="connection-name-hint" class="sr-only">Edit the name. Changes save when you leave this field.</span>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import type { IceOptions, NetworkSettings } from '../lib/webrtc.ts';
|
|
||||||
import { STUN_PROVIDERS } from '../lib/webrtc.ts';
|
|
||||||
const settings = defineModel<NetworkSettings>({ required: true });
|
|
||||||
defineProps<{ disabled?: boolean; managedCredentials?: IceOptions | null }>();
|
|
||||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
|
||||||
</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>
|
|
||||||
</template>
|
|
||||||
@@ -1,494 +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, 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 { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, decodeSignal, signalIdentity, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.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 { ConnectionActivity, ConnectionUpdate, SavedConnection } from '../lib/connections.ts';
|
|
||||||
|
|
||||||
type Step = 'session-ready' | 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
|
||||||
interface Session {
|
|
||||||
pc: RTCPeerConnection;
|
|
||||||
options: IceOptions;
|
|
||||||
controller: AbortController;
|
|
||||||
transfer: FileSession | null;
|
|
||||||
diagnostics: ConnectionDiagnostics;
|
|
||||||
localHello?: IdentityHello;
|
|
||||||
remoteHello?: IdentityHello;
|
|
||||||
identityContext?: IdentityContext;
|
|
||||||
identity?: IdentityState['identity'];
|
|
||||||
expected?: string;
|
|
||||||
timer?: ReturnType<typeof setTimeout>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const props = defineProps<{ sending?: boolean; connection: SavedConnection; loadTrust: () => Promise<SavedConnection> }>();
|
|
||||||
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]; activity: [item: ConnectionActivity]; 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);
|
|
||||||
// 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;
|
|
||||||
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.',
|
|
||||||
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)) { remember('send', outgoing.value, 'interrupted'); sendState.value = 'closed'; }
|
|
||||||
if (incoming.value && receiveState.value && !['done', 'closed'].includes(receiveState.value)) { remember('receive', incoming.value, 'interrupted'); receiveState.value = 'closed'; }
|
|
||||||
}
|
|
||||||
active = null; connected.value = false; queuedFiles.value = []; emit('sessionChange', 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 reset(keepNetwork = false) {
|
|
||||||
const allowTurn = settings.value.allowTurn;
|
|
||||||
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');
|
|
||||||
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 remember(direction: ConnectionActivity['direction'], meta: FileMetadata, result: ConnectionActivity['result']) {
|
|
||||||
emit('activity', { id: crypto.randomUUID(), time: Date.now(), direction, name: meta.name, size: meta.size, result });
|
|
||||||
}
|
|
||||||
function disconnect() {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
session.transfer = new FileSession(channel, !!props.sending, {
|
|
||||||
onReady: () => { if (active === session) {
|
|
||||||
connected.value = true; step.value = 'session-ready'; clearTimeout(session.timer);
|
|
||||||
// Ready implies both fresh proofs verified, so the key may now be saved.
|
|
||||||
if (session.identityContext && session.remoteHello) {
|
|
||||||
const key = session.remoteHello.key;
|
|
||||||
if (session.expected === key) identityStatus.value = 'Paired device authenticated for this connection.';
|
|
||||||
else if (rememberPeer.value) { emit('update', { peerKey: key }); identityStatus.value = `Device proof checked. Remembered for ${props.connection.name}.`; }
|
|
||||||
else identityStatus.value = 'Device proof checked. This device was not remembered.';
|
|
||||||
}
|
|
||||||
} },
|
|
||||||
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;
|
|
||||||
remember(direction, meta, 'complete');
|
|
||||||
void session.diagnostics.capture();
|
|
||||||
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); }
|
|
||||||
},
|
|
||||||
onDecline: (direction, meta) => {
|
|
||||||
if (active !== session) return;
|
|
||||||
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
|
|
||||||
remember(direction, meta, 'declined');
|
|
||||||
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),
|
|
||||||
});
|
|
||||||
if (props.sending) { session.transfer.add(selectedFiles.value); selectedFiles.value = []; file.value = null; }
|
|
||||||
configureIdentity(session);
|
|
||||||
if (verified.value) session.transfer.verify();
|
|
||||||
}
|
|
||||||
function start() {
|
|
||||||
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, 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();
|
|
||||||
// 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;
|
|
||||||
if (!props.sending) { decodeSignal(pasted, session.options); session.remoteHello = signalIdentity(pasted); }
|
|
||||||
const options = { ...session.options, signal: session.controller.signal, identity: session.localHello };
|
|
||||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v3'));
|
|
||||||
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
|
|
||||||
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 {
|
|
||||||
decodeSignal(inputCode.value, session.options);
|
|
||||||
session.remoteHello = signalIdentity(inputCode.value);
|
|
||||||
await acceptAnswerCode(session.pc, inputCode.value, 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 = !!props.sending;
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
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(() => { 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" :disabled="busy || connected" @update="emit('update', $event)" />
|
|
||||||
<details class="network-details">
|
|
||||||
<summary>Network settings</summary>
|
|
||||||
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
|
|
||||||
</details>
|
|
||||||
<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_SIGNAL_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_SIGNAL_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>
|
|
||||||
<button v-if="connected || busy" @click="disconnect">Disconnect</button>
|
|
||||||
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
|
||||||
<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
-9
@@ -4,12 +4,3 @@ declare module '*.vue' {
|
|||||||
const component: DefineComponent;
|
const component: DefineComponent;
|
||||||
export default component;
|
export default component;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ImportMetaEnv {
|
|
||||||
readonly VITE_ICE_ENDPOINT?: string;
|
|
||||||
readonly VITE_STUN_URL?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Window {
|
|
||||||
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<{ createWritable(): Promise<import('./lib/transfer.ts').FileDestination> }>;
|
|
||||||
}
|
|
||||||
@@ -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,113 +0,0 @@
|
|||||||
import { isRecord } from './validation.ts';
|
|
||||||
|
|
||||||
export const CONNECTION_LIMIT = 100;
|
|
||||||
export const HISTORY_LIMIT = 50;
|
|
||||||
export interface ConnectionActivity {
|
|
||||||
id: string;
|
|
||||||
time: number;
|
|
||||||
direction: 'send' | 'receive';
|
|
||||||
name: string;
|
|
||||||
size: number;
|
|
||||||
result: 'complete' | 'declined' | 'interrupted';
|
|
||||||
}
|
|
||||||
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;
|
|
||||||
history: ConnectionActivity[];
|
|
||||||
}
|
|
||||||
export type ConnectionUpdate = { name: string } | { peerKey: string } | { rememberDevice: boolean } | { activity: ConnectionActivity };
|
|
||||||
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 };
|
|
||||||
}
|
|
||||||
if ('rememberDevice' in update) return { ...current, rememberDevice: update.rememberDevice === true };
|
|
||||||
const item = update.activity;
|
|
||||||
if (typeof item.id !== 'string' || !item.id || !Number.isSafeInteger(item.time) || item.time < 0 || item.time > 8640000000000000 ||
|
|
||||||
typeof item.name !== 'string' || !item.name || item.name.length > 255 ||
|
|
||||||
!Number.isSafeInteger(item.size) || item.size < 0 || !['send', 'receive'].includes(item.direction) ||
|
|
||||||
!['complete', 'declined', 'interrupted'].includes(item.result)) throw new Error('Invalid connection activity.');
|
|
||||||
return { ...current, history: [...current.history.filter(previous => previous.id !== item.id), item].sort((a, b) => a.time - b.time).slice(-HISTORY_LIMIT) };
|
|
||||||
}
|
|
||||||
export function emptyConnection(number = 1): SavedConnection {
|
|
||||||
return { id: crypto.randomUUID(), number, name: `Con ${number}`, peerKey: '', rememberDevice: false, history: [] };
|
|
||||||
}
|
|
||||||
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' || !Array.isArray(value.history) || value.history.length > HISTORY_LIMIT) throw new Error('Saved connections are unreadable.');
|
|
||||||
let record: SavedConnection = { id: value.id, number: value.number as number, name: connectionName(value.name), peerKey: '', rememberDevice: value.rememberDevice === true, history: [] };
|
|
||||||
record = updateConnection(record, { peerKey: value.peerKey });
|
|
||||||
for (const item of value.history) {
|
|
||||||
if (!isRecord(item)) throw new Error('Saved activity is unreadable.');
|
|
||||||
record = updateConnection(record, { activity: item as unknown as ConnectionActivity });
|
|
||||||
}
|
|
||||||
return record;
|
|
||||||
}
|
|
||||||
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,
|
|
||||||
// paired device, or history entry 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(validateConnection).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,200 +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;
|
|
||||||
}
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
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 (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,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,207 +0,0 @@
|
|||||||
import { parseHello, type IdentityHello } from './identity.ts';
|
|
||||||
import { asError, 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'> & { identity?: IdentityHello };
|
|
||||||
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 are encoded connection details, not encrypted secrets.
|
|
||||||
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),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function encodeSignal(sdp: string, identity?: IdentityHello) {
|
|
||||||
const code = btoa(JSON.stringify(identity ? { version: 4, sdp, identity: parseHello(identity) } : { version: 3, sdp })).replace(/=+$/, '');
|
|
||||||
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
|
|
||||||
return code;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTurn'>): string {
|
|
||||||
if (typeof text !== 'string' || text.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large.');
|
|
||||||
try {
|
|
||||||
const clean = text.trim().replace(/\s+/g, '');
|
|
||||||
const data: unknown = JSON.parse(atob(clean));
|
|
||||||
if (!isRecord(data) || ![3, 4].includes(data.version as number)) throw new Error('Both people need the current HellCon version.');
|
|
||||||
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
|
|
||||||
if (data.version === 4) parseHello(data.identity);
|
|
||||||
validateDescription(data.sdp, options);
|
|
||||||
return data.sdp;
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof SyntaxError || asError(err).name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createOfferCode(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 encodeSignal(pc.localDescription.sdp, options.identity);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) {
|
|
||||||
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) });
|
|
||||||
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 encodeSignal(pc.localDescription.sdp, options.identity);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) {
|
|
||||||
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) });
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function signalIdentity(text: string): IdentityHello | undefined {
|
|
||||||
const data = JSON.parse(atob(text.trim().replace(/\s+/g, '')));
|
|
||||||
return data.version === 4 ? parseHello(data.identity) : undefined;
|
|
||||||
}
|
|
||||||
+619
-311
File diff suppressed because it is too large.
Load diff
@@ -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,36 +0,0 @@
|
|||||||
import test from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { emptyConnection, updateConnection, HISTORY_LIMIT, type ConnectionActivity } from '../src/lib/connections.ts';
|
|
||||||
|
|
||||||
test('renaming and pairing preserve a slot identity and its activity', () => {
|
|
||||||
const initial = emptyConnection(2);
|
|
||||||
const activity: ConnectionActivity = { id: 'transfer', time: 1, direction: 'send', name: 'example.txt', size: 123, result: 'complete' };
|
|
||||||
const withHistory = updateConnection(initial, { activity });
|
|
||||||
const renamed = updateConnection(withHistory, { 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.deepEqual(paired.history, [activity]);
|
|
||||||
assert.equal(initial.history.length, 0);
|
|
||||||
assert.throws(() => updateConnection(paired, { name: ' ' }));
|
|
||||||
assert.throws(() => updateConnection(paired, { name: 'a'.repeat(81) }));
|
|
||||||
assert.throws(() => updateConnection(paired, { peerKey: 'invalid' }));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('history is bounded, ordered, and does not duplicate an event', () => {
|
|
||||||
let connection = emptyConnection();
|
|
||||||
for (let i = 0; i < HISTORY_LIMIT + 10; i++) {
|
|
||||||
connection = updateConnection(connection, { activity: { id: String(i), time: i, direction: 'receive', name: 'file', size: 0, result: 'declined' } });
|
|
||||||
}
|
|
||||||
const last = connection.history.at(-1)!;
|
|
||||||
connection = updateConnection(connection, { activity: last });
|
|
||||||
assert.equal(connection.history.length, HISTORY_LIMIT);
|
|
||||||
assert.equal(connection.history[0]!.time, 10);
|
|
||||||
assert.throws(() => updateConnection(connection, { activity: { ...last, size: -1 } }));
|
|
||||||
assert.throws(() => updateConnection(connection, { activity: { ...last, direction: 'invalid' as 'send' } }));
|
|
||||||
});
|
|
||||||
@@ -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,146 +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 };
|
|
||||||
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; },
|
|
||||||
};
|
|
||||||
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/);
|
|
||||||
});
|
|
||||||
@@ -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,78 +0,0 @@
|
|||||||
import test from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { iceConfiguration, validateDescription, getFingerprints, signalIdentity, encodeSignal, decodeSignal, 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(() => decodeSignal(encodeSignal(relayed)), /explicitly enable TURN/);
|
|
||||||
assert.equal(decodeSignal(encodeSignal(relayed), { allowTurn: true }), relayed);
|
|
||||||
});
|
|
||||||
|
|
||||||
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('signals round-trip but reject legacy, malformed and oversized codes', () => {
|
|
||||||
assert.equal(decodeSignal(encodeSignal(sdp)), sdp);
|
|
||||||
assert.throws(() => decodeSignal(btoa(sdp)));
|
|
||||||
assert.throws(() => decodeSignal('bad!'));
|
|
||||||
assert.throws(() => decodeSignal('a'.repeat(MAX_SIGNAL_LENGTH + 1)));
|
|
||||||
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 2, sdp }))));
|
|
||||||
});
|
|
||||||
|
|
||||||
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/);
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
test('identity signaling is versioned, bounded, and optional for temporary sessions', () => {
|
|
||||||
const identity = { key: '04' + 'ab'.repeat(64), nonce: 'cd'.repeat(32) };
|
|
||||||
const code = encodeSignal(sdp, identity);
|
|
||||||
assert.equal(JSON.parse(atob(code)).version, 4);
|
|
||||||
assert.equal(decodeSignal(code), sdp);
|
|
||||||
assert.deepEqual(signalIdentity(code), identity);
|
|
||||||
assert.equal(signalIdentity(encodeSignal(sdp)), undefined);
|
|
||||||
assert.equal(JSON.parse(atob(encodeSignal(sdp))).version, 3);
|
|
||||||
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp }))));
|
|
||||||
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 4, sdp, identity: { ...identity, nonce: 'bad' } }))));
|
|
||||||
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 5, sdp, identity }))));
|
|
||||||
});
|
|
||||||
@@ -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
|
|
||||||
RUN 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,125 +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 and runs native Node WebSocket
|
|
||||||
clients against the actual tracker server. It tests 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": {
|
"compilerOptions": {
|
||||||
"target": "ES2023",
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"moduleResolution": "Bundler",
|
"moduleResolution": "bundler",
|
||||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
"types": ["vite/client"],
|
||||||
"types": ["node", "vite/client"],
|
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"noUnusedLocals": true,
|
"noUnusedLocals": true,
|
||||||
"noUnusedParameters": true,
|
"noUnusedParameters": true,
|
||||||
"noEmit": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"allowImportingTsExtensions": true,
|
"noUncheckedIndexedAccess": true,
|
||||||
"verbatimModuleSyntax": true,
|
"verbatimModuleSyntax": true,
|
||||||
"isolatedModules": 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 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.
|
const DEV_STYLE_SRC = "style-src 'self'";
|
||||||
export default defineConfig(({ mode }) => {
|
|
||||||
const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env };
|
export default defineConfig({
|
||||||
return {
|
plugins: [
|
||||||
base: './',
|
vue(),
|
||||||
server: { host: '127.0.0.1' },
|
// index.html's Content-Security-Policy allows no inline styles, the dev server injects the CSS
|
||||||
plugins: [vue(), {
|
// through JavaScript. A nonce lets only those style elements through, so the dev server enforces
|
||||||
name: 'local-turn-credentials',
|
// the same policy as the production build, which links the CSS as files.
|
||||||
configureServer(server) {
|
{
|
||||||
if (env.VITE_ICE_ENDPOINT === '/api/ice-servers') server.middlewares.use(iceMiddleware(env));
|
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