Compare commits

..
20 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
22 changed files with 4736 additions and 1418 deletions

No files matched your search

+66 -10
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
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
get the file, so give it to nobody else.
an 11 character code. Tell it to the receiver, it works for 6 minutes. Whoever has the code can
get the file, or pretend to be you, so give it to nobody else.
2. **Receiver:** open HellCon, enter the code under Receive and click **Receive**.
3. **Receiver:** once connected, you see the file's name and size. Click **Download** to save it.
Keep both tabs open until the transfer is finished. Starting something new in a tab ends what that
tab was doing.
Both sides need the same protocol, shown at the bottom of the page. A HellCon hosted elsewhere may
run another one, the receiver then finds no sender, or with **Manual** says the sender runs another
protocol.
### Without a tracker
If you'd rather not use a tracker, open **Manual** on both sides. The sender creates an offer, a
@@ -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.
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
trust, ideally a call or in person:
codes: **You** and **Peer**. Compare them with the other person over a channel you already trust,
ideally a call or in person:
- your **You** must be their **Peer**, and
- your **Peer** must be their **You**.
If both match, you are connected directly to each other. If they don't, someone has placed
themselves in between: click **Codes don't match** and nothing is sent. Nothing is transferred before
both sides confirmed, so take the 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
own keys, which show up as different codes.
@@ -63,8 +67,11 @@ 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
your browser's download list.
There is no relay server. If both sides are behind very strict networks, e.g. some company or mobile
networks, a direct connection may not be possible.
HellCon uses no relay server. If both sides are behind very strict networks, e.g. some company or
mobile networks, a direct connection may not be possible. And a connection that works isn't
necessarily direct: the other side may name a relay of its own, and a STUN server that reports a
wrong address can put itself in between. Either only passes on encrypted data. The security check
makes sure the connection ends at the two of you.
## Privacy
@@ -73,8 +80,10 @@ networks, a direct connection may not be possible.
few trackers see it too, from the request itself. HellCon tries the STUN servers in order and
sticks with the first that answers. The sender stays on the first tracker that accepts it. The
receiver goes down the list until it finds the sender, and the trackers it passes keep its
encrypted offer. Nobody without the code learns your address through a tracker.
- Settings (STUN on or off, your server lists) are kept in your browser only.
encrypted offer. Nobody without the code learns your address through a tracker. The tracker the
two of you meet on does see which addresses share with each other, and when. If that matters,
use your own tracker and STUN server, or the manual exchange.
- Nothing is kept: every reload starts with the default settings.
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
host your own (below).
@@ -86,6 +95,15 @@ brings back the original lists. The order matters: the sender stays on the first
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
HellCon is a static website, any web server can host it. Build it with Node.js and pnpm:
@@ -100,18 +118,56 @@ Then serve the `dist/` folder, with these requirements:
- **HTTPS.** Browsers only allow the parts HellCon needs on secure pages (`localhost` is fine for
trying it out).
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
HellCon must reach it unchanged, so don't rewrite them to `index.html`.
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
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
but Firefox keeps showing the download as in progress until you cancel it.
- **Chromium:** notices a vanished sender only after about 16 seconds.
- An interrupted transfer can't be resumed, it starts over.
- **Phones:** the sender's page has to stay in front, the connection is lost once it goes to the
background. Receiving keeps going.
- Private windows may not allow the background part that saves downloads. Receiving then doesn't
work, and HellCon tells you so.
+22 -4
View File
@@ -6,8 +6,22 @@
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
finished or failed download though, so a resume would have to start a new one.
- Keep user settings again: for now every reload starts from the defaults, the server lists and the
own salt too. Open which ones to keep, and how a kept one that differs from the other side's would
show, instead of silently breaking a share.
- Revisit the screen wake lock: a browser that keeps refusing it (e.g. in a power saving mode) logs
"screen may lock" each time the page is visible again, open whether once per session is enough.
`awake: …` doesn't cover a session that ends in an error, nor one that ends while a request is
still pending, the case the `wakeLock === request` checks in `holdWakeLock` are for.
## Open observations
- A phone can't send in the background: with Brave on Android (Pixel), the connection is lost as
soon as the sender's page goes to the background. Receiving survives it, likely because the
browser's download manager runs as a foreground service while the file streams into it. The wake
lock only keeps the screen from timing out, the sender's page has to stay in front.
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
logs "download failed: connection lost", but the download stays "in progress" until the user
cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
@@ -23,7 +37,11 @@
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again.
- `boundary: chromium sends an empty file` timed out in the first two full runs after `backend/`'s
tests were added (2026-10-25), with empty logs on both sides. It passed alone 8 times, and in 7
full runs since, one of them with a cold Vite cache. The suite without the new tests passed 4
times. Not reproduced, cause unknown.
- 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.
+5
View File
@@ -7,3 +7,8 @@ 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
+2 -2
View File
@@ -1,6 +1,6 @@
FROM node:26.12.1-alpine3.23
FROM node:26.13.1-alpine3.23
WORKDIR /app
RUN npm install --no-save --omit=dev ws@8.22.0
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"]
+9 -1
View File
@@ -18,6 +18,12 @@ services:
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]
@@ -33,7 +39,8 @@ services:
restart: unless-stopped
# On the host network, so Docker's NAT can't change the source address clients get back. UDP 3478
# on IPv4 only, stun.example.org needs an A record and no AAAA.
# 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
@@ -43,6 +50,7 @@ services:
command:
- --log-file=stdout
- --listening-ip=0.0.0.0
- --listening-ip=::
- --listening-port=3478
- --stun-only
- --no-tcp
+174 -15
View File
@@ -1,8 +1,10 @@
// 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.
// 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().
@@ -24,12 +26,36 @@ const MAX_MESSAGE = 16 * 1024;
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.
@@ -37,17 +63,84 @@ 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';
// Behind Caddy, the only way in. Caddy replaces any X-Forwarded-For a client sends, the last entry is
// its own anyway.
// 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) {
return req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
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) {
@@ -56,10 +149,32 @@ function refuse(socket, status) {
// 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.
// 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.bufferedAmount + bytes <= MAX_QUEUED) return true;
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) {
@@ -76,6 +191,9 @@ function reject(peer, reason) {
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);
}
@@ -89,6 +207,7 @@ function announce(peer, msg) {
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;
@@ -133,8 +252,20 @@ function announce(peer, msg) {
}
}
function open(ws) {
const peer = { ws, id: undefined, hash: undefined, seeder: false, pending: new Map(), forwarded: 0, messages: 0 };
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.
@@ -155,6 +286,8 @@ function open(ws) {
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);
@@ -169,7 +302,22 @@ function open(ws) {
}
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
export const server = createServer((_, res) => res.writeHead(404).end());
// 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.
@@ -177,16 +325,27 @@ server.on('upgrade', (req, socket, head) => {
const ip = clientIp(req);
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
if ((perIp.get(ip) ?? 0) >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
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++;
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
used.open++;
used.connects++;
socket.once('close', () => {
connections--;
const left = perIp.get(ip) - 1;
if (left) perIp.set(ip, left);
else perIp.delete(ip);
used.open--;
});
wss.handleUpgrade(req, socket, head, 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);
+176 -3
View File
@@ -7,6 +7,7 @@ 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 = [];
@@ -18,11 +19,23 @@ let tests = 0;
test.beforeAll(async () => {
process.env.PORT = '0';
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`;
const { server } = await import('./tracker.mjs');
// 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}`;
});
@@ -33,14 +46,29 @@ test.afterEach(async () => {
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 } = {}) {
function open({ origin = ORIGIN, xff = ip } = {}) {
return new Promise((resolve) => {
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': ip } });
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', () => {
@@ -278,6 +306,51 @@ test('limits the signaling forwarded per connection', async () => {
);
});
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();
@@ -310,6 +383,42 @@ test('drops a peer that stops reading', async () => {
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 });
@@ -323,6 +432,70 @@ test('limits connections per IP to 16', async () => {
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');
+61 -3
View File
@@ -1,10 +1,13 @@
{
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"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 },
"javascript": { "formatter": { "quoteStyle": "single" } },
"css": { "formatter": { "quoteStyle": "single" } },
"yaml": { "formatter": { "quoteStyle": "single" } },
"html": {
"experimentalFullSupportEnabled": true,
"formatter": { "enabled": true, "selfCloseVoidElements": "always" }
@@ -13,8 +16,63 @@
"rules": {
"preset": "recommended",
"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" }
}
}
},
"overrides": [
{ "includes": ["src/core.test.ts"], "linter": { "rules": { "style": { "noRestrictedImports": "off" } } } }
]
}
+633 -713
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="robots" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="referrer" content="no-referrer" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; style-src 'self'; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'none'; form-action 'none'"
/>
<link rel="icon" type="image/png" href="./HellNet_alt.png" />
<title>HellCon</title>
</head>
+15 -12
View File
@@ -1,7 +1,7 @@
{
"name": "hellcon",
"private": true,
"version": "0.1.0",
"version": "1.0.2",
"license": "MIT",
"type": "module",
"scripts": {
@@ -11,25 +11,28 @@
"typecheck": "vue-tsc",
"lint": "biome check",
"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:large": "LARGE=1 playwright test -g large"
},
"dependencies": {
"vue": "^3.5.44"
"vue": "^3.5.45"
},
"devDependencies": {
"@biomejs/biome": "2.5.15",
"@playwright/test": "^1.64.1",
"@types/node": "^26.6.5",
"@vitejs/plugin-vue": "^6.0.10",
"@biomejs/biome": "2.6.3",
"@playwright/test": "^1.65.0",
"@types/node": "^26.6.6",
"@vitejs/plugin-vue": "^6.0.11",
"typescript": "~6.0.3",
"vite": "^8.3.5",
"vue-tsc": "^3.3.13",
"ws": "8.22.0"
"vite": "^8.3.8",
"vitest": "^5.1.0",
"vue-tsc": "^3.3.14",
"ws": "8.23.0"
},
"engines": {
"node": ">=26.12.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/**' });
+644 -279
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
// 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
// reply port and how many bytes the download manager has read.
const downloads = new Map();
// Responses by download id, until the download navigation fetches them. Each is served only once.
const responses = new Map();
// The page pings every KEEPALIVE while a transfer stalls, see src/download.ts. Silent for this long,
// it is gone, e.g. its tab was closed: Firefox would stop this worker 30 s after the last event and
// save the truncated file as complete. A failed stream leaves the download failed instead. A page
// that is still there, only late, e.g. throttled in the background, is told with silent.
const SILENCE = 20_000;
function 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.
if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
@@ -22,7 +45,7 @@ function open(id, { name, size }, port) {
const chunk = download.chunks.shift();
if (chunk) {
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) {
download.reported = download.read;
port.postMessage(download.read);
@@ -30,18 +53,19 @@ function open(id, { name, size }, port) {
return controller.enqueue(chunk);
}
controller.close();
downloads.delete(id);
forget(id);
port.postMessage('finished');
},
// The user cancelled the download.
cancel: () => {
downloads.delete(id);
forget(id);
port.postMessage('cancelled');
},
},
{ highWaterMark: 0 },
);
downloads.set(id, download);
watch(id, download);
// RFC 8187 encoding, which leaves nothing in the name that could end the header value.
const encoded = encodeURIComponent(name.toWellFormed()).replace(
@@ -57,17 +81,18 @@ function open(id, { name, size }, port) {
port.postMessage('ready');
}
// The page posts the metadata with a reply port first, then every chunk as its own message and
// finally done (queued as the end marker null) or an error. Pings come in between.
// The page posts its version and the metadata with a reply port first, then every chunk as its own
// message and finally done (queued as the end marker null) or an error. Pings come in between.
self.addEventListener('message', ({ data, ports: [port] }) => {
// 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);
const download = downloads.get(data.id);
if (!download) return;
watch(data.id, download);
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/download.ts.
if (data.ping) return;
if (data.error) {
download.controller.error(new Error(data.error));
downloads.delete(data.id);
forget(data.id);
download.port.postMessage('failed');
} else {
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
@@ -77,7 +102,7 @@ self.addEventListener('message', ({ data, ports: [port] }) => {
self.addEventListener('fetch', (event) => {
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)
return event.respondWith(
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
+272 -76
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { computed, reactive, ref, shallowRef, triggerRef, watch } from 'vue';
import {
answerOffer,
type Check,
@@ -8,35 +8,28 @@ import {
DEFAULT_STUN_SERVERS,
DEFAULT_TRACKERS,
type Events,
formatTime,
type Incoming,
type Phase,
PROTOCOL,
type ReceiveEvents,
randomCode,
receiveViaTracker,
type SendEvents,
sendViaTracker,
TRACKER_WAIT,
} from './core';
const SETTINGS_KEY = 'hellcon:settings';
// Same object as the core's, so the core sees every change.
// Same object as the core's, so the core sees every change. Nothing is kept, a reload brings back the
// defaults.
const settings = reactive(coreSettings);
// Kept in this browser only. Storage can be blocked or hold something old, then the defaults stay.
try {
const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}');
if (typeof saved.stun === 'boolean') settings.stun = saved.stun;
if (Array.isArray(saved.stunServers)) settings.stunServers = saved.stunServers;
if (Array.isArray(saved.trackers)) settings.trackers = saved.trackers;
} catch {}
watch(
settings,
() => {
try {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
} catch {}
},
{ deep: true },
);
// Instead of the clock's, while on. Not kept either, a forgotten one would break every later share.
const ownSalt = reactive({ on: false, text: '' });
// Empty is no salt, Share and Receive wait for one.
const saltMissing = computed(() => ownSalt.on && !ownSalt.text.trim());
const salt = () => (ownSalt.on ? ownSalt.text : undefined);
// From the code's alphabet, 16 characters are about 95 bits.
const onGenerateSalt = () => (ownSalt.text = randomCode(16));
// RTCPeerConnection and WebSocket throw on a URL they don't accept, so only valid lines reach the core.
// For STUN the browser decides, e.g. Firefox rejects stuns: and both a port beyond 65535. A connection
@@ -54,9 +47,23 @@ function isStun(url: string) {
return stunChecks.get(url)!;
}
// Every # starts a fragment, which WebSocket rejects even when empty.
const isTracker = (url: string) =>
URL.canParse(url) && ['ws:', 'wss:'].includes(new URL(url).protocol) && !url.includes('#');
// public/ in the build, which works under any path, see vite.config.ts.
const BASE = import.meta.env.BASE_URL;
// Every # starts a fragment, which WebSocket rejects even when empty. An https page may open ws: only
// to this device, browsers refuse it or fail it for anything else. That is localhost and its
// subdomains, 127.0.0.0/8 and ::1, URL writes every form of these addresses this way.
const secure = location.protocol === 'https:';
const isLocal = (hostname: string) =>
hostname === 'localhost' ||
hostname.endsWith('.localhost') ||
/^127\.\d+\.\d+\.\d+$/.test(hostname) ||
hostname === '[::1]';
const isTracker = (url: string) => {
if (!URL.canParse(url) || url.includes('#')) return false;
const { protocol, hostname } = new URL(url);
return protocol === 'wss:' || (protocol === 'ws:' && (!secure || isLocal(hostname)));
};
// A textarea with one URL per line for the list at settings[key], invalid lines are listed and skipped.
function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boolean) {
@@ -68,7 +75,7 @@ function serverList(key: 'stunServers' | 'trackers', valid: (url: string) => boo
.filter(Boolean),
);
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 });
// Unwraps both refs, so the template can bind them as plain properties.
return reactive({ text, invalid });
@@ -83,13 +90,15 @@ function onResetServers() {
}
const file = ref<File>();
// The file of the send session, the user may have picked another one since.
const shared = ref<File>();
const offer = ref('');
const answerInput = ref('');
const sendCode = ref('');
// Until when a receiver can find the share with its code, the time shown and whether it passed.
const sendUntil = ref('');
// Until when a receiver can find the share with its code, whether with an own salt and whether that
// passed, as the core tells.
const sendUntil = ref(0);
const sendExpired = ref(false);
let sendTimer: number | undefined;
const offerInput = ref('');
const answer = ref('');
@@ -97,17 +106,31 @@ const receiveCode = ref('');
const check = ref<Check>();
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.
const error = ref('');
const status = ref<{ phase: Phase; text: string }>();
// The bar's look, an error colors whatever it showed.
const phase = computed(() => (error.value ? 'error' : status.value?.phase));
// Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = {
log: (message) => 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) => {
events.log(message);
error.value = message;
},
status: (phase, text) => (status.value = { phase, text }),
check: (result) => {
check.value = result;
confirmed.value = false;
@@ -119,7 +142,11 @@ const events: Omit<Events, 'progress'> = {
type Progress = { read: number; size: number };
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 received = ref<Progress>();
@@ -134,24 +161,43 @@ const receiveEvents: ReceiveEvents = {
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
// Undefined makes the bar indeterminate: until the transfer starts it only shows how the session is
// doing. After it, or an error before it, the bar is full.
function barValue(progress?: Progress) {
if (progress) return percent(progress);
return ['start', 'wait', 'retry'].includes(phase.value!) ? undefined : 100;
}
function onConfirm() {
confirmed.value = true;
check.value?.confirm();
}
// The text copied last, its button says so for a moment.
const copied = ref('');
// The text copied last and whether that worked. Its button says so, after a success for a moment.
const copied = ref<{ text: string; ok: boolean }>();
let copiedTimer: number | undefined;
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 {
await navigator.clipboard.writeText(text);
} 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;
clearTimeout(copiedTimer);
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
copied.value = { text, ok: true };
copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
}
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.
let session: AbortController | undefined;
const side = ref<'send' | 'receive'>();
// Whether the session is a tracker share or search, which runs with the salt it started with.
const viaTracker = ref(false);
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 = new AbortController();
side.value = on;
viaTracker.value = tracker;
events.log(`--- ${what} ---`);
error.value = '';
status.value = undefined;
check.value = undefined;
confirmed.value = false;
sent.value = undefined;
@@ -173,7 +225,6 @@ function begin(on: 'send' | 'receive') {
received.value = undefined;
sendCode.value = '';
sendExpired.value = false;
clearTimeout(sendTimer);
offer.value = '';
answer.value = '';
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) {
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);
// A folder comes as a file too, one that can't be read: refused here, it would fail only once the
// receiver downloads it. The file picked before stays.
function onDrop(event: DragEvent) {
dragging.value = false;
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) {
@@ -209,11 +280,12 @@ function formatSize(bytes: number) {
bytes /= 1024;
unit++;
}
return `${bytes.toFixed(unit ? 1 : 0)} ${units[unit]}`;
return `${bytes.toFixed(unit ? 1 : 0)}\u00a0${units[unit]}`;
}
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));
if (!result) return;
offer.value = result.offer;
@@ -227,18 +299,18 @@ function onAcceptAnswer() {
}
async function onCreateAnswer() {
const signal = begin('receive');
const signal = begin('receive', 'manual answer');
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
if (result) answer.value = result;
}
async function onShare() {
const signal = begin('send');
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
if (!code) return;
sendCode.value = code;
sendUntil.value = new Date(Date.now() + TRACKER_WAIT).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
sendTimer = window.setTimeout(() => (sendExpired.value = true), TRACKER_WAIT);
const signal = begin('send', `share ${file.value!.name} via tracker`, true);
shared.value = file.value;
const result = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal, salt()));
if (!result) return;
sendCode.value = result.code;
sendUntil.value = result.until;
}
// Also once the transfer started, which closes the trackers, and once the share failed: every error on
@@ -246,23 +318,115 @@ async function onShare() {
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
function onReceive() {
const signal = begin('receive');
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
const signal = begin('receive', 'receive via tracker', true);
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal, salt()));
}
// The salt stays as it is while a tracker share runs: it waits in the swarm of the salt it started
// with, another one shown would be the wrong one to give the receiver. A search only takes the salt
// on Receive, so a wrong one can be fixed and searched with again.
const saltLocked = computed(
() => viaTracker.value && side.value === 'send' && !['error', 'done', 'stopped'].includes(phase.value!),
);
// While a share waits or a transfer runs. A phone that dims and locks may suspend the tab and the
// connection dies, a reload or a closed tab ends it for sure.
const busy = computed(() => ['start', 'wait', 'retry', 'transfer'].includes(phase.value!));
// The screen's, held while busy. The browser releases it whenever the page is hidden, so it's
// requested again once the page is visible.
let wakeLock: Promise<WakeLockSentinel | undefined> | undefined;
function holdWakeLock() {
// Missing outside a secure context, e.g. the dev server opened by its LAN address.
if (!busy.value || document.hidden || wakeLock || !navigator.wakeLock) return;
const request = navigator.wakeLock.request('screen').then(
(sentinel) => {
sentinel.addEventListener('release', () => {
if (wakeLock === request) wakeLock = undefined;
});
// Unless let go of meanwhile, releaseWakeLock releases it then.
if (wakeLock === request) events.log('keeping the screen on');
return sentinel;
},
(failure) => {
if (wakeLock === request) wakeLock = undefined;
events.log(`screen may lock: ${failure instanceof Error ? failure.message : failure}`);
return undefined;
},
);
wakeLock = request;
}
// Forgotten right away, a session started before the browser released it requests a new one.
function releaseWakeLock() {
const request = wakeLock;
wakeLock = undefined;
request?.then((sentinel) => sentinel?.release());
}
// The browser asks before a reload or a closed tab ends it. Only while busy, a page with the handler
// may be kept out of the back/forward cache.
const confirmLeave = (event: BeforeUnloadEvent) => event.preventDefault();
watch(busy, (busy) => {
if (busy) {
holdWakeLock();
addEventListener('beforeunload', confirmLeave);
} else {
releaseWakeLock();
removeEventListener('beforeunload', confirmLeave);
}
});
document.addEventListener('visibilitychange', holdWakeLock);
</script>
<template>
<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>
</div>
<div id="options">
<div>
<label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
<input id="stun" v-model="settings.stun" type="checkbox" role="switch" />
Use STUN
</label>
<label>
<!-- biome-ignore lint/a11y/useAriaPropsForRole: a checkbox reports its own state, aria-checked on it is not allowed -->
<input id="own-salt" v-model="ownSalt.on" type="checkbox" role="switch" :disabled="saltLocked" />
Use own salt
</label>
</div>
<div v-if="ownSalt.on" role="group">
<input
id="salt"
v-model="ownSalt.text"
aria-label="Own salt"
placeholder="Same salt on both sides"
:aria-invalid="saltMissing"
:disabled="saltLocked"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button id="generate-salt" type="button" data-copy :disabled="saltLocked" @click="onGenerateSalt">
Generate
</button>
</div>
</div>
</header>
<main>
<p v-if="!settings.stun" id="no-stun" role="note">
STUN is off: only devices on the same network or VPN can connect.
</p>
<p v-else-if="!settings.stunServers.length" id="no-stun" role="note">
No STUN server under Servers: only devices on the same network or VPN can connect.
</p>
<aside v-if="check" role="alert">
<p>
Security check: the other side must show the same two codes, swapped. Both sides confirm, nothing is transferred
@@ -288,33 +452,52 @@ function onReceive() {
@dragleave="dragging = false"
@drop.prevent="onDrop"
>
<input type="file" @change="onPick" />
<input type="file" :title="file?.name" @change="onPick" />
<template v-if="file">
<strong>{{ file.name }}</strong>
{{ formatSize(file.size) }}
</template>
<template v-else>Drop a file or click to choose</template>
<span v-if="folder" id="not-a-file" role="alert">{{ folder }} is a folder, only a single file can be sent</span>
</label>
<p v-if="sent">
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress>
{{ percent(sent) }} %
<div v-if="side === 'send' && phase" :data-phase="phase">
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
<div>
<progress id="send-progress" max="100" :value="barValue(sent)" aria-label="Sent"></progress>
</div>
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
<p v-else role="status">
<span id="send-status">{{ status!.text }}</span>
<span v-if="sent">{{ percent(sent) }}&nbsp;%</span>
</p>
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p>
</div>
<section>
<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
</button>
<template v-if="sendCode">
<label v-if="codeGone" for="send-code">Code, no longer valid:</label>
<label v-else for="send-code">Code, give this 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">
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
<button id="copy-send-code" type="button" data-copy :disabled="codeGone" @click="onCopy(sendCode)">
{{ copied === sendCode ? 'Copied' : 'Copy' }}
<button
id="copy-send-code"
type="button"
data-copy
:disabled="codeGone"
@click="onCopy(sendCode, 'send-code')"
>
{{ copyLabel(sendCode) }}
</button>
</div>
<p v-if="copyFailed(sendCode)" role="alert">
The browser blocked copying. The code is selected, copy it yourself.
</p>
</template>
</section>
@@ -325,9 +508,12 @@ function onReceive() {
<template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea>
<button id="copy-offer" type="button" data-copy @click="onCopy(offer)">
{{ copied === offer ? 'Copied' : 'Copy' }}
<button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
{{ copyLabel(offer) }}
</button>
<p v-if="copyFailed(offer)" role="alert">
The browser blocked copying. The offer is selected, copy it yourself.
</p>
<label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
@@ -348,11 +534,16 @@ function onReceive() {
</template>
<template v-else>The sender's file shows up here after the security check</template>
</div>
<p v-if="received">
<progress id="receive-progress" max="100" :value="percent(received)" aria-label="Received"></progress>
{{ percent(received) }} %
<div v-if="side === 'receive' && phase" :data-phase="phase">
<div>
<progress id="receive-progress" max="100" :value="barValue(received)" aria-label="Received"></progress>
</div>
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
<p v-else role="status">
<span id="receive-status">{{ status!.text }}</span>
<span v-if="received">{{ percent(received) }}&nbsp;%</span>
</p>
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p>
</div>
<section>
<h3>Tracker</h3>
@@ -369,7 +560,7 @@ function onReceive() {
<button
id="receive"
type="button"
:disabled="!settings.trackers.length || !receiveCode.trim()"
:disabled="!settings.trackers.length || !receiveCode.trim() || saltMissing"
@click="onReceive"
>
Receive
@@ -388,9 +579,12 @@ function onReceive() {
<template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea>
<button id="copy-answer" type="button" data-copy @click="onCopy(answer)">
{{ copied === answer ? 'Copied' : 'Copy' }}
<button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
{{ copyLabel(answer) }}
</button>
<p v-if="copyFailed(answer)" role="alert">
The browser blocked copying. The answer is selected, copy it yourself.
</p>
</template>
</section>
</details>
@@ -416,7 +610,8 @@ function onReceive() {
<label for="trackers">WebTorrent trackers for the code exchange, one URL per line:</label>
<textarea id="trackers" v-model="trackers.text" :aria-invalid="!!trackers.invalid.length"></textarea>
<p v-if="trackers.invalid.length">
Skipped, not a ws: or wss: URL without #: {{ trackers.invalid.join(', ') }}
Skipped, not a ws: or wss: URL without #{{ secure ? ', ws: only to this device on https' : '' }}:
{{ trackers.invalid.join(', ') }}
</p>
</section>
<button id="reset-servers" type="button" @click="onResetServers">Reset to defaults</button>
@@ -425,14 +620,15 @@ function onReceive() {
<details>
<summary>Log</summary>
<pre id="log">{{ log.join('\n') }}</pre>
<pre id="log">{{ dropped ? `${dropped} earlier lines dropped\n` : '' }}{{ log.join('\n') }}</pre>
</details>
</main>
<footer>
<a href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer">
<img src="/gitea.svg" alt="" width="20" height="20" />
<img :src="`${BASE}gitea.svg`" alt="" width="20" height="20" />
Source code
</a>
<span>Protocol {{ PROTOCOL }}</span>
</footer>
</template>
+1772
View File
File diff suppressed because it is too large. Load diff
+509 -262
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);
}
/* The columns of main, so the options line up with the Receive card, below the title on a phone */
header {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
align-items: center;
gap: var(--space-4);
padding-block: var(--space-6) var(--space-4);
}
header > div:first-child {
display: flex;
align-items: center;
gap: var(--space-3);
padding-block: var(--space-6);
}
header h1 {
font-size: var(--text-xl);
}
header label {
margin-left: auto;
/* The switches at the end, the own salt below while it's on */
#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 {
@@ -136,11 +155,18 @@ main {
padding-bottom: var(--space-8);
}
main > p,
main > aside,
main > details {
grid-column: 1 / -1;
}
/* Note while no STUN server would be used, quiet above the cards */
#no-stun {
font-size: var(--text-sm);
color: var(--color-text-muted);
}
/* Cards */
article,
@@ -186,6 +212,10 @@ section p {
color: var(--color-text-muted);
}
section p[role='alert'] {
color: var(--color-secondary-text);
}
header label {
color: var(--color-text);
}
@@ -208,6 +238,17 @@ textarea:focus {
border-color: var(--color-secondary);
}
/* Like a disabled button, the switch with its label */
input:not([role='switch']):disabled,
label:has([role='switch']:disabled) {
opacity: 0.4;
cursor: not-allowed;
}
label:has([role='switch']:disabled) [role='switch'] {
cursor: inherit;
}
/* Text fields show focus with their border, everything else, the switch too, with :focus-visible */
input:not([type='checkbox'], [type='file']):focus-visible,
textarea:focus-visible {
@@ -281,7 +322,7 @@ button:disabled {
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] {
padding: var(--space-1) var(--space-3);
@@ -370,54 +411,120 @@ label strong,
overflow-wrap: anywhere;
}
/* Progress and what went wrong, below the file on both sides */
article > p[role='alert'] {
font-size: var(--text-sm);
/* A dropped folder, refused */
#not-a-file {
color: var(--color-secondary-text);
overflow-wrap: anywhere;
}
article > p[role='alert']::first-letter {
text-transform: uppercase;
}
/* How the session is doing, below the file on its side. Until the transfer starts a pill passes
through the bar, blue, or pink while it tries again after a failure. Then the transfer's progress,
green once done, muted once stopped, pink for an error. The line below says what. */
[data-phase] {
--bar: var(--color-primary);
p:has(> progress) {
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);
font-size: var(--text-sm);
font-variant-numeric: tabular-nums;
color: var(--color-text-muted);
}
progress {
flex: 1;
/* The send session's file, above its bar once the user picked another one */
#send-file {
color: var(--color-text);
font-weight: 600;
overflow-wrap: anywhere;
}
/* A block, a flex container has no first letter. Flex items do, they are blocks. */
[data-phase] p[role='alert'] {
display: block;
color: var(--color-secondary-text);
}
[data-phase] p[role='alert']::first-letter,
[data-phase] [role='status'] > :first-child::first-letter {
text-transform: uppercase;
}
/* The track, the progress inside it fills it or, without a value, is the pill */
[data-phase] > div {
height: 0.5rem;
appearance: none;
border: none;
border-radius: 999px;
background: var(--color-input);
overflow: hidden;
}
progress {
display: block;
width: 100%;
height: 100%;
appearance: none;
border: none;
background: none;
}
progress::-webkit-progress-bar {
background: var(--color-input);
background: none;
}
progress::-webkit-progress-value {
background: var(--color-primary);
background: var(--bar);
}
progress::-moz-progress-bar {
background: var(--color-primary);
background: var(--bar);
}
progress[value='100']::-webkit-progress-value {
background: var(--color-success);
progress:indeterminate {
width: 25%;
border-radius: 999px;
background: var(--bar);
animation: pass 2584ms linear infinite;
}
progress[value='100']::-moz-progress-bar {
background: var(--color-success);
progress:indeterminate::-moz-progress-bar {
background: none;
}
/* Its own width is a quarter of the track's: from just before it to just past it */
@keyframes pass {
from {
translate: -100%;
}
to {
translate: 400%;
}
}
@media (prefers-reduced-motion: reduce) {
progress:indeterminate {
translate: 150%;
animation: none;
}
}
/* Switch, like Pico's role="switch" */
@@ -515,14 +622,20 @@ output {
/* Source link, quiet below everything */
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);
font-size: var(--text-sm);
color: var(--color-text-muted);
}
footer a {
display: inline-flex;
align-items: center;
gap: var(--space-2);
font-size: var(--text-sm);
color: var(--color-text-muted);
text-decoration: none;
transition: color var(--transition);
+1 -1
View File
@@ -16,5 +16,5 @@
"allowJs": 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 { defineConfig } from 'vite';
const DEV_STYLE_SRC = "style-src 'self'";
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'] },
});