Compare commits

..
26 Commits
Author SHA1 Message Date
SchluffeandClaude Fable 5.2 3c47047ddd Release 1.0.2: take a file picked again, refuse a dropped folder
Chromium fires no change event when the picker returns the file its input
already holds. The page kept the old one then, though the file may have
changed on disk, which makes the old one unreadable, or another file was
dropped in between, which the input never saw. The input is now emptied as
soon as its file is taken, so every pick fires. Its title names the file
taken, the browser's own tooltip would say no file is chosen.

A dropped folder came as a file of 0 B that can't be read and failed only
once the receiver downloaded it. It is refused with a note now, the file
picked before stays.

Both are covered for Chromium, whose protocol is the only one that reaches
the real picker and a drag from the file manager.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 13:00:35 +01:00
SchluffeandClaude Opus 5.5 1b2696b6b4 Release 1.0.1: update dependencies, count only the lost tracker's offers
Node 26.13.1, Vue 3.5.45, Playwright 1.65.0, Vite 8.3.8, Vitest 5.1.0,
vue-tsc 3.3.14, @vitejs/plugin-vue 6.0.11 and ws 8.23.0 for its bugfix.
ws 8.23.0 is younger than pnpm's minimum release age, pnpm-workspace.yaml
excludes it until then.

The test of an offer waiting on a lost tracker counted every offer the
sender answered. The silent receiver proves the code on its next channel and
may come back by the second tracker before the test ends, so it failed most
runs. It now counts the offers via the lost tracker only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:59:58 +01:00
SchluffeandClaude Opus 5.5 ac4d496a48 Version the protocol for 1.0, fail downloads the page abandoned
PROTOCOL (hellcon/1) goes in front of the PBKDF2 salt and names the data
channel, so different versions never meet via a tracker and the manual
receiver tells a sender on another protocol apart. The footer shows it, the
receiver's hints ask to compare it. Forks are asked to name their own.

public/sw.js and the page exchange a VERSION, a mismatch fails the download
with outdated. The worker fails a download after 20 s without a chunk or
ping from its page, else Firefox saves the truncated file of a closed tab as
complete.

The build uses relative links and works under any path. On https only wss:
trackers and ws: to this device are accepted, one the browser refuses to
open counts as lost. Also: a file read short stops the transfer, an offer
waiting on a lost tracker isn't answered, a share ended while its key was
derived opens no tracker, and tracker and receiver errors lose hidden
characters. The README lists what isn't planned and the phone limitation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:10:09 +01:00
SchluffeandClaude Opus 5.5 44a8a72261 Keep the screen on and ask before leaving while a session is busy
While a share waits or a transfer runs, the page holds a Screen Wake Lock,
requested again once the page is visible, since the browser releases it
whenever it's hidden. A beforeunload handler makes the browser ask before a
reload or a closed tab ends the session, only while busy so the page stays
eligible for the back/forward cache otherwise. Covered by awake: with a fake
wake lock, a headless browser may not grant a real one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:51:51 +01:00
Schluffe 870d55b44f Set Content-Security-Policy 2026-10-30 13:39:16 +01:00
SchluffeandClaude Opus 5.5 af0a8c9fee Strip controls, line separators and bidi controls from offered file names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 00:38:10 +01:00
SchluffeandClaude Opus 5.5 7f4811485a Limit what a tracker can make the page do, recommend anti-framing headers
A tracker message over 64 KiB isn't parsed, before acceptance it rejects
the tracker like a failure reason. Beyond 20 messages per 10 s the rest is
dropped, so a tracker can't keep the page parsing and decrypting. What a
tracker makes a socket log goes through one note: each line once, at most
10 per socket. The log keeps the last 1000 lines in a shallow ref and says
how many went.

index.html sets Referrer-Policy itself, the README recommends the headers a
<meta> can't set: frame-ancestors, X-Frame-Options and nosniff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 00:29:23 +01:00
SchluffeandClaude Opus 5.5 b102e55495 Limit the tracker per address and harden its plain HTTP path
Per address and minute: connects and forwarded signaling, so reconnecting
doesn't reset a client's allowance. X-Forwarded-For only counts from PROXIES,
checked with net.BlockList, with one warning when an uncovered peer sends it.
Plain requests get timeouts and a closing 404, silent connections go after
30 s and all queues together share a budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 20:27:50 +01:00
SchluffeandClaude Opus 5.5 ae1e3bef9b Hash all fingerprints into the manual security check
The manual check used to show the first 8 bytes of the first fingerprint
each SDP named, so an interposer could add its own certificate beside the
claimed one and the codes still matched. Now each code is the first 16
bytes of a SHA-256 over every fingerprint the SDP names, also ones hidden
in other lines, so whatever the browser uses changes the code. Without a
fingerprint on either side the connection ends. End-to-end tests try a
claimed certificate in several hiding places.

The README says that a working connection isn't necessarily direct and what
the meeting tracker sees, TODO.md lists hardening from a security review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:23:04 +01:00
Schluffe ae871a2647 Improve tests 2026-10-28 22:24:24 +01:00
Schluffe 8f82700736 Refactor the app 2026-10-28 21:05:47 +01:00
SchluffeandClaude Opus 5.5 f53d39ae69 Update Biome to 2.6.3 and pnpm to 12.16.1
TypeScript stays on 6, vue-tsc can't load TypeScript 7 yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:01:49 +01:00
SchluffeandClaude Opus 5.5 aa61efcc10 Let the receiver fix a wrong salt during a search
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:51:20 +01:00
SchluffeandClaude Opus 5.5 2e47b55901 Salt the tracker swarm with the clock or an own salt
The code used to be derived with a fixed salt, so a tracker could compute a
table from swarm to code ahead of time, once for every share. Now the salt
is the UTC 6 minute window the share was made in, and the code's new 11th
character names that window, so the receiver finds it even with a clock
hours off. Use own salt adds a salt both sides agree on, which nobody can
guess ahead for; Generate makes a random one. The salt is locked while a
tracker share or search runs, and a receiver that finds no sender is told
to check the salt too.

