Compare commits

..
3 Commits
Author SHA1 Message Date
SchluffeandClaude Opus 5.5 8b36e51b56 Require Node.js 26.12.1, it fixes CVE-2026-111497
26.11.1 has the out-of-bounds write in its Brotli decoder. The tracker decompresses nothing, but
the image and development machines should still not run an affected version.

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

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

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

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

No files matched your search

+4
View File
@@ -99,6 +99,10 @@ Then serve the `dist/` folder, with these requirements:
- **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below - **`sw.js` next to `index.html`.** It streams the downloads. Requests to the `download/` path below
HellCon must reach it unchanged, so don't rewrite them to `index.html`. HellCon must reach it unchanged, so don't rewrite them to `index.html`.
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.
## Known limitations ## Known limitations
- **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure, - **Firefox:** if the sender disappears in the middle of a transfer, HellCon reports the failure,
+16 -50
View File
@@ -1,60 +1,21 @@
# TODO # TODO
## Server at pagequit.net, to decide ## Server at pagequit.net
### Review of the coturn setup (STUN only, host network) `backend/` holds both servers, tested locally: a real transfer Chromium to Firefox through only them,
and the tracker's limits one by one. Left to do on the server:
- Good as it is: `stun-only`, `no-tcp`, `no-tls`, `no-software-attribute`, CPU, memory and process - Replace the running coturn with `backend/compose.yaml`. coturn 4.18 has the admin CLI, DTLS, the
limits with swap off, and log rotation. Host networking is right for STUN, so Docker's NAT can't RFC 3489 MAPPED-ADDRESS and the software attribute off by default, the `--no-` options for them are
change the source address the clients get back. Listening on IPv4 only matches DNS: gone. Set `ORIGINS` in `backend/.env`, and `CADDY_NETWORK` if Caddy's network isn't `caddy`.
`stun.pagequit.net` has an A record and no AAAA. - Add `tracker.pagequit.net` to Caddy and DNS (A record, like `stun.pagequit.net`).
- `coturn/coturn:latest` is the only unpinned version. Pin `coturn/coturn:4.18.0` (2026-09-08). - Check that the logs hold no client addresses: transfer once, then
- Add `no-cli`. On the host network, coturn's admin CLI would otherwise listen on the host's `docker compose logs | grep <your IP>` should stay empty.
127.0.0.1:5766 if it's enabled. - Then put `wss://tracker.pagequit.net` first in `DEFAULT_TRACKERS` and keep the public trackers as
- Add `no-stun-backward-compatibility`. Browsers only use the current STUN protocol, so the old fallbacks.
RFC 3489 requests and their extra MAPPED-ADDRESS can go, which also makes responses smaller for
reflection attacks.
- Check that the logs hold no client addresses: send a STUN request, then
`docker compose logs coturn | grep <your IP>`. Logging each request is off by default and
`log-binding` turns it on, so it should stay empty. Otherwise up to 20 MB of addresses stay around.
- Missing compared to the tracker draft: `cap_drop: [ALL]` and
`security_opt: [no-new-privileges:true]`. `read_only: true` is worth trying too, but coturn may
need a writable `/var/run` or `/var/lib/coturn` (`tmpfs`).
- coturn doesn't rate limit STUN requests. A response is about as big as the request, so it's a weak - coturn doesn't rate limit STUN requests. A response is about as big as the request, so it's a weak
amplifier. If it gets abused, an nftables `limit` on the UDP port would help. amplifier. If it gets abused, an nftables `limit` on the UDP port would help.
### Compared to the plan so far
- Caddy and coturn don't share a Docker network, coturn runs on the host network. The tracker joins
Caddy's network (its name is in Caddy's compose file), coturn stays as it is.
- Copy coturn's limits to the tracker, with smaller values: `cpus`, `mem_limit` equal to
`memswap_limit`, `pids_limit`, and the same `json-file` log rotation.
- Pin every version, coturn and the tracker alike.
### Decisions
1. **Which tracker.** Stock `bittorrent-tracker@11.2.3` behind Caddy works: tested locally with a
real transfer from Chromium to Firefox, and it logs nothing with `--quiet`. A review found it too
open to run unchanged:
- it forwards any data and accepts messages up to 100 MiB
- `scrape` lists all swarms even with `--no-stats`
- it has no rate, byte or connection limits
- it accepts any Origin
The recommendation is an own tracker for the WebTorrent subset HellCon uses, so the client stays
unchanged and the public trackers keep working as fallbacks. Node 26 and `ws`, one file of about
250 lines, enforcing:
- an Origin allowlist and messages of at most 16 KiB
- only `announce`, one offer per announce, and answers only to offers it delivered, once
- per connection: a message rate, about 64 KiB of forwarded data, and at most 7 minutes
- connections per IP (from `X-Forwarded-For`), total connections and peers per swarm capped
- empty swarms removed, nothing logged
Then decide where it lives: `tracker/` in this repo (new files, every fork gets it) or a separate
repository.
2. **After deploying:** put `wss://tracker.pagequit.net` first in `DEFAULT_TRACKERS` and keep the
public trackers as fallbacks.
## Ideas ## Ideas
- Resume interrupted transfers: the receiver already reports how much the download manager has - Resume interrupted transfers: the receiver already reports how much the download manager has
@@ -77,3 +38,8 @@
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite), - `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite),
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again. happens again.
- `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 5
full runs since, one of them with a cold Vite cache. The suite without the new tests passed 4
times. Not reproduced, cause unknown.
+6
View File
@@ -0,0 +1,6 @@
FROM node:26.12.1-alpine3.23
WORKDIR /app
RUN npm install --no-save --omit=dev ws@8.22.0
COPY tracker.mjs .
USER node
CMD ["node", "--max-old-space-size=48", "tracker.mjs"]
+71
View File
@@ -0,0 +1,71 @@
# HellCon's own servers: a tracker behind Caddy and a STUN server. Neither is needed, the client works
# with any WebTorrent tracker and STUN server. Set ORIGINS in .env next to this file, e.g.
# ORIGINS=https://hellcon.example.org, then `docker compose up -d --build`. Caddy, in its own compose
# project, proxies to the tracker over its network (CADDY_NETWORK, "caddy" unless set):
#
# tracker.example.org {
# reverse_proxy hellcon-tracker:8000
# }
name: hellcon
x-logging: &logging
driver: json-file
options: { max-size: 10m, max-file: '2' }
services:
tracker:
build: .
environment:
ORIGINS: ${ORIGINS:?set ORIGINS in .env to where HellCon is served from}
networks:
caddy:
aliases: [hellcon-tracker]
init: true
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
cpus: 0.5
mem_limit: 96m
memswap_limit: 96m
pids_limit: 32
logging: *logging
restart: unless-stopped
# On the host network, so Docker's NAT can't change the source address clients get back. UDP 3478
# on IPv4 only, stun.example.org needs an A record and no AAAA.
coturn:
image: coturn/coturn:4.18.0
network_mode: host
# Off by default since 4.18, their --no- options are gone: DTLS, the admin CLI, the software
# attribute, the RFC 3489 MAPPED-ADDRESS and logging each binding request. The image has no config
# file, -n would only fail with "Unknown argument".
command:
- --log-file=stdout
- --listening-ip=0.0.0.0
- --listening-port=3478
- --stun-only
- --no-tcp
- --no-tls
# One per CPU core otherwise, more than cpus allows.
- --relay-threads=1
# The pid file lands in /var/tmp, coturn can't write /var/run. The image declares /var/lib/coturn
# a volume, the tmpfs keeps an anonymous one from piling up.
tmpfs: [/var/lib/coturn, /var/tmp]
read_only: true
cap_drop: [ALL]
# turnserver has it as file capability, without it the kernel refuses to run it. 3478 doesn't need
# it, no-new-privileges keeps it from being granted.
cap_add: [NET_BIND_SERVICE]
security_opt: [no-new-privileges:true]
cpus: 1
mem_limit: 128m
memswap_limit: 128m
pids_limit: 64
logging: *logging
restart: unless-stopped
networks:
caddy:
external: true
name: ${CADDY_NETWORK:-caddy}
+190
View File
@@ -0,0 +1,190 @@
// 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.
import { createServer } from 'node:http';
import { WebSocketServer } from 'ws';
// Read on import, 0 picks a free one, see server.address().
const PORT = Number(process.env.PORT ?? 8000);
// Where HellCon is served from, separated by commas or spaces. Anything else is refused. Read on every
// connection, so test files sharing one process can each allow their own.
const allowed = (origin) =>
(process.env.ORIGINS ?? '')
.split(/[\s,]+/)
.filter(Boolean)
.includes(origin);
// Seconds. Peers last as long as their connection, announcing again only resends a receiver's offer,
// e.g. to a sender that was busy with another receiver.
const INTERVAL = 60;
// A sealed SDP is a few KiB.
const MAX_MESSAGE = 16 * 1024;
// Per connection: messages within RATE_WINDOW, bytes of SDP it gets forwarded and its lifetime. HellCon
// gives up a share or a search after 6 minutes.
const MAX_MESSAGES = 10;
const RATE_WINDOW = 10_000;
const MAX_FORWARDED = 64 * 1024;
// 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;
const MAX_AGE = 7 * 60_000;
const MAX_CONNECTIONS = 1024;
const MAX_PER_IP = 16;
// A share has one sender, receivers keep one connection per tracker.
const MAX_SWARM = 8;
// Offers a sender got and may still answer, the oldest go first.
const MAX_PENDING = 32;
// info_hash → peer_id → peer.
const swarms = new Map();
const perIp = new Map();
let connections = 0;
// 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.
function clientIp(req) {
return req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
}
function refuse(socket, status) {
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
}
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
// wait for its close frame.
function fits(peer, bytes) {
if (peer.ws.bufferedAmount + bytes <= MAX_QUEUED) return true;
peer.ws.terminate();
}
function send(peer, message) {
const data = JSON.stringify(message);
if (fits(peer, Buffer.byteLength(data))) peer.ws.send(data);
}
// HellCon shows the reason, the connection closes.
function reject(peer, reason) {
send(peer, { 'failure reason': reason });
peer.ws.close();
}
function forward(from, to, message, sdp) {
from.forwarded += sdp.length;
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
send(to, message);
}
function announce(peer, msg) {
const { info_hash: hash, peer_id: id } = msg;
if (msg.action !== 'announce' || !isId(hash) || !isId(id)) return reject(peer, 'invalid announce');
if (!peer.id) {
const swarm = swarms.get(hash) ?? new Map();
if (swarm.has(id)) return reject(peer, 'peer_id taken');
if (swarm.size >= MAX_SWARM) return reject(peer, 'swarm full');
swarms.set(hash, swarm.set(id, peer));
peer.id = id;
peer.hash = hash;
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
if (msg.event === 'stopped') return peer.ws.close();
peer.seeder = msg.left === 0;
const swarm = swarms.get(hash);
if (msg.offers !== undefined) {
const [offer, ...more] = Array.isArray(msg.offers) ? msg.offers : [];
if (more.length || (offer && (!isId(offer.offer_id) || !isSdp(offer.offer, 'offer')))) {
return reject(peer, 'invalid offer');
}
const senders = [...swarm.values()].filter((other) => other.seeder && other !== peer);
const sender = senders[Math.floor(Math.random() * senders.length)];
if (offer && sender) {
sender.pending.delete(offer.offer_id);
sender.pending.set(offer.offer_id, peer);
if (sender.pending.size > MAX_PENDING) sender.pending.delete(sender.pending.keys().next().value);
const { sdp } = offer.offer;
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: offer.offer_id };
forward(peer, sender, { ...message, offer: { type: 'offer', sdp } }, sdp);
}
}
if (msg.answer !== undefined) {
if (!isId(msg.to_peer_id) || !isId(msg.offer_id) || !isSdp(msg.answer, 'answer')) {
return reject(peer, 'invalid answer');
}
const receiver = peer.pending.get(msg.offer_id);
// An offer it never got, answered already or whose receiver left: dropped, a stray answer doesn't
// cost the share.
if (receiver?.id === msg.to_peer_id) {
peer.pending.delete(msg.offer_id);
const { sdp } = msg.answer;
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: msg.offer_id };
forward(peer, receiver, { ...message, answer: { type: 'answer', sdp } }, sdp);
}
}
if (peer.ws.readyState === peer.ws.OPEN) {
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash });
}
}
function open(ws) {
const peer = { ws, id: undefined, hash: undefined, seeder: false, pending: new Map(), forwarded: 0, messages: 0 };
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
const age = setTimeout(() => ws.close(), MAX_AGE);
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
ws.on('error', () => {});
// Pings and pongs count as messages. ws would answer every ping on its own, past the limits.
const counted = () => ++peer.messages <= MAX_MESSAGES || reject(peer, 'too many messages');
ws.on('ping', (data) => counted() && fits(peer, data.length) && ws.pong(data));
ws.on('pong', counted);
ws.on('message', (data, binary) => {
if (!counted()) return;
let msg;
try {
msg = binary ? undefined : JSON.parse(data);
} catch {}
if (!msg || typeof msg !== 'object') return reject(peer, 'invalid message');
announce(peer, msg);
});
ws.on('close', () => {
clearInterval(rate);
clearTimeout(age);
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
peer.pending.clear();
const swarm = swarms.get(peer.hash);
if (swarm?.get(peer.id) !== peer) return;
swarm.delete(peer.id);
if (!swarm.size) swarms.delete(peer.hash);
// Its offers go only to peers of its swarm.
for (const other of swarm.values()) {
for (const [offerId, receiver] of other.pending) if (receiver === peer) other.pending.delete(offerId);
}
});
}
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
export const server = createServer((_, res) => res.writeHead(404).end());
server.on('upgrade', (req, socket, head) => {
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
// client resetting a refused connection would end the process.
socket.on('error', () => {});
const ip = clientIp(req);
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
if ((perIp.get(ip) ?? 0) >= MAX_PER_IP) 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);
socket.once('close', () => {
connections--;
const left = perIp.get(ip) - 1;
if (left) perIp.set(ip, left);
else perIp.delete(ip);
});
wss.handleUpgrade(req, socket, head, open);
});
server.listen(PORT);
+351
View File
@@ -0,0 +1,351 @@
// The tracker on its own, without browsers: what it forwards, what it refuses and what it keeps.
// tracker.mjs runs in the worker on a free port. e2e.spec.ts sends a real file through it.
import { once } from 'node:events';
import { connect as connectTcp } from 'node:net';
import { queryObjects } from 'node:v8';
import { expect, test } from '@playwright/test';
import { WebSocket as ServerSocket } from 'ws';
const ORIGIN = 'https://hellcon.test';
let url;
// Every connection a test opened, closed after it.
let clients = [];
// Each test connects from its own address, the tracker takes it from X-Forwarded-For. Otherwise
// connections of the previous test, still closing, would count against the per-IP limit.
let ip;
let tests = 0;
test.beforeAll(async () => {
process.env.PORT = '0';
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`;
const { server } = await import('./tracker.mjs');
if (!server.listening) await once(server, 'listening');
url = `ws://127.0.0.1:${server.address().port}`;
});
test.beforeEach(() => {
ip = `198.51.100.${++tests}`;
});
test.afterEach(async () => {
for (const client of clients) client.ws.close();
await Promise.all(clients.map((client) => client.closed));
clients = [];
});
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 } = {}) {
return new Promise((resolve) => {
const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': ip } });
const client = { ws, messages: [], closed: once(ws, 'close').then(([event]) => event.code) };
ws.addEventListener('message', ({ data }) => client.messages.push(JSON.parse(data)));
ws.addEventListener('open', () => {
clients.push(client);
resolve(client);
});
ws.addEventListener('error', () => resolve(undefined));
});
}
// Takes the first message that matches, once one came. open queues each before this sees it.
async function take(client, match) {
while (!client.messages.some(match)) await once(client.ws, 'message');
return client.messages.splice(client.messages.findIndex(match), 1)[0];
}
// Announces and waits for the tracker's reply. Whatever it forwarded to this peer before is in
// messages by then, so a test can tell that something was not forwarded.
async function announce(client, fields) {
client.ws.send(JSON.stringify({ action: 'announce', numwant: 0, uploaded: 0, downloaded: 0, ...fields }));
return take(client, (msg) => 'interval' in msg);
}
// Sends raw and expects the tracker to reject it with reason, then close.
async function rejected(client, data, reason) {
client.ws.send(typeof data === 'string' || data instanceof Uint8Array ? data : JSON.stringify(data));
expect((await take(client, (msg) => 'failure reason' in msg))['failure reason']).toBe(reason);
await client.closed;
}
// A swarm with a sender, a receiver and their peer ids.
async function swarm() {
const hash = id();
const sender = { ...(await open()), id: id() };
const receiver = { ...(await open()), id: id() };
await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0, event: 'started' });
await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, event: 'started' });
return { hash, sender, receiver };
}
// The receiver's offer, as the sender got it.
async function offer({ hash, sender, receiver }, offerId = id()) {
await announce(receiver, {
info_hash: hash,
peer_id: receiver.id,
left: 1,
offers: [{ offer_id: offerId, offer: sdp('offer') }],
});
return take(sender, (msg) => msg.offer);
}
const answer = ({ hash, sender }, to, offerId, text = 'answer') =>
announce(sender, {
info_hash: hash,
peer_id: sender.id,
left: 0,
to_peer_id: to,
offer_id: offerId,
answer: sdp('answer', text),
});
test('refuses connections from other origins', async () => {
expect(await open({ origin: 'https://evil.test' })).toBeUndefined();
expect(await open({ origin: '' })).toBeUndefined();
});
test('acknowledges an announce with the interval only', async () => {
const client = await open();
const hash = id();
expect(await announce(client, { info_hash: hash, peer_id: id(), left: 0 })).toEqual({
action: 'announce',
interval: 60,
info_hash: hash,
});
});
test('forwards an offer to the sender only, rebuilt from its checked fields', async () => {
const peers = await swarm();
const other = { ...(await open()), id: id() };
await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 });
const offerId = id();
await announce(peers.receiver, {
info_hash: peers.hash,
peer_id: peers.receiver.id,
left: 1,
offers: [{ offer_id: offerId, offer: { ...sdp('offer'), extra: 1 } }],
extra: 1,
});
expect(await take(peers.sender, (msg) => msg.offer)).toEqual({
action: 'announce',
info_hash: peers.hash,
peer_id: peers.receiver.id,
offer_id: offerId,
offer: sdp('offer'),
});
await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 });
expect(other.messages).toEqual([]);
});
test('forwards an answer once, only to whoever sent the offer', async () => {
const peers = await swarm();
const { offer_id } = await offer(peers);
// Unknown offer, wrong receiver: dropped, and the sender stays connected.
await answer(peers, peers.receiver.id, id());
await answer(peers, id(), offer_id);
await answer(peers, peers.receiver.id, offer_id, 'sealed');
expect(await take(peers.receiver, (msg) => msg.answer)).toEqual({
action: 'announce',
info_hash: peers.hash,
peer_id: peers.sender.id,
offer_id,
answer: sdp('answer', 'sealed'),
});
await answer(peers, peers.receiver.id, offer_id, 'again');
await announce(peers.receiver, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
expect(peers.receiver.messages).toEqual([]);
});
test('drops an answer to a receiver that left', async () => {
const peers = await swarm();
const { offer_id } = await offer(peers);
peers.receiver.ws.close();
await peers.receiver.closed;
// Its peer_id comes back with a new connection, the old offer stays gone.
const again = await open();
await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
await answer(peers, peers.receiver.id, offer_id);
await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 });
expect(again.messages).toEqual([]);
});
for (const [name, data, reason] of [
['text that is no JSON', 'nope', 'invalid message'],
['binary messages', new Uint8Array([1]), 'invalid message'],
['scrape', { action: 'scrape', info_hash: id() }, 'invalid announce'],
['a short info_hash', { action: 'announce', info_hash: 'x', peer_id: id() }, 'invalid announce'],
[
'two offers in one announce',
{
action: 'announce',
info_hash: id(),
peer_id: id(),
left: 1,
offers: [1, 2].map(() => ({ offer_id: id(), offer: sdp('offer') })),
},
'invalid offer',
],
[
'an offer that is an answer',
{ action: 'announce', info_hash: id(), peer_id: id(), left: 1, offers: [{ offer_id: id(), offer: sdp('answer') }] },
'invalid offer',
],
[
'an answer without to_peer_id',
{ action: 'announce', info_hash: id(), peer_id: id(), left: 0, offer_id: id(), answer: sdp('answer') },
'invalid answer',
],
]) {
test(`rejects ${name}`, async () => {
await rejected(await open(), data, reason);
});
}
test('rejects a taken peer_id and a second swarm', async () => {
const { hash, sender } = await swarm();
await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: sender.id, left: 0 }, 'peer_id taken');
await rejected(
sender,
{ action: 'announce', info_hash: id(), peer_id: sender.id, left: 0 },
'one swarm per connection',
);
});
test('frees a peer_id once its connection closed', async () => {
const { hash, sender } = await swarm();
sender.ws.close();
await sender.closed;
expect(await announce(await open(), { info_hash: hash, peer_id: sender.id, left: 0 })).toBeTruthy();
});
test('closes on a message beyond 16 KiB', async () => {
const client = await open();
client.ws.send('x'.repeat(16 * 1024 + 1));
expect(await client.closed).toBe(1009);
});
test('limits the message rate', async () => {
const client = await open();
const fields = { action: 'announce', info_hash: id(), peer_id: id(), left: 0 };
for (let i = 0; i < 10; i++) client.ws.send(JSON.stringify(fields));
await rejected(client, fields, 'too many messages');
});
test('limits pings like messages, also from a peer that stops reading', async () => {
// ws's client, browsers send no pings. ws used to answer every one, its pongs piled up in the tracker.
const client = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
const closed = once(client, 'close');
const reasons = [];
client.on('message', (data) => reasons.push(JSON.parse(data)['failure reason']));
await once(client, 'open');
client.ping('x');
expect(String((await once(client, 'pong'))[0])).toBe('x');
client._socket.pause();
for (let i = 0; i < 1000; i++) client.ping('x'.repeat(125));
client._socket.resume();
await closed;
expect(reasons).toEqual(['too many messages']);
});
test('limits the signaling forwarded per connection', async () => {
const { hash, receiver } = await swarm();
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
for (let i = 0; i < 4; i++)
await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] });
await rejected(
receiver,
{ action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] },
'too much signaling',
);
});
test('drops a peer that stops reading', async () => {
const hash = id();
const slowId = id();
// ws's client, its socket can stop reading. What the tracker sends then piles up in the kernel's
// buffers first, then in the tracker.
const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } });
const closed = once(slow, 'close').then(([code]) => code);
await once(slow, 'open');
slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0, numwant: 0 }));
await once(slow, 'message');
slow._socket.pause();
const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) });
// Receivers that reconnect over and over, each within its own limit. The slow sender's peer_id is
// free again once the tracker dropped it.
let dropped = false;
for (let i = 0; i < 1000 && !dropped; i++) {
const receiver = await open();
const fields = { info_hash: hash, peer_id: id(), left: 1 };
for (let j = 0; j < 4; j++) await announce(receiver, { ...fields, offers: [big()] });
receiver.ws.close();
await receiver.closed;
const probe = await open();
probe.ws.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0 }));
dropped = 'interval' in (await take(probe, (msg) => 'interval' in msg || 'failure reason' in msg));
if (!dropped) await probe.closed;
}
expect(dropped).toBe(true);
slow._socket.resume();
// Terminated, without a close frame.
expect(await closed).toBe(1006);
});
test('limits a swarm to 8 peers', async () => {
const hash = id();
for (let i = 0; i < 8; i++) await announce(await open(), { info_hash: hash, peer_id: id(), left: 1 });
await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: id(), left: 1 }, 'swarm full');
});
test('limits connections per IP to 16', async () => {
for (let i = 0; i < 16; i++) expect(await open()).toBeTruthy();
expect(await open()).toBeUndefined();
ip = '198.51.100.250';
expect(await open()).toBeTruthy();
});
test('survives clients resetting refused connections', async () => {
for (let i = 0; i < 100; i++) {
const socket = connectTcp(new URL(url).port, '127.0.0.1');
await once(socket, 'connect');
socket.write(
'GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\n' +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: https://evil.test\r\n\r\n',
);
socket.resetAndDestroy();
}
// An unhandled error would have ended this worker.
expect(await open()).toBeTruthy();
});
test('keeps no peer that left', async () => {
// The root stays and gets the first offer, then every peer gets the next one's offer and leaves.
// Held offers used to keep all of them alive, through the root.
const hash = id();
const root = { ...(await open()), id: id() };
await announce(root, { info_hash: hash, peer_id: root.id, left: 0 });
let holder = root;
for (let i = 0; i < 50; i++) {
const peer = { ...(await open()), id: id() };
await announce(peer, {
info_hash: hash,
peer_id: peer.id,
left: 1,
offers: [{ offer_id: id(), offer: sdp('offer') }],
});
await take(holder, (msg) => msg.offer);
// The only sender for the next offer.
await announce(peer, { info_hash: hash, peer_id: peer.id, left: 0 });
if (holder === root) await announce(root, { info_hash: hash, peer_id: root.id, left: 1 });
else {
holder.ws.close();
await holder.closed;
}
holder = peer;
}
// queryObjects collects garbage first.
await expect.poll(() => queryObjects(ServerSocket, { format: 'count' })).toBeLessThanOrEqual(2);
});
+31
View File
@@ -1,7 +1,9 @@
import { createCipheriv, createDecipheriv, createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto'; import { createCipheriv, createDecipheriv, createHash, hkdfSync, pbkdf2Sync, randomBytes } from 'node:crypto';
import { createSocket, type Socket } from 'node:dgram'; import { createSocket, type Socket } from 'node:dgram';
import { once } from 'node:events';
import { createReadStream } from 'node:fs'; import { createReadStream } from 'node:fs';
import { open as openFile, readFile, writeFile } from 'node:fs/promises'; import { open as openFile, readFile, writeFile } from 'node:fs/promises';
import type { AddressInfo } from 'node:net';
import { networkInterfaces } from 'node:os'; import { networkInterfaces } from 'node:os';
import { import {
type Browser, type Browser,
@@ -420,6 +422,35 @@ for (const mode of ['manual', 'tracker']) {
} }
} }
// The tracker from backend/, in this worker on a free port, allowing the dev server's origin.
// backend/tracker.spec.mjs tests its rules on their own.
async function ownTracker() {
process.env.PORT = '0';
process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${new URL(url).origin}`;
const { server } = await import('./backend/tracker.mjs');
if (!server.listening) await once(server, 'listening');
return `ws://127.0.0.1:${(server.address() as AddressInfo).port}`;
}
// Through the own tracker alone, without STUN. With the public ones as fallbacks, a tracker that
// doesn't understand the client would go unnoticed.
for (const [from, to] of [
['chromium', 'firefox'],
['firefox', 'chromium'],
] as const) {
test(`own tracker: ${from} sends to ${to}`, async () => {
const tracker = await ownTracker();
const [sender, receiver] = await Promise.all([open(from), open(to)]);
for (const page of [sender, receiver]) {
await page.uncheck('#stun');
await page.click('#servers summary');
await page.fill('#trackers', tracker);
}
await transfer('tracker', sender, receiver, await payload(randomBytes(SIZE)), SIZE);
await expect(sender.locator('#log')).toContainText(`offer via ${tracker}`);
});
}
test('build: chromium sends to firefox from the production build', async () => { test('build: chromium sends to firefox from the production build', async () => {
const outDir = test.info().outputPath('dist'); const outDir = test.info().outputPath('dist');
await build({ logLevel: 'silent', build: { outDir, emptyOutDir: true } }); await build({ logLevel: 'silent', build: { outDir, emptyOutDir: true } });
+3 -2
View File
@@ -25,10 +25,11 @@
"@vitejs/plugin-vue": "^6.0.10", "@vitejs/plugin-vue": "^6.0.10",
"typescript": "~6.0.3", "typescript": "~6.0.3",
"vite": "^8.3.4", "vite": "^8.3.4",
"vue-tsc": "^3.3.13" "vue-tsc": "^3.3.13",
"ws": "8.22.0"
}, },
"engines": { "engines": {
"node": ">=26.11.1" "node": ">=26.12.1"
}, },
"packageManager": "pnpm@12.14.0" "packageManager": "pnpm@12.14.0"
} }
+17
View File
@@ -191,6 +191,9 @@ importers:
vue-tsc: vue-tsc:
specifier: ^3.3.13 specifier: ^3.3.13
version: 3.3.13(typescript@6.0.3) version: 3.3.13(typescript@6.0.3)
ws:
specifier: 8.22.0
version: 8.22.0
packages: packages:
@@ -653,6 +656,18 @@ packages:
typescript: typescript:
optional: true optional: true
ws@8.22.0:
resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}
engines: {node: '>=10.0.0'}
peerDependencies:
bufferutil: ^4.0.1
utf-8-validate: '>=5.0.2'
peerDependenciesMeta:
bufferutil:
optional: true
utf-8-validate:
optional: true
snapshots: snapshots:
'@babel/helper-string-parser@7.29.7': {} '@babel/helper-string-parser@7.29.7': {}
@@ -998,3 +1013,5 @@ snapshots:
'@vue/shared': 3.5.44 '@vue/shared': 3.5.44
optionalDependencies: optionalDependencies:
typescript: 6.0.3 typescript: 6.0.3
ws@8.22.0: {}
+1
View File
@@ -13,6 +13,7 @@
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"isolatedModules": true, "isolatedModules": true,
"skipLibCheck": true, "skipLibCheck": true,
"allowJs": true,
"noEmit": true "noEmit": true
}, },
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"] "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e.spec.ts"]