Compare commits
15
Commits
d92c4b50cf
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c47047ddd | ||
|
|
1b2696b6b4 | ||
|
|
ac4d496a48 | ||
|
|
44a8a72261 | ||
|
|
870d55b44f | ||
|
|
af0a8c9fee | ||
|
|
7f4811485a | ||
|
|
b102e55495 | ||
|
|
ae1e3bef9b | ||
|
|
ae871a2647 | ||
|
|
8f82700736 | ||
|
|
f53d39ae69 | ||
|
|
aa61efcc10 | ||
|
|
2e47b55901 | ||
|
|
e3a2b348d6 |
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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"]
|
||||
@@ -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]
|
||||
|
||||
+174
-15
@@ -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
@@ -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
@@ -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" } } } }
|
||||
]
|
||||
}
|
||||
+511
-787
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
// src/core.test.ts is Vitest's, see vite.config.ts. Loaded by Playwright, its vi.mock fails the whole run.
|
||||
export default defineConfig({ testIgnore: 'src/**' });
|
||||
Generated
+644
-279
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
minimumReleaseAgeExclude:
|
||||
- ws@8.23.0
|
||||
+36
-11
@@ -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' } }),
|
||||
|
||||
+194
-61
@@ -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,36 +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
|
||||
@@ -55,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) {
|
||||
@@ -69,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 });
|
||||
@@ -89,10 +95,10 @@ 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('');
|
||||
@@ -100,7 +106,12 @@ 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 }>();
|
||||
@@ -109,7 +120,12 @@ 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;
|
||||
@@ -126,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>();
|
||||
@@ -186,12 +206,15 @@ 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);
|
||||
|
||||
// what goes into the log, so the sessions in it can be told apart.
|
||||
function begin(on: 'send' | 'receive', what: string) {
|
||||
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;
|
||||
@@ -202,7 +225,6 @@ function begin(on: 'send' | 'receive', what: string) {
|
||||
received.value = undefined;
|
||||
sendCode.value = '';
|
||||
sendExpired.value = false;
|
||||
clearTimeout(sendTimer);
|
||||
offer.value = '';
|
||||
answer.value = '';
|
||||
acceptAnswer = undefined;
|
||||
@@ -220,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) {
|
||||
@@ -238,7 +280,7 @@ 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() {
|
||||
@@ -263,13 +305,12 @@ async function onCreateAnswer() {
|
||||
}
|
||||
|
||||
async function onShare() {
|
||||
const signal = begin('send', `share ${file.value!.name} via tracker`);
|
||||
const signal = begin('send', `share ${file.value!.name} via tracker`, true);
|
||||
shared.value = file.value;
|
||||
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 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
|
||||
@@ -277,20 +318,106 @@ async function onShare() {
|
||||
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
||||
|
||||
function onReceive() {
|
||||
const signal = begin('receive', 'receive via tracker');
|
||||
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" />
|
||||
<h1>HellCon</h1>
|
||||
<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>
|
||||
<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>
|
||||
@@ -325,12 +452,13 @@ 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>
|
||||
<div v-if="side === 'send' && phase" :data-phase="phase">
|
||||
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
|
||||
@@ -340,18 +468,21 @@ function onReceive() {
|
||||
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="send-status">{{ status!.text }}</span>
|
||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||
</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
|
||||
@@ -410,7 +541,7 @@ function onReceive() {
|
||||
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="receive-status">{{ status!.text }}</span>
|
||||
<span v-if="received">{{ percent(received) }} %</span>
|
||||
<span v-if="received">{{ percent(received) }} %</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -429,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
|
||||
@@ -479,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>
|
||||
@@ -488,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
File diff suppressed because it is too large.
Load diff
+385
-295
File diff suppressed because it is too large.
Load diff
+165
@@ -0,0 +1,165 @@
|
||||
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
|
||||
// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests.
|
||||
// This is the page's half of it. The receiver in src/core.ts only sees startDownload, so it can be
|
||||
// tested against a download in memory, and another way of saving could take this one's place.
|
||||
|
||||
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
|
||||
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
|
||||
// Without either for longer, public/sw.js takes the page for gone and fails the download, see SILENCE.
|
||||
const KEEPALIVE = 10_000;
|
||||
// The browser may read all of a small file, e.g. an empty one, before it hands the navigation to its
|
||||
// download manager. Its frame removed before that, the download never shows up, though the worker
|
||||
// reported it finished. No event tells when the browser took it, 1 s was always enough in the tests.
|
||||
const DOWNLOAD_GRACE = 1000;
|
||||
// Of the messages between this page and public/sw.js, which has it too. A page can talk to a worker
|
||||
// of another version: a new page while another tab's download holds the old worker, or an old page
|
||||
// once an update took over. The worker refuses a version it doesn't speak with outdated, each change
|
||||
// to the messages takes a new one, in both files.
|
||||
const VERSION = 1;
|
||||
|
||||
const downloads = registerDownloads();
|
||||
// Reported once the user receives, not as an uncaught error on every visit, e.g. in a private window.
|
||||
downloads.catch(() => {});
|
||||
|
||||
// Only the first visit has to wait here, updates are picked up per transfer by holdWorker.
|
||||
async function registerDownloads() {
|
||||
const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' });
|
||||
const pending = registration.installing ?? registration.waiting;
|
||||
if (!registration.active && pending) {
|
||||
await new Promise((resolve) =>
|
||||
pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)),
|
||||
);
|
||||
}
|
||||
if (!registration.active) throw new Error('service worker did not activate');
|
||||
}
|
||||
|
||||
// Awaited before receiving starts, so a browser without service workers fails before connecting.
|
||||
export function downloadsReady() {
|
||||
return downloads.catch((error) => {
|
||||
throw new Error(`downloads unavailable in this browser: ${error instanceof Error ? error.message : error}`);
|
||||
});
|
||||
}
|
||||
|
||||
// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling
|
||||
// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that
|
||||
// worker in the middle of the download.
|
||||
async function holdWorker() {
|
||||
await downloads;
|
||||
const frame = document.createElement('iframe');
|
||||
frame.hidden = true;
|
||||
frame.src = 'download/';
|
||||
document.body.append(frame);
|
||||
await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true }));
|
||||
const worker = frame.contentWindow!.navigator.serviceWorker.controller;
|
||||
if (!worker) {
|
||||
frame.remove();
|
||||
throw new Error('service worker did not take over');
|
||||
}
|
||||
return { frame, worker };
|
||||
}
|
||||
|
||||
// What the download manager does with a download, see startDownload. Each one but read ends it, only
|
||||
// the first of them comes, and none after fail.
|
||||
export type DownloadEvents = {
|
||||
// How many bytes it has read so far, every MiB.
|
||||
read: (bytes: number) => void;
|
||||
// It has read the last byte.
|
||||
finished: () => void;
|
||||
// The user cancelled it.
|
||||
cancelled: () => void;
|
||||
// Something else than fail ended it: no worker, the worker refused it or stopped.
|
||||
failed: (reason: string) => void;
|
||||
};
|
||||
|
||||
// The receiver writes every chunk, then ends it once all arrived, or fails it.
|
||||
export type Download = {
|
||||
write: (chunk: ArrayBuffer) => void;
|
||||
end: () => void;
|
||||
fail: (reason: string) => void;
|
||||
};
|
||||
|
||||
// Starts saving file in the browser's download manager. Writes can come before the worker is held,
|
||||
// they wait for it in order. Once it ended, its frames go and the worker is free for an update.
|
||||
export function startDownload(file: { name: string; size: number }, events: DownloadEvents): Download {
|
||||
const id = crypto.randomUUID();
|
||||
const frames: HTMLIFrameElement[] = [];
|
||||
let keepalive: ReturnType<typeof setInterval> | undefined;
|
||||
// By whatever came first: the worker's answer, its stop or fail.
|
||||
let ended = false;
|
||||
// Chaining every post on this keeps them in order.
|
||||
const worker: Promise<ServiceWorker | undefined> = holdWorker().then(
|
||||
({ frame, worker }) => {
|
||||
frames.push(frame);
|
||||
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
|
||||
// An update takes over only once the frames are released, then this changes nothing. Else
|
||||
// something stopped it in the middle, e.g. clearing the site data, it can't answer then.
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state !== 'redundant') return;
|
||||
if (!ended) events.failed('service worker stopped');
|
||||
ended = true;
|
||||
release();
|
||||
});
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.onmessage = ({ data }) => {
|
||||
if (typeof data === 'number') return ended || events.read(data);
|
||||
if (data === 'ready') {
|
||||
if (ended) return;
|
||||
// A navigation, not fetch(): only navigations hand the response to the download manager.
|
||||
const download = document.createElement('iframe');
|
||||
download.hidden = true;
|
||||
download.src = `download/${id}`;
|
||||
document.body.append(download);
|
||||
frames.push(download);
|
||||
return;
|
||||
}
|
||||
if (!ended) {
|
||||
if (data === 'finished') events.finished();
|
||||
if (data === 'cancelled') events.cancelled();
|
||||
if (data === 'failed') events.failed('the service worker refused it');
|
||||
if (data === 'silent') events.failed('the service worker heard nothing from this page for too long');
|
||||
if (data === 'outdated') {
|
||||
events.failed('this page and its service worker are different versions, reload once no tab receives');
|
||||
}
|
||||
}
|
||||
ended = true;
|
||||
release(data === 'finished');
|
||||
};
|
||||
worker.postMessage({ id, version: VERSION, ...file }, [port2]);
|
||||
return worker;
|
||||
},
|
||||
(error) => {
|
||||
if (!ended) events.failed(String(error));
|
||||
ended = true;
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
const post = (message: object, transfer: Transferable[] = []) =>
|
||||
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
|
||||
|
||||
// Removed earlier, Chromium keeps a failed download running instead of failing it. A finished
|
||||
// download keeps its own frame for DOWNLOAD_GRACE, that one doesn't hold the worker. Only the first
|
||||
// call counts, a later one would take that frame right away.
|
||||
let released = false;
|
||||
function release(finished = false) {
|
||||
if (released) return;
|
||||
released = true;
|
||||
clearInterval(keepalive);
|
||||
const [hold, download] = frames;
|
||||
hold?.remove();
|
||||
if (finished) setTimeout(() => download?.remove(), DOWNLOAD_GRACE);
|
||||
else download?.remove();
|
||||
}
|
||||
|
||||
return {
|
||||
write: (chunk) => post({ chunk }, [chunk]),
|
||||
end: () => post({ done: true }),
|
||||
// The worker answers with failed, only then the frames go. A worker that restarted lost the
|
||||
// download, and its stream with it, it never answers: they go after KEEPALIVE anyway.
|
||||
fail: (reason) => {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
post({ error: reason });
|
||||
void worker.then(() => setTimeout(release, KEEPALIVE));
|
||||
},
|
||||
};
|
||||
}
|
||||
+47
-5
@@ -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 {
|
||||
@@ -219,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 {
|
||||
@@ -292,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);
|
||||
@@ -381,6 +411,12 @@ label strong,
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* A dropped folder, refused */
|
||||
#not-a-file {
|
||||
color: var(--color-secondary-text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* How the session is doing, below the file on its side. Until the transfer starts a pill passes
|
||||
through the bar, blue, or pink while it tries again after a failure. Then the transfer's progress,
|
||||
green once done, muted once stopped, pink for an error. The line below says what. */
|
||||
@@ -586,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
@@ -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
@@ -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'] },
|
||||
});
|
||||
Reference in new issue
Block a user