Settings are no longer kept in localStorage: a remembered list or salt that
differs from the other side's would silently break shares. The core now
reports when a share expires and until when it lasts, and the session owns
a tracker's timers, so a socket still closing after an abort announces
nothing more. Header options line up with the cards, disabled switches look
disabled, and sizes, percents and times don't wrap. postcss 8.5.32.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 01:14:27 +01:00
Schluffe e3a2b348d6 Harden the app 2026-10-26 20:48:24 +01:00
SchluffeandClaude Opus 5.5 d92c4b50cf Let one pill pass through the bar until the transfer starts
Start, wait and retry used a gradient sweep and a pulse, which felt restless.
Now a solid pill passes through the bar at an even speed for all three, pink
while retrying, and the line below says the rest. The sender's waiting line
is shorter, the code's label already says to give it to the receiver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 19:28:45 +01:00
SchluffeandClaude Opus 5.5 f7e8999439 Show how a session is doing on the progress bar
Each side's bar now shows the session's phase by color and movement, with a
short line below saying what is going on: a sweep while connecting, a pulse
while someone has to act, a slow pink sweep while retrying after a failure
(with the reason and the attempt), then the transfer, done, stopped or error.
A receiver whose code no tracker knows says so right away instead of after
6 minutes, and a connection that fails though both sides have a public
address names a blocking network as the likely reason.

The log marks where each session starts. The send card names the session's
file once another one is picked, and a blocked clipboard is shown inline with
the text selected for copying by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:26:53 +01:00
Schluffe 02668de602 Add IPv6 to the coturn config 2026-10-25 20:46:19 +01:00
SchluffeandClaude Opus 5.5 3c4e706e1f Keep a finished download's frame for a moment
Small downloads, empty or 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 the frame was removed right then, which cancels it.
Without a delay an empty file failed 8 of 10 runs, a one byte file 4 of 10.

The download's frame now stays for DOWNLOAD_GRACE (1 s) after finished, the frame that holds the
worker still goes right away. No event tells when the browser took the download, so the 1 s is
empirical. A new test checks the retention on a paused clock, it fails without the delay and with
the worker's frame held too. The browser's timing it can't cover, TODO.md keeps a record of that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:55:45 +01:00
SchluffeandClaude Opus 5.5 bd0154db68 Tell the user when a missing public address explains a failed connection
Without STUN a side offers only local addresses, enough on the same network or VPN. Between
networks the connection never came up, and nothing said why: tracker signaling only logged "did
not connect" and ended after 6 minutes with the generic message, the manual exchange in Chromium
never ended at all, since Chromium doesn't fail a connection without usable addresses.

A connection that doesn't come up now checks both SDPs for a public address (typ srflx) and names
the side without one, in the log and in the error at the end of the session. That covers STUN
turned off, an empty list and servers that don't answer, on either side. A device with a public
address of its own offers none either, so it's a hint. The manual sender gives up 30 s after the
answer, the receiver after 6 minutes, it has to hand the answer over first.

A note above the cards says when STUN is off or no server is listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:55:45 +01:00
Schluffe 21ea9a7e02 Update node packages 2026-10-25 19:04:06 +01:00
SchluffeandClaude Opus 5.5 840bc3572b Contact one STUN server and one tracker at a time
Both sides used to contact every STUN server and tracker at once, so each of them learned the IP
address and each tracker that A sent to B.

Connections now use one STUN server: the first in the list that reports a public address to a
throwaway probe connection within 2 s. It stays for the page's lifetime. If a connection gets no
address from it, the next connection probes on from the server after it. A probe runs only while a
session waits for it and stops once none does, STUN is turned off or the list changes.

The sender joins the first tracker that accepts it and moves to the next only once that one rejects
it, can't be reached within 10 s or is lost. The receiver walks the list with one offer each and
stays where a tracker reports a seeder (complete), which is the sender: it always announces before
anyone has the code. Trackers it passed keep its offer. backend/tracker.mjs now sends complete.

wss://tracker.pagequit.net comes first in the default trackers, the public ones are fallbacks.
TODO.md drops the server tasks, they aren't work on this codebase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:51:42 +01:00
SchluffeandClaude Opus 5.5 5729ed62f7 Add backend/.env.example
It shows what ORIGINS has to look like: exactly what browsers send as Origin, so scheme, host and a
non-default port, without path or trailing slash. Anything else locks out every client. CADDY_NETWORK
is there too, commented out with its default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:51:42 +01:00
SchluffeandClaude Opus 5.5 8b36e51b56 Require Node.js 26.12.1, it fixes CVE-2026-111497
26.11.1 has the out-of-bounds write in its Brotli decoder. The tracker decompresses nothing, but
the image and development machines should still not run an affected version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:09:49 +01:00
SchluffeandClaude Opus 5.5 4725b14a40 Limit pings like messages in the tracker
ws answered every ping on its own, past the message rate limit and past the bound on bytes queued
for a peer: a client pinging without reading made the tracker buffer pongs until it ran out of
memory. Pongs are now sent by the tracker, pings and pongs count as messages, and a pong is queued
only within the same bound as any message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:54:03 +01:00
SchluffeandClaude Opus 5.5 22d794965e Add an own tracker and STUN server in backend/
backend/ runs both as Docker Compose services, neither is needed: the client works with any
WebTorrent tracker and STUN server. The tracker is one file on Node and ws that does only the part
of the protocol HellCon uses. It accepts allowed origins only and messages of at most 16 KiB, only
announce, one offer per announce and answers only to offers it delivered, once. Forwarded messages
are rebuilt from the checked fields. It limits the message rate, the signaling each connection
sends, the bytes queued for a peer that stops reading, connection age, connections per IP and in
total, and peers per swarm. It logs nothing. coturn runs STUN only on the host network, pinned,
read-only and without capabilities beyond the one its binary needs.

backend/tracker.spec.mjs tests its rules one by one, e2e.spec.ts sends a real file through it alone
in both directions between Chromium and Firefox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:26:42 +01:00
22 changed files with 5623 additions and 1382 deletions

No files matched your search

