Compare commits
59
Commits
58c3e2af86
..
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 | ||
|
|
e3af2de051 | ||
|
|
8665d04f2c | ||
|
|
a73b3075b6 | ||
|
|
5f8c6a1916 |
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
|
||||||
-114
@@ -1,114 +0,0 @@
|
|||||||
# Changelog
|
|
||||||
|
|
||||||
## Unreleased
|
|
||||||
|
|
||||||
- Add opt-in hosted device identities and saved contacts, with fresh mutual
|
|
||||||
signatures bound to both connection fingerprints before remembered verification.
|
|
||||||
- Add contact removal, identity reset, and password-encrypted backup/restore.
|
|
||||||
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.
|
|
||||||
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers
|
|
||||||
must update; v2 codes are rejected before connection setup.
|
|
||||||
- Document the hosted-first, serverless UX roadmap.
|
|
||||||
|
|
||||||
## [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,359 +1,176 @@
|
|||||||
# HellCon
|
# HellCon
|
||||||
|
|
||||||
Current version: **0.0.4**. 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
|
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
|
||||||
explicit opt-in by both people; no relay is configured automatically.
|
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.
|
||||||
|
|
||||||
|
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
|
||||||
|
tab was doing.
|
||||||
|
|
||||||
|
Both sides need the same protocol, shown at the bottom of the page. A HellCon hosted elsewhere may
|
||||||
|
run another one, the receiver then finds no sender, or with **Manual** says the sender runs another
|
||||||
|
protocol.
|
||||||
|
|
||||||
|
### Without a tracker
|
||||||
|
|
||||||
|
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
|
||||||
|
long block of text, and sends it to the receiver any way you like, e.g. a chat or an email. The
|
||||||
|
receiver pastes it, creates an answer and sends that back. The sender pastes the answer and clicks
|
||||||
|
**Connect**. The offer and answer contain your network addresses, so only share them with the person
|
||||||
|
you're sending to. Both sides then compare the security check (see below) and click **Codes match**.
|
||||||
|
|
||||||
|
## 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 explicitly accepts the file.
|
|
||||||
On the hosted app (HTTPS or localhost), **Receive as download** shows the incoming file size and streams into the browser's download manager using a same-origin service worker.
|
|
||||||
It 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.
|
|
||||||
**Choose destination & receive to disk** remains available with a supported
|
|
||||||
native file picker. **Receive in memory** retains its 64 MiB cap. Even capped
|
|
||||||
memory downloads 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. Completed memory downloads remain available after
|
your browser's download list.
|
||||||
disconnect. Save a previous memory download before accepting another file;
|
|
||||||
acceptance replaces it. **Reset** discards the memory download 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. The local HTML supports the same manual flow.
|
|
||||||
|
|
||||||
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 devices** and choose **Create device
|
## Host your own
|
||||||
identity** on both browsers. Enable **Use my device identity for this connection**,
|
|
||||||
exchange codes, and compare both full fingerprints for the first pairing. Once
|
|
||||||
connected, give the peer a local nickname and choose **Remember device**.
|
|
||||||
|
|
||||||
For later connections, enable your identity and select the **Expected device**
|
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
|
||||||
on each side before exchanging fresh codes. HellCon checks fresh signed proofs
|
|
||||||
bound to both device keys and both connection fingerprints. A matching saved key
|
|
||||||
can replace manual fingerprint comparison; file acceptance is still required.
|
|
||||||
A changed or missing identity requires manual comparison and never overwrites a
|
|
||||||
saved contact. Nicknames stay local. Public identities in codes can link sessions.
|
|
||||||
|
|
||||||
Use **Forget** to remove a contact, or explicitly delete your identity and contacts.
|
|
||||||
Encrypted backup/restore includes both, protected by a password of at least 12
|
|
||||||
characters. Keep that password separately. Clearing site data loses saved trust;
|
|
||||||
restoring a backup on another browser gives it the same identity. Browser-stored
|
|
||||||
keys remain accessible to trusted app code and are not protection against a
|
|
||||||
malicious host. Identity use defaults off after reload. Storage failure leaves
|
|
||||||
temporary connections available; downloaded local HTML stays manual.
|
|
||||||
|
|
||||||
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 backup format](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.
|
|
||||||
|
|
||||||
## Download and run locally
|
|
||||||
|
|
||||||
Run `bun run build`, then open `dist/hellcon-local.html` directly in a browser.
|
|
||||||
This single HTML file includes the app code, styles, and icon. A hosted production
|
|
||||||
build also offers **Download app for local use**. Download that file instead of
|
|
||||||
using the browser's **Save Page As** command, which may save only the hosted page
|
|
||||||
without its required assets. You can share the downloaded HTML file with the
|
|
||||||
other participant; both can open it from disk. No web server is needed to load
|
|
||||||
the app itself.
|
|
||||||
|
|
||||||
The app still needs network access to connect peers on different machines, and
|
|
||||||
the selected STUN or TURN servers must be reachable. A `file://` copy cannot use
|
|
||||||
the host's managed TURN credential endpoint; enter your own relay details when
|
|
||||||
needed. Service-worker downloads are **disabled for `file://` copies**; there is
|
|
||||||
no hosted helper dependency in the local version. For large local transfers,
|
|
||||||
use desktop Chrome with its native save picker and select **Choose destination
|
|
||||||
& receive to disk**. Brave may disable that API even though it is Chromium-based.
|
|
||||||
Native disk access still depends on browser settings and platform support.
|
|
||||||
The 64 MiB in-memory receive option remains available.
|
|
||||||
|
|
||||||
To self-host the regular multi-file build, serve the whole `dist/` directory,
|
|
||||||
including `assets/`. Serve it over HTTPS for access from other machines.
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
### Local STUN/TURN environment (Linux)
|
|
||||||
|
|
||||||
Keep Vite on the host for hot reload; only coturn runs in Docker. Both bind to
|
|
||||||
loopback, so use two browser tabs on this machine. No DNS, certificates, firewall
|
|
||||||
changes or production services are needed. Nothing is enabled at boot, and the
|
|
||||||
container has no automatic restart policy.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Start Docker only when needed (if it isn't already running).
|
pnpm install
|
||||||
sudo systemctl start docker.service
|
pnpm build
|
||||||
# If you just joined the docker group, log in again or run: newgrp docker
|
|
||||||
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
|
Then serve the `dist/` folder, with these requirements:
|
||||||
TURN relay** in both tabs. Leave **Use the configured relay with temporary
|
|
||||||
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
|
- **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for
|
||||||
bun run test # protocol and temporary-credential unit tests
|
trying it out).
|
||||||
bun run test:turn # real Chromium file transfer, forced TURN/UDP
|
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
|
||||||
bun run test:turn --tcp # same test, TURN/TCP only
|
HellCon must reach it unchanged, so don't rewrite them to `index.html`. Any path works, e.g.
|
||||||
bun run build
|
`https://example.org/hellcon/`, with the trailing slash: the page links its files relative to it,
|
||||||
bun run test:browser # direct-path browser regressions and axe accessibility checks
|
so redirect `/hellcon` there.
|
||||||
docker compose --env-file .env.development logs --tail=50 coturn
|
|
||||||
|
Recommended, as response headers, a `<meta>` can't set them (`index.html` sets
|
||||||
|
`Referrer-Policy: no-referrer` and the rest of its Content-Security-Policy itself, which keeps out
|
||||||
|
scripts and styles from elsewhere but allows connections to any tracker):
|
||||||
|
|
||||||
|
```
|
||||||
|
Content-Security-Policy: frame-ancestors 'none'
|
||||||
|
X-Frame-Options: DENY
|
||||||
|
X-Content-Type-Options: nosniff
|
||||||
```
|
```
|
||||||
|
|
||||||
The TURN checks start and stop their own Vite server and isolated browser profiles;
|
The first two keep other sites from framing HellCon and laying their own page over its buttons,
|
||||||
coturn must already be running. They obtain real temporary credentials, force
|
`X-Frame-Options` for older browsers.
|
||||||
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:
|
Your own tracker and STUN server are optional, any public ones work. `backend/` has both as Docker
|
||||||
|
Compose services: a tracker that only does what HellCon needs, with an Origin allowlist and limits,
|
||||||
|
and coturn as STUN server. `backend/compose.yaml` says how to set them up.
|
||||||
|
|
||||||
```sh
|
If you change how HellCon talks to the other side, e.g. the code, the encryption or the messages,
|
||||||
bun run turn:down
|
give `PROTOCOL` in `src/core.ts` a name of your own, e.g. `yourname/1`, and count up from there.
|
||||||
# Optional: stop Docker too, after finishing any other containers.
|
|
||||||
sudo systemctl stop docker.service docker.socket containerd.service
|
|
||||||
```
|
|
||||||
|
|
||||||
`.env.development` contains the private shared `TURN_SECRET`, server-side
|
## Not planned
|
||||||
`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` settings.
|
|
||||||
See [.env.example](.env.example). The secret never enters the client bundle.
|
|
||||||
Compose passes it directly to coturn; no config-file environment substitution is
|
|
||||||
assumed. If changing the port, update both `TURN_PORT` and `VITE_STUN_URL`, then
|
|
||||||
rerun `turn:up` and restart Vite. The image is pinned to a concrete release;
|
|
||||||
loopback listeners and UDP relay ports 49160–49200 are defined in [compose.yaml](compose.yaml).
|
|
||||||
Loopback peer access is explicitly allowed for these local tests.
|
|
||||||
|
|
||||||
The credential endpoint is **development-only**, implemented as Vite middleware.
|
These were considered and decided against, please don't ask for them without a new reason. HellCon
|
||||||
It isn't included in `dist/` or `vite preview`. Production builds ignore
|
is copy and paste a code, with public trackers and STUN servers. Anything that puts state in the URL,
|
||||||
`.env.development` and retain the existing static/manual configuration. To reuse
|
needs infrastructure of its own or only helps small files doesn't pay off.
|
||||||
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.
|
- **The code in a share link:** the code would end up in the browser history and wherever links get
|
||||||
Automatic renewal during long transfers is not implemented because this app
|
handled, for one click less.
|
||||||
uses manual signaling. Keep development transfers below that duration; expired
|
- **Another code alphabet,** e.g. one that ignores case or uses words: most people copy and paste
|
||||||
or failed sessions need fresh codes.
|
the code anyway.
|
||||||
|
- **Saving without the service worker,** holding the file in memory instead: useless for files of
|
||||||
|
several GB.
|
||||||
|
- **TURN servers or a relay-only mode:** too much infrastructure to host and test.
|
||||||
|
- **A longer or extendable share,** **several files as a zip,** and **resuming in Chromium:** not
|
||||||
|
for now.
|
||||||
|
- **Keeping a phone sending in the background,** e.g. with a silent audio loop: the sender's page
|
||||||
|
has to stay in front.
|
||||||
|
|
||||||
Configuration references: [coturn Docker usage](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md)
|
## Known limitations
|
||||||
and [coturn configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf).
|
|
||||||
|
|
||||||
### Existing checks and static build
|
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
|
||||||
|
but Firefox keeps showing the download as in progress until you cancel it.
|
||||||
Use Bun for dependency installation and Node.js 22.18+ for the scripts and tests.
|
- **Chromium:** notices a vanished sender only after about 16 seconds.
|
||||||
All application code, Vue scripts, development middleware, and checks use strict
|
- An interrupted transfer can't be resumed, it starts over.
|
||||||
TypeScript. `vue-tsc` checks both TypeScript and Vue templates, and runs before
|
- **Phones:** the sender's page has to stay in front, the connection is lost once it goes to the
|
||||||
every production build. TypeScript stays on 5.9 until Vue's checker supports the
|
background. Receiving keeps going.
|
||||||
TypeScript 7 compiler.
|
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
|
||||||
|
work, and HellCon tells you so.
|
||||||
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: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,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,90 +0,0 @@
|
|||||||
# Remembered-device protocol and storage
|
|
||||||
|
|
||||||
Phase 3 adds optional hosted-browser identities. Temporary sessions still use
|
|
||||||
manual fingerprint comparison. The local HTML never opens identity storage.
|
|
||||||
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.
|
|
||||||
|
|
||||||
A local user either compares both full fingerprints or explicitly selects an
|
|
||||||
expected saved public key. A nickname alone has no protocol meaning. A matching
|
|
||||||
expected 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 saved contact automatically. 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.
|
|
||||||
|
|
||||||
Contacts may only be saved after both peers' ready frames pass verification.
|
|
||||||
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 nicknames are added
|
|
||||||
to diagnostic logs, and nicknames are not sent to peers.
|
|
||||||
|
|
||||||
## Storage and recovery
|
|
||||||
|
|
||||||
IndexedDB holds a CryptoKey private key, the public key, and at most 100 contacts.
|
|
||||||
Keys are extractable to support user-requested backups. Browser storage does not
|
|
||||||
protect against compromised app code, a hostile host, or compromised browser.
|
|
||||||
The identity-use checkbox defaults off after page load. Clearing site data loses
|
|
||||||
identity and contacts; an empty store never creates trust automatically. Storage
|
|
||||||
errors leave temporary sessions available. Unreadable storage can be explicitly
|
|
||||||
cleared before restoring a backup. Atomic revision checks reject stale writes
|
|
||||||
from other tabs instead of overwriting a newer identity or contact list. Controls for deletion/restoration
|
|
||||||
require explicit replacement consent and are disabled during a session.
|
|
||||||
Before each identity-enabled connection, settings are read again from storage.
|
|
||||||
A contact forgotten in another tab loses automatic verification on the next
|
|
||||||
connection; a replaced or deleted local identity requires opting in again.
|
|
||||||
A failed refresh stops setup instead of using cached trust.
|
|
||||||
|
|
||||||
The v1 backup is JSON containing `format: "hellcon-identity"`, `version: 1`,
|
|
||||||
`iterations: 600000`, a 16-byte random salt, 12-byte random IV, and ciphertext.
|
|
||||||
Salt, IV, and ciphertext use lowercase hex. PBKDF2-HMAC-SHA-256 with 600,000
|
|
||||||
iterations derives an AES-256-GCM key from the password (12–1024 characters,
|
|
||||||
UTF-8 without normalization). AES-GCM uses the default 128-bit authentication
|
|
||||||
tag and additional authenticated data `HellCon backup v1`. The encrypted JSON
|
|
||||||
contains the private JWK, public key, and contacts. Passwords are cleared from
|
|
||||||
the UI after operations and are never stored. Backup input is capped at 100 KB;
|
|
||||||
unsupported versions/iteration counts, malformed fields, wrong passwords, failed
|
|
||||||
authentication tags, invalid contacts, and mismatched private/public keys are
|
|
||||||
rejected before replacing stored data. Restoring a backup clones that identity;
|
|
||||||
there is no central revocation service. Contacts 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, backup tampering and incorrect
|
|
||||||
passwords, 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,104 +0,0 @@
|
|||||||
# Serverless UX roadmap
|
|
||||||
|
|
||||||
The hosted HTTPS app is the primary experience. The downloadable HTML must keep
|
|
||||||
working for basic manual connection and file transfer; it need not match hosted
|
|
||||||
conveniences. No signaling backend, peer presence service, automatic offline-peer
|
|
||||||
reconnection, or silent TURN fallback is in scope.
|
|
||||||
|
|
||||||
## 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, streaming downloads, and the local HTML.
|
|
||||||
|
|
||||||
## 3. Remember trusted devices — implemented
|
|
||||||
|
|
||||||
The hosted app offers opt-in device identities and up to 100 named contacts in
|
|
||||||
browser storage. First pairing requires manual fingerprint comparison; contacts
|
|
||||||
can be saved only after successful mutual verification. Later connections can
|
|
||||||
select an expected saved public key and verify fresh signed proofs bound to both
|
|
||||||
keys, both nonces, both DTLS fingerprints, and participant roles. Nicknames and
|
|
||||||
saved codes never authenticate a peer. Changed or missing identities require
|
|
||||||
manual comparison and never replace saved contacts automatically.
|
|
||||||
|
|
||||||
Temporary sessions remain the default, and every file still requires acceptance.
|
|
||||||
Contact removal, identity deletion, encrypted backup/restore, storage failure
|
|
||||||
fallback, unreadable-storage recovery, and conflicting-tab write protection are
|
|
||||||
implemented. The local HTML remains manual. 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,
|
|
||||||
wrong backup passwords and tampering, 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. Local HTML only needs manual codes.
|
|
||||||
|
|
||||||
## 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.
|
|
||||||
+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
-19
@@ -1,35 +1,38 @@
|
|||||||
{
|
{
|
||||||
"name": "hellcon",
|
"name": "hellcon",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.4",
|
"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",
|
|
||||||
"test:turn": "node scripts/browser-check.ts --turn",
|
|
||||||
"build": "vue-tsc --noEmit && vite build && node scripts/build-local.ts",
|
|
||||||
"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,481 +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 } from 'node:fs/promises';
|
|
||||||
import { createReadStream } from 'node:fs';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import { dirname, extname, join, resolve } from 'node:path';
|
|
||||||
import { fileURLToPath, pathToFileURL } 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 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 {
|
|
||||||
'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);
|
|
||||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
|
|
||||||
if (streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = 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) assert.ok(await evaluate(sender, () => document.body.textContent?.includes('Device identity differs from the expected contact')));
|
|
||||||
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');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (streaming) {
|
|
||||||
const downloads = join(profile, 'downloads');
|
|
||||||
await mkdir(downloads);
|
|
||||||
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
|
|
||||||
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, `Receive as download (${size === 0 ? '0 B' : (size / 1024 ** 2).toFixed(1) + ' MiB'})`);
|
|
||||||
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/);
|
|
||||||
const destination = join(downloads, 'browser-test.bin');
|
|
||||||
const deadline = Date.now() + 30000;
|
|
||||||
while (true) {
|
|
||||||
try { if ((await stat(destination)).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(destination)) {
|
|
||||||
assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match');
|
|
||||||
bytes += (chunk as Buffer).length;
|
|
||||||
}
|
|
||||||
assert.equal(bytes, size);
|
|
||||||
await rm(destination);
|
|
||||||
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');
|
|
||||||
}
|
|
||||||
if (!turn) {
|
|
||||||
const localUrl = pathToFileURL(join(root, 'dist/hellcon-local.html')).href;
|
|
||||||
const localReceiver = await page(localUrl);
|
|
||||||
assert.equal(await evaluate(localReceiver, () => document.querySelector<HTMLSelectElement>('#stun-provider')?.value), 'pagequit');
|
|
||||||
assert.equal(await evaluate(localReceiver, () => document.querySelector('h1')?.textContent), 'HellCon');
|
|
||||||
await click(localReceiver, 'Receive');
|
|
||||||
assert.equal(await evaluate(localReceiver, () => !!document.querySelector('#offer-input')), true);
|
|
||||||
const localSender = await page(localUrl);
|
|
||||||
await connect(localSender, localReceiver, 1024);
|
|
||||||
assert.equal(await evaluate(localReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent?.includes('Receive as download'))), false, 'file:// must not offer service-worker downloads');
|
|
||||||
await click(localReceiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
await wait(localReceiver, () => !!document.querySelector('a.download'));
|
|
||||||
const data = await evaluate(localReceiver, async () => {
|
|
||||||
const bytes = new Uint8Array(await (await fetch(document.querySelector<HTMLAnchorElement>('a.download')!.href)).arrayBuffer());
|
|
||||||
return { length: bytes.length, valid: bytes.every(byte => byte === 123) };
|
|
||||||
});
|
|
||||||
assert.deepEqual(data, { length: 1024, valid: true });
|
|
||||||
console.log('PASS: standalone HTML opens from file:// and transfers a file between two local copies.');
|
|
||||||
}
|
|
||||||
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, 'Receive in memory (up to 64 MiB)');
|
|
||||||
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 });
|
|
||||||
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.');
|
|
||||||
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, 'Receive in memory (up to 64 MiB)');
|
|
||||||
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, 'Receive in memory (up to 64 MiB)');
|
|
||||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
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, 'Choose destination & receive to disk');
|
|
||||||
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 connect(sender, receiver, 2048);
|
|
||||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
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 identityReceiver = await page(origin.replace('127.0.0.1', 'localhost'));
|
|
||||||
await click(identityReceiver, 'Receive');
|
|
||||||
for (const session of [identitySender, identityReceiver]) {
|
|
||||||
await evaluate(session, () => { const details = [...document.querySelectorAll('details')].find(el => el.querySelector('summary')?.textContent === 'Remembered devices'); 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>('#use-device-identity')?.checked);
|
|
||||||
}
|
|
||||||
await connect(identitySender, identityReceiver, 2048);
|
|
||||||
for (const session of [identitySender, identityReceiver]) {
|
|
||||||
await wait(session, () => !!document.querySelector('#contact-name'));
|
|
||||||
await input(session, '#contact-name', 'Paired device');
|
|
||||||
await click(session, 'Remember device');
|
|
||||||
await wait(session, () => !document.querySelector('#contact-name'));
|
|
||||||
}
|
|
||||||
await checkAccessibility(identitySender, 'remembered identity');
|
|
||||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
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 contacts.
|
|
||||||
for (const [session, url] of [[identitySender, origin], [identityReceiver, origin.replace('127.0.0.1', 'localhost')]]) {
|
|
||||||
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('#use-device-identity'));
|
|
||||||
assert.equal(await evaluate(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')!.checked), false, 'Reload defaults to a temporary connection');
|
|
||||||
await evaluate(session, () => document.querySelector<HTMLInputElement>('#use-device-identity')!.click());
|
|
||||||
const key = await evaluate(session, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options[1]!.value);
|
|
||||||
await input(session, '#expected-device', key);
|
|
||||||
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('Remembered device authenticated')));
|
|
||||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
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 contacts persist across reload; fresh mutual proofs authenticate remembered devices 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]) {
|
|
||||||
const editor = await page(forgottenSide === identitySender ? origin : origin.replace('127.0.0.1', 'localhost'));
|
|
||||||
await wait(editor, () => !!document.querySelector('#expected-device'));
|
|
||||||
await click(editor, 'Forget');
|
|
||||||
await wait(editor, () => document.querySelector<HTMLSelectElement>('#expected-device')?.options.length === 1);
|
|
||||||
assert.ok(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), 'Original tab still has the stale expected contact before connection setup');
|
|
||||||
|
|
||||||
await evaluate(identitySender, () => window.__hellcon.chooseFile(128, 'forgotten-contact.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 evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.value), '');
|
|
||||||
assert.equal(await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options.length), 1);
|
|
||||||
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 click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
|
||||||
await input(forgottenSide, '#contact-name', 'Paired device'); await click(forgottenSide, 'Remember device');
|
|
||||||
await wait(forgottenSide, () => !document.querySelector('#contact-name'));
|
|
||||||
await click(identitySender, 'Disconnect');
|
|
||||||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
|
||||||
await click(identitySender, 'Reset'); await click(identityReceiver, 'Reset');
|
|
||||||
const key = await evaluate(forgottenSide, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options[1]!.value);
|
|
||||||
await input(forgottenSide, '#expected-device', key);
|
|
||||||
}
|
|
||||||
console.log('PASS: forgetting a device in another tab removes stale trust before either role reconnects; manual confirmation gates metadata and permits pairing 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 contact.');
|
|
||||||
|
|
||||||
await evaluate(identityReceiver, () => {
|
|
||||||
const label = [...document.querySelectorAll('label')].find(el => el.textContent?.includes('Replace or delete'));
|
|
||||||
label?.querySelector<HTMLInputElement>('input')?.click();
|
|
||||||
});
|
|
||||||
await click(identityReceiver, 'Delete identity and contacts');
|
|
||||||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Create device identity'));
|
|
||||||
await click(identityReceiver, 'Create device identity');
|
|
||||||
await wait(identityReceiver, () => document.querySelector<HTMLInputElement>('#use-device-identity')?.checked);
|
|
||||||
await connect(identitySender, identityReceiver, 512, true);
|
|
||||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
|
||||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
|
||||||
assert.equal(await evaluate(identitySender, () => document.querySelector<HTMLSelectElement>('#expected-device')!.options.length), 2, 'Changed identity must not replace or append saved contacts automatically');
|
|
||||||
console.log('PASS: replaced peer identity requires manual comparison and preserves the original saved contact.');
|
|
||||||
const stale = await page();
|
|
||||||
await wait(stale, () => !!document.querySelector('#use-device-identity'));
|
|
||||||
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 click(stale, 'Forget');
|
|
||||||
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: null, contacts: 'broken', revision: 'broken' }, 'state'); tx.oncomplete = () => resolve(); }); db.close();
|
|
||||||
});
|
|
||||||
await call('Page.navigate', { url: origin }, stale);
|
|
||||||
await wait(stale, () => document.body.textContent?.includes('Invalid contact list'));
|
|
||||||
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 contact 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,103 +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 => button.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,25 +0,0 @@
|
|||||||
import { readFile, writeFile } from 'node:fs/promises';
|
|
||||||
import { dirname, join, resolve } from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
|
|
||||||
const dist = resolve(dirname(fileURLToPath(import.meta.url)), '../dist');
|
|
||||||
let html = await readFile(join(dist, 'index.html'), 'utf8');
|
|
||||||
|
|
||||||
const scriptTag = /<script type="module"(?: [^>]*)? src="(\.\/assets\/[^"<>]+\.js)"><\/script>/;
|
|
||||||
const scriptPath = html.match(scriptTag)?.[1];
|
|
||||||
if (!scriptPath) throw new Error('Expected a Vite JavaScript asset in dist/index.html');
|
|
||||||
|
|
||||||
const [javascript, icon] = await Promise.all([
|
|
||||||
readFile(join(dist, scriptPath)),
|
|
||||||
readFile(join(dist, 'HellNet_alt.png')),
|
|
||||||
]);
|
|
||||||
const js = javascript.toString('utf8');
|
|
||||||
if (/<\/script/i.test(js)) throw new Error('Built JavaScript contains an unsafe inline closing tag');
|
|
||||||
|
|
||||||
html = html.replace(scriptTag, '');
|
|
||||||
html = html.replace('href="./HellNet_alt.png"', `href="data:image/png;base64,${icon.toString('base64')}"`);
|
|
||||||
html = html.replace('</body>', () => ` <script>${js}</script>\n </body>`);
|
|
||||||
if (/src="\.\/assets\/|href="\.\/assets\/|href="\.\/HellNet_alt\.png"/.test(html)) {
|
|
||||||
throw new Error('Standalone HTML still references external build assets');
|
|
||||||
}
|
|
||||||
await writeFile(join(dist, 'hellcon-local.html'), html);
|
|
||||||
@@ -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,72 +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, mkdtemp, rm } 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);
|
|
||||||
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,62 +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;
|
|
||||||
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('Receive in memory (up to 64 MiB)');
|
|
||||||
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.');
|
|
||||||
}
|
|
||||||
+618
-34
@@ -1,50 +1,634 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from 'vue';
|
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
|
||||||
import TransferPanel from './components/TransferPanel.vue';
|
import {
|
||||||
|
answerOffer,
|
||||||
|
type Check,
|
||||||
|
settings as coreSettings,
|
||||||
|
createOffer,
|
||||||
|
DEFAULT_STUN_SERVERS,
|
||||||
|
DEFAULT_TRACKERS,
|
||||||
|
type Events,
|
||||||
|
formatTime,
|
||||||
|
type Incoming,
|
||||||
|
type Phase,
|
||||||
|
PROTOCOL,
|
||||||
|
type ReceiveEvents,
|
||||||
|
randomCode,
|
||||||
|
receiveViaTracker,
|
||||||
|
type SendEvents,
|
||||||
|
sendViaTracker,
|
||||||
|
} from './core';
|
||||||
|
|
||||||
const mode = ref<'send' | 'receive'>('send');
|
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
|
||||||
const sessionActive = ref(false);
|
// defaults.
|
||||||
const connected = ref(false);
|
const settings = reactive(coreSettings);
|
||||||
const direction = ref<'send' | 'receive'>('send');
|
|
||||||
const panel = ref<InstanceType<typeof TransferPanel> | null>(null);
|
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
|
||||||
function navigate(next: 'send' | 'receive') {
|
const ownSalt = reactive({ on: false, text: '' });
|
||||||
if (connected.value) { direction.value = next; panel.value?.focusDirection(next); }
|
// Empty is no salt, Share and Receive wait for one.
|
||||||
else if (!sessionActive.value) mode.value = next;
|
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
|
||||||
|
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
|
||||||
|
// From the code's alphabet, 16 characters are about 95 bits.
|
||||||
|
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
|
||||||
|
|
||||||
|
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
|
||||||
|
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
|
||||||
|
// contacts nobody before an offer, but typing makes one per keystroke, so each line is checked once.
|
||||||
|
const stunChecks = new Map<string, boolean>();
|
||||||
|
function isStun(url: string) {
|
||||||
|
if (!stunChecks.has(url)) {
|
||||||
|
try {
|
||||||
|
new RTCPeerConnection({ iceServers: [{ urls: url }] }).close();
|
||||||
|
stunChecks.set(url, /^stuns?:/i.test(url));
|
||||||
|
} catch {
|
||||||
|
stunChecks.set(url, false);
|
||||||
}
|
}
|
||||||
const isLocal = location.protocol === 'file:';
|
}
|
||||||
const canDownloadApp = import.meta.env.PROD && !isLocal;
|
return stunChecks.get(url)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// public/ in the build, which works under any path, see vite.config.ts.
|
||||||
|
const BASE = import.meta.env.BASE_URL;
|
||||||
|
|
||||||
|
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
|
||||||
|
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
|
||||||
|
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
|
||||||
|
const secure = location.protocol === 'https:';
|
||||||
|
const isLocal = (hostname: string) =>
|
||||||
|
hostname === 'localhost' ||
|
||||||
|
hostname.endsWith('.localhost') ||
|
||||||
|
/^127\.\d+\.\d+\.\d+$/.test(hostname) ||
|
||||||
|
hostname === '[::1]';
|
||||||
|
const isTracker = (url: string) => {
|
||||||
|
if (!URL.canParse(url) || url.includes('#')) return false;
|
||||||
|
const { protocol, hostname } = new URL(url);
|
||||||
|
return protocol === 'wss:' || (protocol === 'ws:' && (!secure || isLocal(hostname)));
|
||||||
|
};
|
||||||
|
|
||||||
|
// A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped.
|
||||||
|
function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
|
||||||
|
const text = ref(settings[key].join('\n'));
|
||||||
|
const lines = computed(() =>
|
||||||
|
text.value
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
);
|
||||||
|
const invalid = computed(() => lines.value.filter((line) => !valid(line)));
|
||||||
|
// Immediate, a default may be a line this browser rejects.
|
||||||
|
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
|
||||||
|
// Unwraps both refs, so the template can bind them as plain properties.
|
||||||
|
return reactive({ text, invalid });
|
||||||
|
}
|
||||||
|
|
||||||
|
const stunServers = serverList('stunServers', isStun);
|
||||||
|
const trackers = serverList('trackers', isTracker);
|
||||||
|
|
||||||
|
function onResetServers() {
|
||||||
|
stunServers.text = DEFAULT_STUN_SERVERS.join('\n');
|
||||||
|
trackers.text = DEFAULT_TRACKERS.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} catch {
|
||||||
|
events.log('copy failed, the browser blocked the clipboard');
|
||||||
|
copied.value = { text, ok: false };
|
||||||
|
const element = document.getElementById(id);
|
||||||
|
if (element instanceof HTMLTextAreaElement) {
|
||||||
|
element.focus();
|
||||||
|
element.select();
|
||||||
|
} else if (element) getSelection()?.selectAllChildren(element);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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>
|
||||||
<main id="main-content" tabindex="-1">
|
<div>
|
||||||
|
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
|
||||||
<h1>HellCon</h1>
|
<h1>HellCon</h1>
|
||||||
<p class="subtitle">
|
</div>
|
||||||
Browser-to-browser file sharing. No account or file-hosting backend.
|
<div id="options">
|
||||||
Direct WebRTC connections, with an optional relay you explicitly enable.
|
<div>
|
||||||
|
<label>
|
||||||
|
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||||
|
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
|
||||||
|
Use STUN
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
|
||||||
|
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
|
||||||
|
Use own salt
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div v-if="ownSalt.on" role="group">
|
||||||
|
<input
|
||||||
|
id="salt"
|
||||||
|
v-model="ownSalt.text"
|
||||||
|
aria-label="Own salt"
|
||||||
|
placeholder="Same salt on both sides"
|
||||||
|
:aria-invalid="saltMissing"
|
||||||
|
:disabled="saltLocked"
|
||||||
|
autocapitalize="off"
|
||||||
|
autocomplete="off"
|
||||||
|
autocorrect="off"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
|
||||||
|
Generate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</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>
|
||||||
<a v-if="canDownloadApp" class="app-download" href="./hellcon-local.html" download="HellCon.html">Download app for local use</a>
|
<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>
|
||||||
|
|
||||||
<p v-if="canDownloadApp || isLocal" class="status">For large files in the downloaded local version, use desktop Chrome on the receiving machine and choose “Choose destination & receive to disk”.</p>
|
<article>
|
||||||
|
<h2>Send</h2>
|
||||||
<div class="tabs" role="group" :aria-label="connected ? 'Transfer sections' : 'Connection setup'">
|
<label
|
||||||
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'send' }" :aria-pressed="(connected ? direction : mode) === 'send'" @click="navigate('send')">Send</button>
|
:data-dragging="dragging || undefined"
|
||||||
<button :disabled="sessionActive && !connected" :class="{ active: (connected ? direction : mode) === 'receive' }" :aria-pressed="(connected ? direction : mode) === 'receive'" @click="navigate('receive')">Receive</button>
|
@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>
|
</div>
|
||||||
|
|
||||||
<p v-if="connected" class="status">Connected — either person can send files. Send and Receive jump to those sections without interrupting transfers.</p>
|
<section>
|
||||||
<p v-else-if="sessionActive" class="status">Finish connecting and verifying first. Then either person can send and receive.</p>
|
<h3>Tracker</h3>
|
||||||
<TransferPanel ref="panel" :key="mode" :sending="mode === 'send'" @session-change="sessionActive = $event" @connected-change="connected = $event; direction = mode" />
|
<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>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>
|
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
|
||||||
Files travel over encrypted WebRTC data channels (SCTP over DTLS).
|
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
|
||||||
Compare both full fingerprints on first pairing, or authenticate an expected remembered device. This requires trusted
|
Source code
|
||||||
browsers, a trusted copy of this app, and an authenticated comparison
|
</a>
|
||||||
channel. The website host supplies JavaScript that can read your selected
|
<span>Protocol {{ PROTOCOL }}</span>
|
||||||
file; HTTPS protects delivery but cannot protect you from a malicious host.
|
|
||||||
A TURN relay is used only after opt-in and carries encrypted traffic.
|
|
||||||
</p>
|
|
||||||
</footer>
|
</footer>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
|
|
||||||
import { clearIdentityStorage, createIdentity, loadIdentityState, saveIdentityState, exportBackup, importBackup, type IdentityState } from '../lib/identity.ts';
|
|
||||||
import { asError } from '../lib/validation.ts';
|
|
||||||
const props = defineProps<{ disabled: boolean }>();
|
|
||||||
const emit = defineEmits<{ change: [state: IdentityState, enabled: boolean, expected: string] }>();
|
|
||||||
const supported = (() => { try { return location.protocol !== 'file:' && isSecureContext && !!crypto.subtle && !!window.indexedDB; } catch { return false; } })();
|
|
||||||
const state = shallowRef<IdentityState>({ identity: null, contacts: [] });
|
|
||||||
const enabled = ref(false), expected = ref(''), working = ref(false), loaded = ref(false);
|
|
||||||
const error = ref(''), password = ref(''), confirmReplace = ref(false);
|
|
||||||
const backupUrl = ref('');
|
|
||||||
onBeforeUnmount(() => { if (backupUrl.value) URL.revokeObjectURL(backupUrl.value); });
|
|
||||||
watch([state, enabled, expected], () => emit('change', state.value, enabled.value, expected.value));
|
|
||||||
onMounted(async () => {
|
|
||||||
if (!supported) return;
|
|
||||||
try { state.value = await loadIdentityState(); loaded.value = true; }
|
|
||||||
catch (err) { error.value = asError(err).message; }
|
|
||||||
});
|
|
||||||
async function store(next: IdentityState) {
|
|
||||||
state.value = await saveIdentityState(next, state.value.revision);
|
|
||||||
if (backupUrl.value) { URL.revokeObjectURL(backupUrl.value); backupUrl.value = ''; }
|
|
||||||
}
|
|
||||||
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; password.value = ''; }
|
|
||||||
}
|
|
||||||
function recover() { void run(async () => { if (!confirmReplace.value) return; await clearIdentityStorage(); state.value = { identity: null, contacts: [] }; loaded.value = true; confirmReplace.value = false; }); }
|
|
||||||
function create() { void run(async () => { await store({ identity: await createIdentity(), contacts: [] }); enabled.value = true; }); }
|
|
||||||
function remove(key: string) { void run(async () => { await store({ ...state.value, contacts: state.value.contacts.filter(item => item.key !== key) }); if (expected.value === key) expected.value = ''; }); }
|
|
||||||
function reset() { void run(async () => { if (!confirmReplace.value) return; await store({ identity: null, contacts: [] }); enabled.value = false; expected.value = ''; confirmReplace.value = false; }); }
|
|
||||||
function backup() { void run(async () => {
|
|
||||||
const data = await exportBackup(state.value, password.value);
|
|
||||||
if (backupUrl.value) URL.revokeObjectURL(backupUrl.value);
|
|
||||||
backupUrl.value = URL.createObjectURL(new Blob([data], { type: 'application/json' }));
|
|
||||||
}); }
|
|
||||||
function restore(event: Event) {
|
|
||||||
const input = event.target as HTMLInputElement, file = input.files?.[0]; input.value = '';
|
|
||||||
if (!file) return;
|
|
||||||
void run(async () => {
|
|
||||||
if (state.value.identity && !confirmReplace.value) throw new Error('Confirm replacement before restoring a backup.');
|
|
||||||
if (file.size > 100000) throw new Error('Backup is too large.');
|
|
||||||
const next = await importBackup(await file.text(), password.value);
|
|
||||||
await store(next); enabled.value = false; expected.value = ''; confirmReplace.value = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async function remember(key: string, name: string) {
|
|
||||||
if (!state.value.identity) throw new Error('Create a local identity first.');
|
|
||||||
const next = { ...state.value, contacts: [...state.value.contacts.filter(item => item.key !== key), { key, name }] };
|
|
||||||
await store(next);
|
|
||||||
}
|
|
||||||
async function refreshForConnection() {
|
|
||||||
if (working.value) throw new Error('Wait for the device settings operation to finish before connecting.');
|
|
||||||
if (!supported || !enabled.value) return { identity: null, expected: '' };
|
|
||||||
try {
|
|
||||||
const next = await loadIdentityState();
|
|
||||||
if (next.identity?.publicKey !== state.value.identity?.publicKey) {
|
|
||||||
enabled.value = false; expected.value = '';
|
|
||||||
}
|
|
||||||
if (!next.contacts.some(contact => contact.key === expected.value)) expected.value = '';
|
|
||||||
if (next.revision !== state.value.revision) {
|
|
||||||
if (backupUrl.value) URL.revokeObjectURL(backupUrl.value);
|
|
||||||
backupUrl.value = ''; confirmReplace.value = false; password.value = '';
|
|
||||||
}
|
|
||||||
state.value = next; loaded.value = true; error.value = '';
|
|
||||||
return { identity: enabled.value ? next.identity : null, expected: expected.value };
|
|
||||||
} catch (err) {
|
|
||||||
error.value = asError(err).message;
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
defineExpose({ remember, refreshForConnection });
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<details v-if="supported">
|
|
||||||
<summary>Remembered devices</summary>
|
|
||||||
<p class="status">Opt in to a device identity stored in this browser. Temporary connections remain available. Clearing site data loses your identity and contacts. Trusted app code is required: it can use and export 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>
|
|
||||||
<label><input id="use-device-identity" v-model="enabled" type="checkbox" /> Use my device identity for this connection</label>
|
|
||||||
<p class="status">Your public identity is included in connection codes when enabled and can link your sessions.</p>
|
|
||||||
<label for="expected-device">Expected device</label>
|
|
||||||
<select id="expected-device" v-model="expected" :disabled="!enabled">
|
|
||||||
<option value="">New device — compare fingerprints manually</option>
|
|
||||||
<option v-for="contact in state.contacts" :key="contact.key" :value="contact.key">{{ contact.name }} ({{ contact.key.slice(-12) }})</option>
|
|
||||||
</select>
|
|
||||||
<ul aria-label="Remembered devices"><li v-for="contact in state.contacts" :key="contact.key">{{ contact.name }} <button @click="remove(contact.key)" :aria-label="'Forget ' + contact.name">Forget</button></li></ul>
|
|
||||||
</template>
|
|
||||||
<label for="backup-password">Backup password (at least 12 characters)</label>
|
|
||||||
<input id="backup-password" v-model="password" type="password" autocomplete="new-password" maxlength="1024" />
|
|
||||||
<button :disabled="!state.identity || password.length < 12" @click="backup">Create encrypted backup</button>
|
|
||||||
<a v-if="backupUrl" :href="backupUrl" download="hellcon-device-backup.json">Save encrypted backup</a>
|
|
||||||
<p class="status">A backup contains your identity and contacts. Keep its password separately. Restoring the same backup on another browser gives that browser the same identity.</p>
|
|
||||||
<label v-if="state.identity"><input v-model="confirmReplace" type="checkbox" /> Replace or delete this browser’s identity and contacts</label>
|
|
||||||
<label for="restore-identity">Restore encrypted backup</label>
|
|
||||||
<input id="restore-identity" type="file" accept="application/json,.json" :disabled="password.length < 12 || (!!state.identity && !confirmReplace)" @change="restore" />
|
|
||||||
<button v-if="state.identity" :disabled="!confirmReplace" @click="reset">Delete identity and contacts</button>
|
|
||||||
</fieldset>
|
|
||||||
<div v-if="!loaded && error">
|
|
||||||
<label><input v-model="confirmReplace" type="checkbox" :disabled="disabled || working" /> Delete unreadable device storage, including identity and contacts</label>
|
|
||||||
<button :disabled="disabled || working || !confirmReplace" @click="recover">Clear device storage</button>
|
|
||||||
</div>
|
|
||||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
|
||||||
</details>
|
|
||||||
</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 = location.protocol === 'file:' ? '' : 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,4 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import TransferPanel from './TransferPanel.vue';
|
|
||||||
</script>
|
|
||||||
<template><TransferPanel /></template>
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import TransferPanel from './TransferPanel.vue';
|
|
||||||
</script>
|
|
||||||
<template><TransferPanel sending /></template>
|
|
||||||
@@ -1,478 +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, shallowRef, 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';
|
|
||||||
|
|
||||||
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 }>();
|
|
||||||
const devices = ref<InstanceType<typeof DeviceSettings> | null>(null);
|
|
||||||
const deviceState = shallowRef<IdentityState>({ identity: null, contacts: [] });
|
|
||||||
const identityStatus = ref(''), contactName = ref('');
|
|
||||||
const canRemember = ref(false), savingContact = ref(false);
|
|
||||||
function deviceChange(state: IdentityState) { deviceState.value = state; }
|
|
||||||
async function saveContact() {
|
|
||||||
const session = active;
|
|
||||||
if (!session?.remoteHello || !connected.value || !canRemember.value || savingContact.value) return;
|
|
||||||
savingContact.value = true;
|
|
||||||
try { await devices.value?.remember(session.remoteHello.key, contactName.value.trim()); canRemember.value = false; contactName.value = ''; }
|
|
||||||
catch (err) { error.value = asError(err).message; }
|
|
||||||
finally { savingContact.value = 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 history = ref<string[]>([]);
|
|
||||||
const emit = defineEmits<{ sessionChange: [active: boolean]; connectedChange: [connected: boolean] }>();
|
|
||||||
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 = location.protocol === 'file:' ? '' : import.meta.env.VITE_ICE_ENDPOINT || '';
|
|
||||||
const defaultStun = location.protocol === 'file:' ? '' : 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);
|
|
||||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
|
||||||
const canStreamDownload = supportsStreamingDownload();
|
|
||||||
const streamedDownload = 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': 'Choose how to receive 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.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'),
|
|
||||||
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 dispose() {
|
|
||||||
const old = active;
|
|
||||||
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 = ''; canRemember.value = false; contactName.value = '';
|
|
||||||
fps.value = incoming.value = null;
|
|
||||||
verified.value = copied.value = choosing.value = false;
|
|
||||||
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; streamedDownload.value = false;
|
|
||||||
sendState.value = receiveState.value = null; outgoing.value = null; history.value = [];
|
|
||||||
}
|
|
||||||
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(message: string) { history.value = [...history.value.slice(-49), message]; }
|
|
||||||
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);
|
|
||||||
if (session.identityContext) {
|
|
||||||
identityStatus.value = session.expected === session.remoteHello?.key ? 'Remembered device authenticated for this connection.' : 'Device proof checked. You can remember this manually verified device.';
|
|
||||||
canRemember.value = !deviceState.value.contacts.some(contact => contact.key === session.remoteHello?.key);
|
|
||||||
}
|
|
||||||
} },
|
|
||||||
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; streamedDownload.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 === 'send' ? 'Sent' : 'Received'}: ${meta.name}`);
|
|
||||||
void session.diagnostics.capture();
|
|
||||||
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; }
|
|
||||||
},
|
|
||||||
onDecline: (direction, meta) => {
|
|
||||||
if (active !== session) return;
|
|
||||||
if (direction === 'send') sendState.value = null; else { receiveState.value = null; incoming.value = null; }
|
|
||||||
remember(`Declined: ${meta.name}`);
|
|
||||||
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 expected peer or replaced the local identity since this page loaded.
|
|
||||||
const device = await devices.value?.refreshForConnection();
|
|
||||||
if (active !== session) return;
|
|
||||||
if (device?.identity) {
|
|
||||||
session.identity = device.identity; session.localHello = hello(device.identity); session.expected = device.expected;
|
|
||||||
}
|
|
||||||
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); 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);
|
|
||||||
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 configureIdentity(session: Session) {
|
|
||||||
if (!fps.value || !session.transfer || session.identityContext) return;
|
|
||||||
if (!session.identity || !session.localHello || !session.remoteHello) {
|
|
||||||
if (session.expected) identityStatus.value = 'Expected device identity is missing. Compare both fingerprints manually; saved trust is not being used.';
|
|
||||||
else if (session.localHello || session.remoteHello) identityStatus.value = 'Both people must enable 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 remembered device’s fresh proof…'; verify();
|
|
||||||
} else {
|
|
||||||
identityStatus.value = session.expected ? 'Device identity differs from the expected contact. Compare both fingerprints manually before continuing. The saved contact will not be replaced.' : '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(destination: 'disk' | 'memory' | 'download') {
|
|
||||||
const session = active;
|
|
||||||
if (!session?.transfer || !incoming.value || 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();
|
|
||||||
streamedDownload.value = destination === 'download';
|
|
||||||
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': 'Choose where to save', 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. Each direction sends one file at a time; both people can send on this connection.</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" :disabled="busy || connected || savingContact" @change="deviceChange" />
|
|
||||||
<NetworkSettings v-model="settings" :disabled="busy || connected" :managed-credentials="managedCredentials" />
|
|
||||||
<p class="status">Connection codes are not encrypted: they can reveal your IP address and connection details to anyone who sees them. Exchange them privately with your intended peer.</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>
|
|
||||||
<button class="primary" :disabled="verified || step === 'done'" @click="verify">{{ verified ? 'Verification submitted' : 'Both fingerprints match — confirm' }}</button>
|
|
||||||
</div>
|
|
||||||
<div v-if="connected && canRemember">
|
|
||||||
<label for="contact-name">Remember this device as</label>
|
|
||||||
<input id="contact-name" v-model="contactName" maxlength="80" />
|
|
||||||
<button :disabled="!contactName.trim() || savingContact" @click="saveContact">Remember device</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="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download ({{ formatBytes(incoming.size) }})</button>
|
|
||||||
<p v-if="canStreamDownload" class="status">Allow the browser download and keep this page open until the transfer finishes. Check Downloads for the final save result.</p>
|
|
||||||
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile('disk')">Choose destination & receive to disk</button>
|
|
||||||
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button>
|
|
||||||
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" class="error">This browser cannot save directly to disk. Use a browser with 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 file</a></div>
|
|
||||||
<p v-if="downloadUrl && receiveState === 'choose-storage'" class="status">Save the previous file before accepting this one. Accepting replaces its memory download.</p>
|
|
||||||
</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>
|
|
||||||
<ul v-if="history.length" aria-label="Recent file results"><li v-for="(entry, index) in history" :key="index">{{ entry }}</li></ul>
|
|
||||||
<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,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,141 +0,0 @@
|
|||||||
import { isRecord } from './validation.ts';
|
|
||||||
|
|
||||||
export interface Identity { publicKey: string; privateKey: CryptoKey }
|
|
||||||
export interface IdentityHello { key: string; nonce: string }
|
|
||||||
export interface Contact { key: string; name: string }
|
|
||||||
export interface IdentityState { revision?: string; identity: Identity | null; contacts: Contact[] }
|
|
||||||
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> {
|
|
||||||
// Extractable for explicit password-encrypted backups. Stored as a CryptoKey,
|
|
||||||
// never plaintext JSON. Same-origin JavaScript can still use/export this key.
|
|
||||||
const pair = await crypto.subtle.generateKey(curve, true, ['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.');
|
|
||||||
}
|
|
||||||
export function validateContacts(value: unknown): Contact[] {
|
|
||||||
if (!Array.isArray(value) || value.length > 100) throw new Error('Invalid contact list.');
|
|
||||||
const keys = new Set<string>();
|
|
||||||
return value.map(item => {
|
|
||||||
if (!isRecord(item) || typeof item.name !== 'string' || !item.name.trim() || item.name.length > 80) throw new Error('Invalid contact name.');
|
|
||||||
unhex(item.key, 65);
|
|
||||||
const key = item.key as string;
|
|
||||||
if (keys.has(key)) throw new Error('Duplicate contact identity.');
|
|
||||||
keys.add(key); return { key, name: item.name.trim() };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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, contacts: [] };
|
|
||||||
validateContacts(state.contacts);
|
|
||||||
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. Reset it or restore a backup.');
|
|
||||||
}
|
|
||||||
return state;
|
|
||||||
} finally { db.close(); }
|
|
||||||
}
|
|
||||||
export async function saveIdentityState(state: IdentityState, expectedRevision = state.revision): Promise<IdentityState> {
|
|
||||||
validateContacts(state.contacts);
|
|
||||||
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(); }
|
|
||||||
}
|
|
||||||
const iterations = 600000;
|
|
||||||
async function backupKey(password: string, salt: Uint8Array<ArrayBuffer>) {
|
|
||||||
if (password.length < 12 || password.length > 1024) throw new Error('Use a backup password between 12 and 1024 characters.');
|
|
||||||
const material = await crypto.subtle.importKey('raw', bytes(password), 'PBKDF2', false, ['deriveKey']);
|
|
||||||
return crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
||||||
}
|
|
||||||
export async function exportBackup(state: IdentityState, password: string) {
|
|
||||||
if (!state.identity) throw new Error('Create a device identity first.');
|
|
||||||
const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));
|
|
||||||
const data = bytes(JSON.stringify({ key: await crypto.subtle.exportKey('jwk', state.identity.privateKey), publicKey: state.identity.publicKey, contacts: validateContacts(state.contacts) }));
|
|
||||||
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: bytes('HellCon backup v1') }, await backupKey(password, salt), data);
|
|
||||||
return JSON.stringify({ format: 'hellcon-identity', version: 1, iterations, salt: hex(salt), iv: hex(iv), data: hex(encrypted) });
|
|
||||||
}
|
|
||||||
export async function importBackup(text: string, password: string): Promise<IdentityState> {
|
|
||||||
if (text.length > 100000) throw new Error('Backup is too large.');
|
|
||||||
try {
|
|
||||||
const value: unknown = JSON.parse(text);
|
|
||||||
if (!isRecord(value) || value.format !== 'hellcon-identity' || value.version !== 1 || value.iterations !== iterations || typeof value.data !== 'string' || value.data.length < 32) throw new Error();
|
|
||||||
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unhex(value.iv, 12), additionalData: bytes('HellCon backup v1') }, await backupKey(password, unhex(value.salt, 16)), unhex(value.data, value.data.length / 2));
|
|
||||||
const payload: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decrypted));
|
|
||||||
if (!isRecord(payload) || !isRecord(payload.key)) throw new Error();
|
|
||||||
const publicKey = payload.publicKey as string;
|
|
||||||
const pub = await crypto.subtle.importKey('raw', unhex(publicKey, 65), curve, false, ['verify']);
|
|
||||||
const privateKey = await crypto.subtle.importKey('jwk', payload.key, curve, true, ['sign']);
|
|
||||||
const challenge = crypto.getRandomValues(new Uint8Array(32));
|
|
||||||
if (!await crypto.subtle.verify(signing, pub, await crypto.subtle.sign(signing, privateKey, challenge), challenge)) throw new Error();
|
|
||||||
return { identity: { publicKey, privateKey }, contacts: validateContacts(payload.contacts) };
|
|
||||||
} catch { throw new Error('Could not restore backup. Check the password and backup file.'); }
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
+636
-237
@@ -1,299 +1,698 @@
|
|||||||
:root {
|
*,
|
||||||
color-scheme: dark;
|
*::before,
|
||||||
--bg: #0f1117;
|
*::after {
|
||||||
--panel: #181b24;
|
|
||||||
--border: #2a2f3d;
|
|
||||||
--accent: #ff9b3d;
|
|
||||||
--accent-soft: rgba(255, 155, 61, 0.15);
|
|
||||||
--text: #e8eaf0;
|
|
||||||
--muted: #8b91a3;
|
|
||||||
}
|
|
||||||
|
|
||||||
* {
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
*:not(dialog) {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
background: var(--bg);
|
}
|
||||||
color: var(--text);
|
|
||||||
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
html {
|
||||||
|
interpolate-size: allow-keywords;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
line-height: 1.5;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
img,
|
||||||
|
picture,
|
||||||
|
video,
|
||||||
|
canvas,
|
||||||
|
svg {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
button,
|
||||||
|
textarea,
|
||||||
|
select {
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
p,
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
text-wrap: pretty;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
text-wrap: balance;
|
||||||
}
|
}
|
||||||
|
|
||||||
#app {
|
#app {
|
||||||
|
isolation: isolate;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
font-family: system-ui, sans-serif;
|
||||||
|
|
||||||
|
--color-primary: #5865f2;
|
||||||
|
--color-primary-hover: #4752c4;
|
||||||
|
--color-on-primary: #fff;
|
||||||
|
--color-secondary: #eb459e;
|
||||||
|
/* The secondary is too dark for text on the surfaces, this one keeps 4.5:1 */
|
||||||
|
--color-secondary-text: #f278b7;
|
||||||
|
--color-success: #23a559;
|
||||||
|
|
||||||
|
--color-bg: #313338;
|
||||||
|
--color-surface: #2b2d31;
|
||||||
|
--color-input: #1e1f22;
|
||||||
|
--color-border: #3f4147;
|
||||||
|
--color-text: #dbdee1;
|
||||||
|
--color-text-muted: #949ba4;
|
||||||
|
|
||||||
|
--space-1: 0.25rem;
|
||||||
|
--space-2: 0.5rem;
|
||||||
|
--space-3: 0.75rem;
|
||||||
|
--space-4: 1rem;
|
||||||
|
--space-6: 1.5rem;
|
||||||
|
--space-8: 2rem;
|
||||||
|
|
||||||
|
--text-sm: 0.875rem;
|
||||||
|
--text-lg: 1.125rem;
|
||||||
|
--text-xl: 1.25rem;
|
||||||
|
|
||||||
|
--radius: 0.5rem;
|
||||||
|
--shadow: 0 1px 3px rgb(0 0 0 / 0.4), 0 1px 2px rgb(0 0 0 / 0.3);
|
||||||
|
--transition: 150ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
|
background: var(--color-bg);
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Layout */
|
||||||
|
|
||||||
|
header,
|
||||||
|
main,
|
||||||
|
footer {
|
||||||
|
max-width: 64rem;
|
||||||
|
margin-inline: auto;
|
||||||
|
padding-inline: var(--space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The columns of main, so the options line up with the Receive card, below the title on a phone */
|
||||||
|
header {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding-block: var(--space-6) var(--space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
header > div:first-child {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
header h1 {
|
||||||
|
font-size: var(--text-xl);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The switches at the end, the own salt below while it's on */
|
||||||
|
#options {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#options > div:first-child {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: end;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding-inline: 0.9rem;
|
gap: var(--space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
main {
|
main {
|
||||||
width: 100%;
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||||
|
align-items: start;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding-bottom: var(--space-8);
|
||||||
|
}
|
||||||
|
|
||||||
|
main > p,
|
||||||
|
main > aside,
|
||||||
|
main > details {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Note while no STUN server would be used, quiet above the cards */
|
||||||
|
#no-stun {
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cards */
|
||||||
|
|
||||||
|
article,
|
||||||
|
details {
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
article {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: center;
|
gap: var(--space-4);
|
||||||
|
padding: var(--space-6);
|
||||||
}
|
}
|
||||||
|
|
||||||
.skip-link {
|
article h2 {
|
||||||
position: absolute;
|
font-size: var(--text-lg);
|
||||||
left: 0.9rem;
|
|
||||||
top: 0.5rem;
|
|
||||||
transform: translateY(-200%);
|
|
||||||
z-index: 1;
|
|
||||||
padding: 0.55rem 0.8rem;
|
|
||||||
border-radius: 8px;
|
|
||||||
background: var(--accent);
|
|
||||||
color: var(--bg);
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.skip-link:focus {
|
section {
|
||||||
transform: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.panel {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 680px;
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 1.5rem;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0.9rem;
|
align-items: start;
|
||||||
|
gap: var(--space-2);
|
||||||
|
padding-top: var(--space-4);
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
h3,
|
||||||
margin: 2rem 0 0.25rem;
|
article summary {
|
||||||
font-family: ui-monospace, 'Cascadia Code', monospace;
|
font-size: var(--text-sm);
|
||||||
}
|
|
||||||
|
|
||||||
.subtitle {
|
|
||||||
color: var(--muted);
|
|
||||||
margin: 0 0 1.5rem;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.app-download {
|
|
||||||
color: var(--accent);
|
|
||||||
margin: -0.5rem 0 1.5rem;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs {
|
|
||||||
display: flex;
|
|
||||||
gap: 0.5rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 680px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs button {
|
|
||||||
flex: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
background: var(--panel);
|
|
||||||
color: var(--text);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 0.55rem 1rem;
|
|
||||||
font-size: 1rem;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:hover:not(:disabled) {
|
|
||||||
border-color: var(--accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
:where(a, button, input, select, textarea):focus-visible {
|
|
||||||
outline: 2px solid var(--accent);
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button.primary {
|
|
||||||
background: var(--accent);
|
|
||||||
border-color: var(--accent);
|
|
||||||
color: var(--bg);
|
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
|
||||||
|
|
||||||
button:disabled {
|
|
||||||
opacity: 0.45;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs button.active {
|
|
||||||
background: var(--accent);
|
|
||||||
border-color: var(--accent);
|
|
||||||
color: var(--bg);
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.step {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
font-weight: 700;
|
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.06em;
|
letter-spacing: 0.05em;
|
||||||
color: var(--muted);
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
label,
|
||||||
|
section p {
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
section p[role='alert'] {
|
||||||
|
color: var(--color-secondary-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
header label {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Forms */
|
||||||
|
|
||||||
|
input,
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
background: var(--color-input);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: inherit;
|
||||||
|
transition: border-color var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus,
|
||||||
|
textarea:focus {
|
||||||
|
border-color: var(--color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Like a disabled button, the switch with its label */
|
||||||
|
input:not([role='switch']):disabled,
|
||||||
|
label:has([role='switch']:disabled) {
|
||||||
|
opacity: 0.4;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
label:has([role='switch']:disabled) [role='switch'] {
|
||||||
|
cursor: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
|
||||||
|
input:not([type='checkbox'], [type='file']):focus-visible,
|
||||||
|
textarea:focus-visible {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::placeholder {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
opacity: 0.7;
|
||||||
}
|
}
|
||||||
|
|
||||||
textarea {
|
textarea {
|
||||||
width: 100%;
|
min-height: 5rem;
|
||||||
min-height: 90px;
|
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
background: var(--bg);
|
|
||||||
color: var(--text);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 0.6rem;
|
|
||||||
font-family: ui-monospace, monospace;
|
font-family: ui-monospace, monospace;
|
||||||
font-size: 0.75rem;
|
font-size: var(--text-sm);
|
||||||
word-break: break-all;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.dropzone {
|
button {
|
||||||
border: 2px dashed var(--border);
|
padding: var(--space-2) var(--space-4);
|
||||||
border-radius: 10px;
|
border: 1px solid transparent;
|
||||||
padding: 2rem;
|
border-radius: var(--radius);
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: var(--color-on-primary);
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover:not(:disabled) {
|
||||||
|
background: var(--color-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.4;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
:focus-visible {
|
||||||
|
outline: 2px solid var(--color-secondary);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
[role='group'] {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--space-2);
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The tracker code on both sides. The sender's is read only like an input, one click selects it. */
|
||||||
|
#send-code,
|
||||||
|
#receive-code {
|
||||||
|
color: var(--color-secondary-text);
|
||||||
|
font-family: ui-monospace, monospace;
|
||||||
|
font-size: var(--text-lg);
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.15em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#send-code {
|
||||||
|
flex: 1;
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
background: var(--color-input);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
user-select: all;
|
||||||
|
}
|
||||||
|
|
||||||
|
#send-code[data-expired] {
|
||||||
|
text-decoration: line-through;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Copy and Generate, secondary next to the value they are for */
|
||||||
|
|
||||||
|
[data-copy] {
|
||||||
|
padding: var(--space-1) var(--space-3);
|
||||||
|
background: transparent;
|
||||||
|
border-color: var(--color-border);
|
||||||
|
color: var(--color-text);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-copy]:hover:not(:disabled) {
|
||||||
|
background: var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Manual signaling, folded away below the tracker in each card */
|
||||||
|
|
||||||
|
article details {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
border-radius: 0;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
article summary {
|
||||||
|
padding: var(--space-4) 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
article details section {
|
||||||
|
padding-top: var(--space-2);
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Drop zone, the invisible file input covers the whole label. The incoming file looks alike. */
|
||||||
|
|
||||||
|
label:has(> [type='file']),
|
||||||
|
#incoming {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-1);
|
||||||
|
padding: var(--space-8) var(--space-4);
|
||||||
|
background: var(--color-input);
|
||||||
|
border: 2px dashed var(--color-border);
|
||||||
|
border-radius: var(--radius);
|
||||||
text-align: center;
|
text-align: center;
|
||||||
color: var(--muted);
|
transition:
|
||||||
|
border-color var(--transition),
|
||||||
|
background-color var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
label:has(> [type='file']):hover,
|
||||||
|
label[data-dragging] {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
label[data-dragging] {
|
||||||
|
background: color-mix(in srgb, var(--color-primary) 10%, var(--color-input));
|
||||||
|
}
|
||||||
|
|
||||||
|
label:has(> [type='file']:focus-visible) {
|
||||||
|
outline: 2px solid var(--color-secondary);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#incoming {
|
||||||
|
border-style: solid;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#incoming button {
|
||||||
|
margin-top: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[type='file'] {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
opacity: 0;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dropzone.dragover {
|
label strong,
|
||||||
border-color: var(--accent);
|
#incoming strong {
|
||||||
background: var(--accent-soft);
|
color: var(--color-text);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
|
|
||||||
.progress {
|
/* A dropped folder, refused */
|
||||||
height: 10px;
|
#not-a-file {
|
||||||
background: var(--bg);
|
color: var(--color-secondary-text);
|
||||||
border-radius: 6px;
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* How the session is doing, below the file on its side. Until the transfer starts a pill passes
|
||||||
|
through the bar, blue, or pink while it tries again after a failure. Then the transfer's progress,
|
||||||
|
green once done, muted once stopped, pink for an error. The line below says what. */
|
||||||
|
|
||||||
|
[data-phase] {
|
||||||
|
--bar: var(--color-primary);
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-phase='retry'],
|
||||||
|
[data-phase='error'] {
|
||||||
|
--bar: var(--color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-phase='done'] {
|
||||||
|
--bar: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-phase='stopped'] {
|
||||||
|
--bar: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-phase] p {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-3);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The send session's file, above its bar once the user picked another one */
|
||||||
|
#send-file {
|
||||||
|
color: var(--color-text);
|
||||||
|
font-weight: 600;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A block, a flex container has no first letter. Flex items do, they are blocks. */
|
||||||
|
[data-phase] p[role='alert'] {
|
||||||
|
display: block;
|
||||||
|
color: var(--color-secondary-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-phase] p[role='alert']::first-letter,
|
||||||
|
[data-phase] [role='status'] > :first-child::first-letter {
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The track, the progress inside it fills it or, without a value, is the pill */
|
||||||
|
[data-phase] > div {
|
||||||
|
height: 0.5rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--color-input);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.progress > div {
|
progress {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: var(--accent);
|
appearance: none;
|
||||||
transition: width 0.15s linear;
|
border: none;
|
||||||
|
background: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.status {
|
progress::-webkit-progress-bar {
|
||||||
color: var(--muted);
|
background: none;
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.error {
|
progress::-webkit-progress-value {
|
||||||
color: #ff6b5e;
|
background: var(--bar);
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.file-chip {
|
progress::-moz-progress-bar {
|
||||||
|
background: var(--bar);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress:indeterminate {
|
||||||
|
width: 25%;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--bar);
|
||||||
|
animation: pass 2584ms linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
progress:indeterminate::-moz-progress-bar {
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Its own width is a quarter of the track's: from just before it to just past it */
|
||||||
|
@keyframes pass {
|
||||||
|
from {
|
||||||
|
translate: -100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
translate: 400%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
progress:indeterminate {
|
||||||
|
translate: 150%;
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Switch, like Pico's role="switch" */
|
||||||
|
|
||||||
|
label:has([role='switch']) {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 1rem;
|
gap: var(--space-2);
|
||||||
background: var(--bg);
|
cursor: pointer;
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 0.6rem 0.9rem;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
a.download {
|
[role='switch'] {
|
||||||
color: var(--accent);
|
appearance: none;
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 1.25rem;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--color-border);
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
position: relative;
|
||||||
|
transition: background-color var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
[role='switch']::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
inset: 0.125rem auto 0.125rem 0.125rem;
|
||||||
|
aspect-ratio: 1;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--color-text);
|
||||||
|
transition: translate var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
[role='switch']:checked {
|
||||||
|
background: var(--color-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
[role='switch']:checked::before {
|
||||||
|
translate: 1rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Security check callout */
|
||||||
|
|
||||||
|
aside {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding: var(--space-4) var(--space-6);
|
||||||
|
background: color-mix(in srgb, var(--color-secondary) 8%, var(--color-surface));
|
||||||
|
border: 1px solid var(--color-secondary);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
aside p {
|
||||||
|
flex: 1 1 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Monospaced in a grid, so both codes line up byte by byte */
|
||||||
|
aside dl {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto auto;
|
||||||
|
justify-content: start;
|
||||||
|
column-gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
aside dt {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
aside div {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
aside button + button {
|
||||||
|
background: transparent;
|
||||||
|
border-color: var(--color-border);
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
aside button + button:hover {
|
||||||
|
background: var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
output {
|
||||||
|
color: var(--color-secondary-text);
|
||||||
|
font-family: ui-monospace, monospace;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
.fingerprint {
|
/* Source link, quiet below everything */
|
||||||
background: var(--bg);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 0.75rem 0.9rem;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.4rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.fp-row {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
gap: 1rem;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.fp-row code {
|
|
||||||
font-family: ui-monospace, monospace;
|
|
||||||
color: var(--accent);
|
|
||||||
letter-spacing: 0.12em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.fingerprint .status {
|
|
||||||
margin: 0.2rem 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
footer {
|
footer {
|
||||||
max-width: 680px;
|
|
||||||
width: 100%;
|
|
||||||
margin: 1.5rem 0 2.5rem;
|
|
||||||
padding: 0 0.25rem;
|
|
||||||
color: var(--muted);
|
|
||||||
font-size: 0.78rem;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
|
|
||||||
footer p {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stun-select,
|
|
||||||
.stun-input {
|
|
||||||
width: 100%;
|
|
||||||
background: var(--bg);
|
|
||||||
color: var(--text);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 0.55rem 0.75rem;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-family: inherit;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stun-input {
|
|
||||||
font-family: ui-monospace, monospace;
|
|
||||||
font-size: 0.85rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stun-select:focus,
|
|
||||||
.stun-input:focus {
|
|
||||||
border-color: var(--accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
p.stun-hint {
|
|
||||||
margin: -0.35rem 0 0;
|
|
||||||
font-size: 0.78rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.network-settings {
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-wrap: wrap;
|
||||||
gap: 0.7rem;
|
justify-content: space-between;
|
||||||
border: 1px solid var(--border);
|
align-items: center;
|
||||||
border-radius: 8px;
|
gap: var(--space-2) var(--space-4);
|
||||||
min-width: 0;
|
padding-bottom: var(--space-6);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
.network-settings legend { color: var(--muted); }
|
|
||||||
.checkbox { display: flex; align-items: start; gap: 0.6rem; }
|
|
||||||
.fp-row { flex-direction: column; align-items: start; }
|
|
||||||
.fp-row code { overflow-wrap: anywhere; line-height: 1.7; font-size: 0.8rem; }
|
|
||||||
.file-chip span { overflow-wrap: anywhere; min-width: 0; }
|
|
||||||
.incoming { display: flex; flex-direction: column; gap: 0.7rem; overflow-wrap: anywhere; }
|
|
||||||
|
|
||||||
.transfer-section { display: flex; flex-direction: column; gap: 0.9rem; scroll-margin-top: 1rem; min-width: 0; }
|
footer a {
|
||||||
.transfer-section:focus-visible { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 4px; }
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-decoration: none;
|
||||||
|
transition: color var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
.device-settings { display: flex; flex-direction: column; gap: 0.75rem; min-width: 0; border: 1px solid var(--border); border-radius: 8px; }
|
footer a:hover {
|
||||||
.device-settings input:not([type=checkbox]), .device-settings select, #contact-name { box-sizing: border-box; max-width: 100%; padding: 0.6rem; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; }
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
footer img {
|
||||||
|
filter: grayscale(1);
|
||||||
|
opacity: 0.6;
|
||||||
|
transition: opacity var(--transition);
|
||||||
|
}
|
||||||
|
|
||||||
|
footer a:hover img {
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Servers */
|
||||||
|
|
||||||
|
#servers > div {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||||
|
justify-items: start;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding: var(--space-4) var(--space-6) var(--space-6);
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
#servers section {
|
||||||
|
justify-self: stretch;
|
||||||
|
padding-top: 0;
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#servers p {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
[aria-invalid='true'] {
|
||||||
|
border-color: var(--color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Log */
|
||||||
|
|
||||||
|
summary {
|
||||||
|
padding: var(--space-3) var(--space-6);
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre {
|
||||||
|
max-height: 20rem;
|
||||||
|
overflow: auto;
|
||||||
|
padding: var(--space-4) var(--space-6);
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -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,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,49 +0,0 @@
|
|||||||
import test from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { createIdentity, hello, signIdentity, verifyIdentity, exportBackup, importBackup, parseHello, validateContacts, 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 and contacts cannot supply duplicate identities', async () => {
|
|
||||||
const identity = await createIdentity();
|
|
||||||
assert.throws(() => parseHello({ key: identity.publicKey, nonce: 'bad' }));
|
|
||||||
assert.throws(() => parseHello({ key: 'ff'.repeat(65), nonce: '00'.repeat(32) }));
|
|
||||||
assert.throws(() => validateContacts([{ key: identity.publicKey, name: ' ' }]));
|
|
||||||
assert.throws(() => validateContacts(Array(101).fill({ key: identity.publicKey, name: 'friend' })));
|
|
||||||
assert.throws(() => validateContacts(Array(2).fill({ key: identity.publicKey, name: 'friend' })));
|
|
||||||
});
|
|
||||||
test('encrypted backup restores signing identity and contacts; wrong password and tampering fail', async () => {
|
|
||||||
const { first, second, context } = await setup();
|
|
||||||
const state = { identity: first, contacts: [{ key: second.publicKey, name: 'Other device' }] };
|
|
||||||
const password = 'a long private backup passphrase';
|
|
||||||
const backup = await exportBackup(state, password);
|
|
||||||
assert.doesNotMatch(backup, /Other device|privateKey/);
|
|
||||||
const restored = await importBackup(backup, password);
|
|
||||||
assert.deepEqual(restored.contacts, state.contacts);
|
|
||||||
assert.equal(restored.identity!.publicKey, first.publicKey);
|
|
||||||
await verifyIdentity(await signIdentity(restored.identity!, context, true), context, true);
|
|
||||||
await assert.rejects(importBackup(backup, 'the incorrect password'));
|
|
||||||
const damaged = JSON.parse(backup); damaged.data = (damaged.data.startsWith('00') ? 'ff' : '00') + damaged.data.slice(2);
|
|
||||||
await assert.rejects(importBackup(JSON.stringify(damaged), password));
|
|
||||||
damaged.iterations = 1; await assert.rejects(importBackup(JSON.stringify(damaged), password));
|
|
||||||
await assert.rejects(importBackup('x'.repeat(100001), password));
|
|
||||||
await assert.rejects(exportBackup(state, 'short'));
|
|
||||||
});
|
|
||||||
@@ -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 }))));
|
|
||||||
});
|
|
||||||
+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
-15
@@ -1,19 +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(),
|
||||||
build: { rollupOptions: { output: { format: 'iife' } } },
|
// index.html's Content-Security-Policy allows no inline styles, the dev server injects the CSS
|
||||||
server: { host: '127.0.0.1' },
|
// through JavaScript. A nonce lets only those style elements through, so the dev server enforces
|
||||||
plugins: [vue(), {
|
// the same policy as the production build, which links the CSS as files.
|
||||||
name: 'local-turn-credentials',
|
{
|
||||||
configureServer(server) {
|
name: 'dev-csp',
|
||||||
if (env.VITE_ICE_ENDPOINT === '/api/ice-servers') server.middlewares.use(iceMiddleware(env));
|
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