+77 -14
View File
@@ -6,14 +6,18 @@ size limit: the file goes directly to the other person and is never stored on a
## How to send a file ## How to send a file
1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get 1. **Sender:** open HellCon, drop a file onto the Send card and click **Share via tracker**. You get
an 8 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can an 11 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
get the file, so give it to nobody else. 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**. 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. 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 Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
tab was doing. 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 ### Without a tracker
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
@@ -32,15 +36,15 @@ to the encryption keys of this very connection. Someone in between, or anyone el
know the code, can't do that, and HellCon drops the connection and waits for the right one. 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 The manual exchange has no code, so there you compare yourselves. Once connected, both sides see two
short codes: **You** and **Peer**. Compare them with the other person over a channel you already codes: **You** and **Peer**. Compare them with the other person over a channel you already trust,
trust, ideally a call or in person: ideally a call or in person:
- your **You** must be their **Peer**, and - your **You** must be their **Peer**, and
- your **Peer** must be their **You**. - your **Peer** must be their **You**.
If both match, you are connected directly to each other. If they don't, someone has placed 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 themselves in between: click **Codes don't match** and nothing is sent. Nothing is transferred before
both sides confirmed, so take the few seconds to really compare them. 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 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. own keys, which show up as different codes.
@@ -63,16 +67,23 @@ On the receiving side, HellCon hands the incoming data to the browser's own down
it arrives. That's why files larger than your memory work too, and why the download shows up in it arrives. That's why files larger than your memory work too, and why the download shows up in
your browser's download list. your browser's download list.
There is no relay server. If both sides are behind very strict networks, e.g. some company or mobile HellCon uses no relay server. If both sides are behind very strict networks, e.g. some company or
networks, a direct connection may not be possible. mobile networks, a direct connection may not be possible. And a connection that works isn't
necessarily direct: the other side may name a relay of its own, and a STUN server that reports a
wrong address can put itself in between. Either only passes on encrypted data. The security check
makes sure the connection ends at the two of you.
## Privacy ## Privacy
- The file only goes to the person you connected with. - The file only goes to the person you connected with.
- That person learns your IP address, as with any direct connection. The tracker and the STUN - That person learns your IP address, as with any direct connection. One STUN server and one or a
servers see it too, from the request itself. Nobody without the code learns it through the few trackers see it too, from the request itself. HellCon tries the STUN servers in order and
tracker. sticks with the first that answers. The sender stays on the first tracker that accepts it. The
- Settings (STUN on or off, your server lists) are kept in your browser only. 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, - Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
host your own (below). host your own (below).
@@ -80,8 +91,18 @@ networks, a direct connection may not be possible.
Under **Servers** you can change which STUN servers and trackers your browser uses, one address per Under **Servers** you can change which STUN servers and trackers your browser uses, one address per
line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults** line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults**
brings back the original lists. Both sides must use at least one tracker in common to find each brings back the original lists. The order matters: the sender stays on the first tracker that
other. works, the receiver tries them in order until it finds the sender. Both lists must contain that
tracker.
The code goes to the tracker mixed with a salt, which changes with the clock every 6 minutes (by UTC):
guessing codes ahead of time pays off for 6 minutes at most. The code's last character tells the
receiver which 6 minutes it was made in, so the two clocks may be up to 3 hours apart. Someone could
still guess ahead for a particular 6 minutes. If that worries you, turn on **Use own salt** on both
sides and enter the same salt, agreed on any way you like. **Generate** makes a random one. Nobody
can guess ahead for a salt they don't know.
Nothing of this is kept, a reload brings back the defaults.
## Host your own ## Host your own
@@ -97,7 +118,47 @@ Then serve the `dist/` folder, with these requirements:
- **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for - **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for
trying it out). trying it out).
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below - **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
HellCon must reach it unchanged, so don't rewrite them to `index.html`. HellCon must reach it unchanged, so don't rewrite them to `index.html`. Any path works, e.g.
`https://example.org/hellcon/`, with the trailing slash: the page links its files relative to it,
so redirect `/hellcon` there.
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 first two keep other sites from framing HellCon and laying their own page over its buttons,
`X-Frame-Options` for older browsers.
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.
If you change how HellCon talks to the other side, e.g. the code, the encryption or the messages,
give `PROTOCOL` in `src/core.ts` a name of your own, e.g. `yourname/1`, and count up from there.
## Not planned
These were considered and decided against, please don't ask for them without a new reason. HellCon
is copy and paste a code, with public trackers and STUN servers. Anything that puts state in the URL,
needs infrastructure of its own or only helps small files doesn't pay off.
- **The code in a share link:** the code would end up in the browser history and wherever links get
handled, for one click less.
- **Another code alphabet,** e.g. one that ignores case or uses words: most people copy and paste
the code anyway.
- **Saving without the service worker,** holding the file in memory instead: useless for files of
several GB.
- **TURN servers or a relay-only mode:** too much infrastructure to host and test.
- **A longer or extendable share,** **several files as a zip,** and **resuming in Chromium:** not
for now.
- **Keeping a phone sending in the background,** e.g. with a silent audio loop: the sender's page
has to stay in front.
## Known limitations ## Known limitations
@@ -105,6 +166,8 @@ Then serve the `dist/` folder, with these requirements:
but Firefox keeps showing the download as in progress until you cancel it. but Firefox keeps showing the download as in progress until you cancel it.
- **Chromium:** notices a vanished sender only after about 16 seconds. - **Chromium:** notices a vanished sender only after about 16 seconds.
- An interrupted transfer can't be resumed, it starts over. - An interrupted transfer can't be resumed, it starts over.
- **Phones:** the sender's page has to stay in front, the connection is lost once it goes to the
background. Receiving keeps going.
- Private windows may not allow the background part that saves downloads. Receiving then doesn't - Private windows may not allow the background part that saves downloads. Receiving then doesn't
work, and HellCon tells you so. work, and HellCon tells you so.
+23 -55
View File
@@ -1,68 +1,27 @@
# TODO # TODO
## Server at pagequit.net, to decide
### Review of the coturn setup (STUN only, host network)
- Good as it is: `stun-only`, `no-tcp`, `no-tls`, `no-software-attribute`, CPU, memory and process
limits with swap off, and log rotation. Host networking is right for STUN, so Docker's NAT can't
change the source address the clients get back. Listening on IPv4 only matches DNS:
`stun.pagequit.net` has an A record and no AAAA.
- `coturn/coturn:latest` is the only unpinned version. Pin `coturn/coturn:4.18.0` (2026-09-08).
- Add `no-cli`. On the host network, coturn's admin CLI would otherwise listen on the host's
127.0.0.1:5766 if it's enabled.
- Add `no-stun-backward-compatibility`. Browsers only use the current STUN protocol, so the old
RFC 3489 requests and their extra MAPPED-ADDRESS can go, which also makes responses smaller for
reflection attacks.
- Check that the logs hold no client addresses: send a STUN request, then
`docker compose logs coturn | grep <your IP>`. Logging each request is off by default and
`log-binding` turns it on, so it should stay empty. Otherwise up to 20 MB of addresses stay around.
- Missing compared to the tracker draft: `cap_drop: [ALL]` and
`security_opt: [no-new-privileges:true]`. `read_only: true` is worth trying too, but coturn may
need a writable `/var/run` or `/var/lib/coturn` (`tmpfs`).
- coturn doesn't rate limit STUN requests. A response is about as big as the request, so it's a weak
amplifier. If it gets abused, an nftables `limit` on the UDP port would help.
### Compared to the plan so far
- Caddy and coturn don't share a Docker network, coturn runs on the host network. The tracker joins
Caddy's network (its name is in Caddy's compose file), coturn stays as it is.
- Copy coturn's limits to the tracker, with smaller values: `cpus`, `mem_limit` equal to
`memswap_limit`, `pids_limit`, and the same `json-file` log rotation.
- Pin every version, coturn and the tracker alike.
### Decisions
1. **Which tracker.** Stock `bittorrent-tracker@11.2.3` behind Caddy works: tested locally with a
real transfer from Chromium to Firefox, and it logs nothing with `--quiet`. A review found it too
open to run unchanged:
- it forwards any data and accepts messages up to 100 MiB
- `scrape` lists all swarms even with `--no-stats`
- it has no rate, byte or connection limits
- it accepts any Origin
The recommendation is an own tracker for the WebTorrent subset HellCon uses, so the client stays
unchanged and the public trackers keep working as fallbacks. Node 26 and `ws`, one file of about
250 lines, enforcing:
- an Origin allowlist and messages of at most 16 KiB
- only `announce`, one offer per announce, and answers only to offers it delivered, once
- per connection: a message rate, about 64 KiB of forwarded data, and at most 7 minutes
- connections per IP (from `X-Forwarded-For`), total connections and peers per swarm capped
- empty swarms removed, nothing logged
Then decide where it lives: `tracker/` in this repo (new files, every fork gets it) or a separate
repository.
2. **After deploying:** put `wss://tracker.pagequit.net` first in `DEFAULT_TRACKERS` and keep the
public trackers as fallbacks.
## Ideas ## Ideas
- Resume interrupted transfers: the receiver already reports how much the download manager has - 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 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. 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 ## 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 - 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 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 cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
@@ -77,3 +36,12 @@
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite), - `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 not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again. 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.
+14
View File
@@ -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
+6
View File
@@ -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"]
+79
View File
@@ -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}
+351
View File
@@ -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);
+540
View File
@@ -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);
});
+61 -3
View File
@@ -1,10 +1,13 @@
{ {
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json", "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": { "includes": ["**", "!**/node_modules", "!**/dist", "!**/test-results", "!**/*.svg"] }, "files": {
"includes": ["**", "!**/node_modules", "!**/dist", "!**/test-results", "!**/*.svg", "!**/pnpm-lock.yaml"]
},
"formatter": { "indentStyle": "space", "lineWidth": 120 }, "formatter": { "indentStyle": "space", "lineWidth": 120 },
"javascript": { "formatter": { "quoteStyle": "single" } }, "javascript": { "formatter": { "quoteStyle": "single" } },
"css": { "formatter": { "quoteStyle": "single" } }, "css": { "formatter": { "quoteStyle": "single" } },
"yaml": { "formatter": { "quoteStyle": "single" } },
"html": { "html": {
"experimentalFullSupportEnabled": true, "experimentalFullSupportEnabled": true,
"formatter": { "enabled": true, "selfCloseVoidElements": "always" } "formatter": { "enabled": true, "selfCloseVoidElements": "always" }
@@ -13,8 +16,63 @@
"rules": { "rules": {
"preset": "recommended", "preset": "recommended",
"nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" }, "nursery": { "noFloatingPromises": "error", "noMisusedPromises": "error" },
"style": { "noNonNullAssertion": "off", "noDescendingSpecificity": "off" }, "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" } "a11y": { "useSemanticElements": "off" }
} }
} },
"overrides": [
{ "includes": ["src/core.test.ts"], "linter": { "rules": { "style": { "noRestrictedImports": "off" } } } }
]
} }
+706 -632
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -5,6 +5,11 @@
<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</title> <title>HellCon</title>
</head> </head>
+15 -11
View File
@@ -1,7 +1,7 @@
{ {
"name": "hellcon", "name": "hellcon",
"private": true, "private": true,
"version": "0.1.0", "version": "1.0.2",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
"scripts": { "scripts": {
@@ -11,24 +11,28 @@
"typecheck": "vue-tsc", "typecheck": "vue-tsc",
"lint": "biome check", "lint": "biome check",
"format": "biome check --write", "format": "biome check --write",
"test": "playwright test", "test": "vitest run && playwright test",
"test:unit": "vitest",
"test:e2e": "playwright test",
"test:install": "playwright install chromium firefox", "test:install": "playwright install chromium firefox",
"test:large": "LARGE=1 playwright test -g large" "test:large": "LARGE=1 playwright test -g large"
}, },
"dependencies": { "dependencies": {
"vue": "^3.5.44" "vue": "^3.5.45"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "2.5.15", "@biomejs/biome": "2.6.3",
"@playwright/test": "^1.64.1", "@playwright/test": "^1.65.0",
"@types/node": "^26.6.5", "@types/node": "^26.6.6",
"@vitejs/plugin-vue": "^6.0.10", "@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": ">=26.11.1" "node": ">=26.13.1"
}, },
"packageManager": "pnpm@12.14.0" "packageManager": "pnpm@12.16.1"
} }
+4
View File
@@ -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/**' });
+669 -287
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -0,0 +1,2 @@
minimumReleaseAgeExclude:
- ws@8.23.0
+36 -11
View File
@@ -1,14 +1,37 @@
// Streams received files into the browser's download manager. It is the only script besides the app // 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 // because service workers can only be registered from a same-origin script URL. Registered with the
// scope download/ by src/core.ts, it sees no other requests. // 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 // 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. // reply port and how many bytes the download manager has read.
const downloads = new Map(); const downloads = new Map();
// Responses by download id, until the download navigation fetches them. Each is served only once. // Responses by download id, until the download navigation fetches them. Each is served only once.
const responses = new Map(); 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 open(id, { name, size }, port) { 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. // 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'); if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 }; const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
@@ -22,7 +45,7 @@ function open(id, { name, size }, port) {
const chunk = download.chunks.shift(); const chunk = download.chunks.shift();
if (chunk) { if (chunk) {
download.read += chunk.byteLength; download.read += chunk.byteLength;
// Every MiB, src/core.ts forwards it to the sender for its flow control window. // Every MiB, the receiver forwards it to the sender for its flow control window.
if (download.read - download.reported >= 2 ** 20) { if (download.read - download.reported >= 2 ** 20) {
download.reported = download.read; download.reported = download.read;
port.postMessage(download.read); port.postMessage(download.read);
@@ -30,18 +53,19 @@ function open(id, { name, size }, port) {
return controller.enqueue(chunk); return controller.enqueue(chunk);
} }
controller.close(); controller.close();
downloads.delete(id); forget(id);
port.postMessage('finished'); port.postMessage('finished');
}, },
// The user cancelled the download. // The user cancelled the download.
cancel: () => { cancel: () => {
downloads.delete(id); forget(id);
port.postMessage('cancelled'); port.postMessage('cancelled');
}, },
}, },
{ highWaterMark: 0 }, { highWaterMark: 0 },
); );
downloads.set(id, download); downloads.set(id, download);
watch(id, download);
// RFC 8187 encoding, which leaves nothing in the name that could end the header value. // RFC 8187 encoding, which leaves nothing in the name that could end the header value.
const encoded = encodeURIComponent(name.toWellFormed()).replace( const encoded = encodeURIComponent(name.toWellFormed()).replace(
@@ -57,17 +81,18 @@ function open(id, { name, size }, port) {
port.postMessage('ready'); port.postMessage('ready');
} }
// The page posts the metadata with a reply port first, then every chunk as its own message and // The page posts its version and the metadata with a reply port first, then every chunk as its own
// finally done (queued as the end marker null) or an error. Pings come in between. // message and finally done (queued as the end marker null) or an error. Pings come in between.
self.addEventListener('message', ({ data, ports: [port] }) => { self.addEventListener('message', ({ data, ports: [port] }) => {
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/core.ts.
if (data.ping) return;
if (port) return open(data.id, data, port); if (port) return open(data.id, data, port);
const download = downloads.get(data.id); const download = downloads.get(data.id);
if (!download) return; 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) { if (data.error) {
download.controller.error(new Error(data.error)); download.controller.error(new Error(data.error));
downloads.delete(data.id); forget(data.id);
download.port.postMessage('failed'); download.port.postMessage('failed');
} else { } else {
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null); download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
@@ -77,7 +102,7 @@ self.addEventListener('message', ({ data, ports: [port] }) => {
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {
const id = new URL(event.request.url).pathname.split('/').pop(); const id = new URL(event.request.url).pathname.split('/').pop();
// download/ itself is the empty page src/core.ts keeps open to hold this worker during a transfer. // download/ itself is the empty page src/download.ts keeps open to hold this worker during a transfer.
if (!id) if (!id)
return event.respondWith( return event.respondWith(
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }), new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
+272 -76
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'; import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
import { import {
answerOffer, answerOffer,
type Check, type Check,
@@ -8,35 +8,28 @@ import {
DEFAULT_STUN_SERVERS, DEFAULT_STUN_SERVERS,
DEFAULT_TRACKERS, DEFAULT_TRACKERS,
type Events, type Events,
formatTime,
type Incoming, type Incoming,
type Phase,
PROTOCOL,
type ReceiveEvents, type ReceiveEvents,
randomCode,
receiveViaTracker, receiveViaTracker,
type SendEvents,
sendViaTracker, sendViaTracker,
TRACKER_WAIT,
} from './core'; } from './core';
const SETTINGS_KEY = 'hellcon:settings'; // Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
// defaults.
// Same object as the core's, so the core sees every change.
const settings = reactive(coreSettings); const settings = reactive(coreSettings);
// Kept in this browser only. Storage can be blocked or hold something old, then the defaults stay. // Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
try { const ownSalt = reactive({ on: false, text: '' });
const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}'); // Empty is no salt, Share and Receive wait for one.
if (typeof saved.stun === 'boolean') settings.stun = saved.stun; const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
if (Array.isArray(saved.stunServers)) settings.stunServers = saved.stunServers; const salt = () => (ownSalt.on ? ownSalt.text : undefined);
if (Array.isArray(saved.trackers)) settings.trackers = saved.trackers; // From the code's alphabet, 16 characters are about 95 bits.
} catch {} const onGenerateSalt = () => (ownSalt.text = randomCode(16));
watch(
settings,
() => {
try {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
} catch {}
},
{ deep: true },
);
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core. // 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 // For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
@@ -54,9 +47,23 @@ function isStun(url: string) {
return stunChecks.get(url)!; return stunChecks.get(url)!;
} }
// Every # starts a fragment, which WebSocket rejects even when empty. // public/ in the build, which works under any path, see vite.config.ts.
const isTracker = (url: string) => const BASE = import.meta.env.BASE_URL;
URL.canParse(url) && ['ws:', 'wss:'].includes(new URL(url).protocol) && !url.includes('#');
// 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. // 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) { function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
@@ -68,7 +75,7 @@ function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boo
.filter(Boolean), .filter(Boolean),
); );
const invalid = computed(() => lines.value.filter((line) => !valid(line))); const invalid = computed(() => lines.value.filter((line) => !valid(line)));
// Immediate, a saved list may hold lines this browser rejects. // Immediate, a default may be a line this browser rejects.
watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true }); watch(lines, (lines) => (settings[key] = lines.filter(valid)), { immediate: true });
// Unwraps both refs, so the template can bind them as plain properties. // Unwraps both refs, so the template can bind them as plain properties.
return reactive({ text, invalid }); return reactive({ text, invalid });
@@ -83,13 +90,15 @@ function onResetServers() {
} }
const file = ref<File>(); 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 offer = ref('');
const answerInput = ref(''); const answerInput = ref('');
const sendCode = ref(''); const sendCode = ref('');
// Until when a receiver can find the share with its code, the time shown and whether it passed. // Until when a receiver can find the share with its code, whether with an own salt and whether that
const sendUntil = ref(''); // passed, as the core tells.
const sendUntil = ref(0);
const sendExpired = ref(false); const sendExpired = ref(false);
let sendTimer: number | undefined;
const offerInput = ref(''); const offerInput = ref('');
const answer = ref(''); const answer = ref('');
@@ -97,17 +106,31 @@ const receiveCode = ref('');
const check = ref<Check>(); const check = ref<Check>();
const confirmed = ref(false); const confirmed = ref(false);
const log = ref<string[]>([]); // 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. // Of the session, shown in the card of its side.
const error = ref(''); 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. // Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = { const events: Omit<Events, 'progress'> = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`), 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) => { error: (message) => {
events.log(message); events.log(message);
error.value = message; error.value = message;
}, },
status: (phase, text) => (status.value = { phase, text }),
check: (result) => { check: (result) => {
check.value = result; check.value = result;
confirmed.value = false; confirmed.value = false;
@@ -119,7 +142,11 @@ const events: Omit<Events, 'progress'> = {
type Progress = { read: number; size: number }; type Progress = { read: number; size: number };
const sent = ref<Progress>(); const sent = ref<Progress>();
const sendEvents: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) }; const sendEvents: SendEvents = {
...events,
progress: (read, size) => (sent.value = { read, size }),
expired: () => (sendExpired.value = true),
};
const incoming = ref<Incoming>(); const incoming = ref<Incoming>();
const received = ref<Progress>(); const received = ref<Progress>();
@@ -134,24 +161,43 @@ const receiveEvents: ReceiveEvents = {
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100); 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() { function onConfirm() {
confirmed.value = true; confirmed.value = true;
check.value?.confirm(); check.value?.confirm();
} }
// The text copied last, its button says so for a moment. // The text copied last and whether that worked. Its button says so, after a success for a moment.
const copied = ref(''); const copied = ref<{ text: string; ok: boolean }>();
let copiedTimer: number | undefined; let copiedTimer: number | undefined;
async function onCopy(text: string) { const copyLabel = (text: string) => (copied.value?.text !== text ? 'Copy' : copied.value.ok ? 'Copied' : 'Copy failed');
const copyFailed = (text: string) => copied.value?.text === text && !copied.value.ok;
// Copies text, shown in the element with id. If the browser blocks that, the text gets selected, so
// the user can copy it themselves.
async function onCopy(text: string, id: string) {
clearTimeout(copiedTimer);
try { try {
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
} catch { } catch {
return events.log('copy failed, the browser blocked the clipboard'); 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; copied.value = { text, ok: true };
clearTimeout(copiedTimer); copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
} }
let acceptAnswer: ((answer: string) => Promise<void>) | undefined; let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
@@ -160,12 +206,18 @@ let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
// the one before: its connections close and what it showed goes, so nothing else can write here. // the one before: its connections close and what it showed goes, so nothing else can write here.
let session: AbortController | undefined; let session: AbortController | undefined;
const side = ref<'send' | 'receive'>(); 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);
function begin(on: 'send' | 'receive') { // 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?.abort();
session = new AbortController(); session = new AbortController();
side.value = on; side.value = on;
viaTracker.value = tracker;
events.log(`--- ${what} ---`);
error.value = ''; error.value = '';
status.value = undefined;
check.value = undefined; check.value = undefined;
confirmed.value = false; confirmed.value = false;
sent.value = undefined; sent.value = undefined;
@@ -173,7 +225,6 @@ function begin(on: 'send' | 'receive') {
received.value = undefined; received.value = undefined;
sendCode.value = ''; sendCode.value = '';
sendExpired.value = false; sendExpired.value = false;
clearTimeout(sendTimer);
offer.value = ''; offer.value = '';
answer.value = ''; answer.value = '';
acceptAnswer = undefined; acceptAnswer = undefined;
@@ -191,15 +242,35 @@ async function attempt<T>(signal: AbortSignal, step: Promise<T>) {
} }
} }
// 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) { function onPick(event: Event) {
file.value = (event.target as HTMLInputElement).files?.[0]; const input = event.target as HTMLInputElement;
const picked = input.files?.[0];
input.value = '';
if (picked) take(picked);
} }
const dragging = ref(false); 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) { function onDrop(event: DragEvent) {
dragging.value = false; dragging.value = false;
file.value = event.dataTransfer?.files[0] ?? file.value; 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) { function formatSize(bytes: number) {
@@ -209,11 +280,12 @@ function formatSize(bytes: number) {
bytes /= 1024; bytes /= 1024;
unit++; unit++;
} }
return `${bytes.toFixed(unit ? 1 : 0)} ${units[unit]}`; return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
} }
async function onCreateOffer() { async function onCreateOffer() {
const signal = begin('send'); const signal = begin('send', `manual offer for ${file.value!.name}`);
shared.value = file.value;
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal)); const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
if (!result) return; if (!result) return;
offer.value = result.offer; offer.value = result.offer;
@@ -227,18 +299,18 @@ function onAcceptAnswer() {
} }
async function onCreateAnswer() { async function onCreateAnswer() {
const signal = begin('receive'); const signal = begin('receive', 'manual answer');
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal)); const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
if (result) answer.value = result; if (result) answer.value = result;
} }
async function onShare() { async function onShare() {
const signal = begin('send'); const signal = begin('send', `share ${file.value!.name} via tracker`, true);
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal)); shared.value = file.value;
if (!code) return; const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
sendCode.value = code; if (!result) return;
sendUntil.value = new Date(Date.now() + TRACKER_WAIT).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); sendCode.value = result.code;
sendTimer = window.setTimeout(() => (sendExpired.value = true), TRACKER_WAIT); sendUntil.value = result.until;
} }
// Also once the transfer started, which closes the trackers, and once the share failed: every error on // Also once the transfer started, which closes the trackers, and once the share failed: every error on
@@ -246,23 +318,115 @@ async function onShare() {
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value); const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
function onReceive() { function onReceive() {
const signal = begin('receive'); const signal = begin('receive', 'receive via tracker', true);
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal)); 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>
<header> <header>
<img src="/HellNet_alt.png" alt="" width="40" height="40" /> <div>
<img :src="`${BASE}HellNet_alt.png`" alt="" width="40" height="40" />
<h1>HellCon</h1> <h1>HellCon</h1>
</div>
<div id="options">
<div>
<label> <label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed --> <!-- 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" /> <input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
Use STUN Use STUN
</label> </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> </header>
<main> <main>
<p v-if="!settings.stun" id="no-stun" role="note">
STUN is off: only devices on the same network or VPN can connect.
</p>
<p v-else-if="!settings.stunServers.length" id="no-stun" role="note">
No STUN server under Servers: only devices on the same network or VPN can connect.
</p>
<aside v-if="check" role="alert"> <aside v-if="check" role="alert">
<p> <p>
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
@@ -288,33 +452,52 @@ function onReceive() {
@dragleave="dragging = false" @dragleave="dragging = false"
@drop.prevent="onDrop" @drop.prevent="onDrop"
> >
<input type="file" @change="onPick" /> <input type="file" :title="file?.name" @change="onPick" />
<template v-if="file"> <template v-if="file">
<strong>{{ file.name }}</strong> <strong>{{ file.name }}</strong>
{{ formatSize(file.size) }} {{ formatSize(file.size) }}
</template> </template>
<template v-else>Drop a file or click to choose</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> </label>
<p v-if="sent"> <div v-if="side === 'send' && phase" :data-phase="phase">
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress> <p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
{{ percent(sent) }} % <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) }}&nbsp;%</span>
</p> </p>
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p> </div>
<section> <section>
<h3>Tracker</h3> <h3>Tracker</h3>
<button id="share" type="button" :disabled="!file || !settings.trackers.length" @click="onShare"> <button id="share" type="button" :disabled="!file || !settings.trackers.length || saltMissing" @click="onShare">
Share via tracker Share via tracker
</button> </button>
<template v-if="sendCode"> <template v-if="sendCode">
<label v-if="codeGone" for="send-code">Code, no longer valid:</label> <label v-if="codeGone" for="send-code">Code, no longer valid:</label>
<label v-else for="send-code">Code, give this to the receiver, valid until {{ sendUntil }}:</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"> <div role="group">
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output> <output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
<button id="copy-send-code" type="button" data-copy :disabled="codeGone" @click="onCopy(sendCode)"> <button
{{ copied === sendCode ? 'Copied' : 'Copy' }} id="copy-send-code"
type="button"
data-copy
:disabled="codeGone"
@click="onCopy(sendCode, 'send-code')"
>
{{ copyLabel(sendCode) }}
</button> </button>
</div> </div>
<p v-if="copyFailed(sendCode)" role="alert">
The browser blocked copying. The code is selected, copy it yourself.
</p>
</template> </template>
</section> </section>
@@ -325,9 +508,12 @@ function onReceive() {
<template v-if="offer"> <template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label> <label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea> <textarea id="offer" readonly :value="offer"></textarea>
<button id="copy-offer" type="button" data-copy @click="onCopy(offer)"> <button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
{{ copied === offer ? 'Copied' : 'Copy' }} {{ copyLabel(offer) }}
</button> </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> <label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea> <textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer"> <button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
@@ -348,11 +534,16 @@ function onReceive() {
</template> </template>
<template v-else>The sender's file shows up here after the security check</template> <template v-else>The sender's file shows up here after the security check</template>
</div> </div>
<p v-if="received"> <div v-if="side === 'receive' && phase" :data-phase="phase">
<progress id="receive-progress" max="100" :value="percent(received)" aria-label="Received"></progress> <div>
{{ percent(received) }} % <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) }}&nbsp;%</span>
</p> </p>
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p> </div>
<section> <section>
<h3>Tracker</h3> <h3>Tracker</h3>
@@ -369,7 +560,7 @@ function onReceive() {
<button <button
id="receive" id="receive"
type="button" type="button"
:disabled="!settings.trackers.length || !receiveCode.trim()" :disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
@click="onReceive" @click="onReceive"
> >
Receive Receive
@@ -388,9 +579,12 @@ function onReceive() {
<template v-if="answer"> <template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label> <label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea> <textarea id="answer" readonly :value="answer"></textarea>
<button id="copy-answer" type="button" data-copy @click="onCopy(answer)"> <button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
{{ copied === answer ? 'Copied' : 'Copy' }} {{ copyLabel(answer) }}
</button> </button>
<p v-if="copyFailed(answer)" role="alert">
The browser blocked copying. The answer is selected, copy it yourself.
</p>
</template> </template>
</section> </section>
</details> </details>
@@ -416,7 +610,8 @@ function onReceive() {
<label for="trackers">WebTorrent trackers for the code exchange, one URL per line:</label> <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> <textarea id="trackers" v-model="trackers.text" :aria-invalid="!!trackers.invalid.length"></textarea>
<p v-if="trackers.invalid.length"> <p v-if="trackers.invalid.length">
Skipped, not a ws: or wss: URL without #: {{ trackers.invalid.join(', ') }} Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}:
{{ trackers.invalid.join(', ') }}
</p> </p>
</section> </section>
<button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button> <button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button>
@@ -425,14 +620,15 @@ function onReceive() {
<details> <details>
<summary>Log</summary> <summary>Log</summary>
<pre id="log">{{ log.join('\n') }}</pre> <pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
</details> </details>
</main> </main>
<footer> <footer>
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer"> <a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
<img src="/gitea.svg" alt="" width="20" height="20" /> <img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
Source code Source code
</a> </a>
<span>Protocol {{ PROTOCOL }}</span>
</footer> </footer>
</template> </template>
+1772
View File
File diff suppressed because it is too large. Load diff
+661 -266
View File
File diff suppressed because it is too large. Load diff
+165
View File
@@ -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));
},
};
}
+138 -25
View File
@@ -113,19 +113,38 @@ footer {
padding-inline: var(--space-4); 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 { 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; display: flex;
align-items: center; align-items: center;
gap: var(--space-3); gap: var(--space-3);
padding-block: var(--space-6);
} }
header h1 { header h1 {
font-size: var(--text-xl); font-size: var(--text-xl);
} }
header label { /* The switches at the end, the own salt below while it's on */
margin-left: auto; #options {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
#options > div:first-child {
display: flex;
flex-wrap: wrap;
justify-content: end;
align-items: center;
gap: var(--space-3);
} }
main { main {
@@ -136,11 +155,18 @@ main {
padding-bottom: var(--space-8); padding-bottom: var(--space-8);
} }
main > p,
main > aside, main > aside,
main > details { main > details {
grid-column: 1 / -1; 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 */ /* Cards */
article, article,
@@ -186,6 +212,10 @@ section p {
color: var(--color-text-muted); color: var(--color-text-muted);
} }
section p[role='alert'] {
color: var(--color-secondary-text);
}
header label { header label {
color: var(--color-text); color: var(--color-text);
} }
@@ -208,6 +238,17 @@ textarea:focus {
border-color: var(--color-secondary); 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 */ /* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
input:not([type='checkbox'], [type='file']):focus-visible, input:not([type='checkbox'], [type='file']):focus-visible,
textarea:focus-visible { textarea:focus-visible {
@@ -281,7 +322,7 @@ button:disabled {
user-select: none; user-select: none;
} }
/* Copy buttons, secondary next to the value they copy */ /* Copy and Generate, secondary next to the value they are for */
[data-copy] { [data-copy] {
padding: var(--space-1) var(--space-3); padding: var(--space-1) var(--space-3);
@@ -370,54 +411,120 @@ label strong,
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
/* Progress and what went wrong, below the file on both sides */ /* A dropped folder, refused */
#not-a-file {
article > p[role='alert'] {
font-size: var(--text-sm);
color: var(--color-secondary-text); color: var(--color-secondary-text);
overflow-wrap: anywhere;
} }
article > p[role='alert']::first-letter { /* How the session is doing, below the file on its side. Until the transfer starts a pill passes
text-transform: uppercase; 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);
p:has(> progress) {
display: flex; display: flex;
align-items: center; 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); gap: var(--space-3);
font-size: var(--text-sm); font-size: var(--text-sm);
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
color: var(--color-text-muted); color: var(--color-text-muted);
} }
progress { /* The send session's file, above its bar once the user picked another one */
flex: 1; #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; height: 0.5rem;
appearance: none;
border: none;
border-radius: 999px; border-radius: 999px;
background: var(--color-input); background: var(--color-input);
overflow: hidden; overflow: hidden;
} }
progress {
display: block;
width: 100%;
height: 100%;
appearance: none;
border: none;
background: none;
}
progress::-webkit-progress-bar { progress::-webkit-progress-bar {
background: var(--color-input); background: none;
} }
progress::-webkit-progress-value { progress::-webkit-progress-value {
background: var(--color-primary); background: var(--bar);
} }
progress::-moz-progress-bar { progress::-moz-progress-bar {
background: var(--color-primary); background: var(--bar);
} }
progress[value='100']::-webkit-progress-value { progress:indeterminate {
background: var(--color-success); width: 25%;
border-radius: 999px;
background: var(--bar);
animation: pass 2584ms linear infinite;
} }
progress[value='100']::-moz-progress-bar { progress:indeterminate::-moz-progress-bar {
background: var(--color-success); 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" */ /* Switch, like Pico's role="switch" */
@@ -515,14 +622,20 @@ output {
/* Source link, quiet below everything */ /* Source link, quiet below everything */
footer { footer {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: var(--space-2) var(--space-4);
padding-bottom: var(--space-6); padding-bottom: var(--space-6);
font-size: var(--text-sm);
color: var(--color-text-muted);
} }
footer a { footer a {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: var(--space-2); gap: var(--space-2);
font-size: var(--text-sm);
color: var(--color-text-muted); color: var(--color-text-muted);
text-decoration: none; text-decoration: none;
transition: color var(--transition); transition: color var(--transition);
+2 -1
View File
@@ -13,7 +13,8 @@
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"isolatedModules": true, "isolatedModules": true,
"skipLibCheck": true, "skipLibCheck": true,
"allowJs": true,
"noEmit": true "noEmit": true
}, },
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"] "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "playwright.config.ts", "e2e.spec.ts"]
} }
+25 -1
View File
@@ -1,6 +1,30 @@
/// <reference types="vitest/config" />
import vue from '@vitejs/plugin-vue'; import vue from '@vitejs/plugin-vue';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
const DEV_STYLE_SRC = "style-src 'self'";
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [
vue(),
// index.html's Content-Security-Policy allows no inline styles, the dev server injects the CSS
// through JavaScript. A nonce lets only those style elements through, so the dev server enforces
// the same policy as the production build, which links the CSS as files.
{
name: 'dev-csp',
apply: 'serve',
config: () => ({ html: { cspNonce: 'dev' } }),
transformIndexHtml(html) {
if (!html.includes(DEV_STYLE_SRC)) throw new Error(`dev-csp: index.html has no "${DEV_STYLE_SRC}"`);
return html.replace(DEV_STYLE_SRC, `${DEV_STYLE_SRC} 'nonce-dev'`);
},
},
],
// The dev server would inline small images like gitea.svg as data: URLs, which index.html's
// Content-Security-Policy blocks. The production build links them as files either way.
build: { assetsInlineLimit: 0 },
// Relative links, so the build works under any path, not only at the root of a host.
base: './',
// Playwright runs e2e.spec.ts and backend/, which Vitest would pick up too.
test: { include: ['src/**/*.test.ts'] },
}); });