Files
SchluffeandClaude Opus 5.5 b102e55495 Limit the tracker per address and harden its plain HTTP path
Per address and minute: connects and forwarded signaling, so reconnecting
doesn't reset a client's allowance. X-Forwarded-For only counts from PROXIES,
checked with net.BlockList, with one warning when an uncovered peer sends it.
Plain requests get timeouts and a closing 404, silent connections go after
30 s and all queues together share a budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 20:27:50 +01:00

352 lines
16 KiB
JavaScript

// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged
// but one warning about PROXIES, without any address.
import { createServer } from 'node:http';
import { BlockList, isIP } from 'node:net';
import { WebSocketServer } from 'ws';
// Read on import, 0 picks a free one, see server.address().
const PORT = Number(process.env.PORT ?? 8000);
// Where HellCon is served from, separated by commas or spaces. Anything else is refused. Read on every
// connection, so test files sharing one process can each allow their own.
const allowed = (origin) =>
(process.env.ORIGINS ?? '')
.split(/[\s,]+/)
.filter(Boolean)
.includes(origin);
// Seconds. Peers last as long as their connection, announcing again only resends a receiver's offer,
// e.g. to a sender that was busy with another receiver.
const INTERVAL = 60;
// A sealed SDP is a few KiB.
const MAX_MESSAGE = 16 * 1024;
// Per connection: messages within RATE_WINDOW, bytes of SDP it gets forwarded and its lifetime. HellCon
// gives up a share or a search after 6 minutes.
const MAX_MESSAGES = 10;
const RATE_WINDOW = 10_000;
const MAX_FORWARDED = 64 * 1024;
// A positive number from the environment, read on every use like ORIGINS, so the spec can lower it
// to a testable moment. 0 or a typo would cut every connection short, the default stands then.
const fromEnv = (name, fallback) => {
const value = Number(process.env[name]);
return value > 0 ? value : fallback;
};
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
// a peer that reads never gets near it.
const MAX_QUEUED = 32 * 1024;
// The same for all peers together: MAX_QUEUED for each of MAX_CONNECTIONS would be 32 MiB against
// mem_limit. A quarter of them can still fill theirs.
const maxQueuedAll = () => fromEnv('MAX_QUEUED_ALL', 8 * 1024 * 1024);
const MAX_AGE = 7 * 60_000;
// A connection that announced nothing by then only holds a slot: 1024 of them would serve nobody
// for MAX_AGE.
const maxSilent = () => fromEnv('MAX_SILENT', 30_000);
const MAX_CONNECTIONS = 1024;
const MAX_PER_IP = 16;
// Per address and window, across its connections: MAX_PER_IP is only at once, MAX_FORWARDED only one
// connection, so a client that reconnects would otherwise get a fresh allowance for each. The window
// is long enough for a search to walk the trackers and to reannounce, short enough to cap a relay.
// Relaying through many addresses, e.g. the /64s of one /48, is accepted: other WebTorrent trackers
// relay anything anyway, the caps only keep one address from using this one's bandwidth.
const maxConnectsPerIp = () => fromEnv('MAX_CONNECTS_PER_IP', 120);
const maxForwardedPerIp = () => fromEnv('MAX_FORWARDED_PER_IP', 1024 * 1024);
const IP_WINDOW = 60_000;
// A record without open connections lives until its window is over, a churning client could pile up
// many: past a few thousand, the oldest closed ones go. An address dropping out only forgets its
// rate, the concurrent limit still holds.
const maxIps = () => fromEnv('MAX_IPS', 4 * MAX_CONNECTIONS);
// A share has one sender, receivers keep one connection per tracker.
const MAX_SWARM = 8;
// Offers a sender got and may still answer, the oldest go first.
const MAX_PENDING = 32;
// info_hash → peer_id → peer.
const swarms = new Map();
// address → { open, connects, forwarded, since }, see usage.
const perIp = new Map();
let connections = 0;
// Peers that were sent something and may still have it queued, see fits.
const queued = new Set();
// info_hash, peer_id and offer_id are 20 byte binary strings.
const isId = (value) => typeof value === 'string' && value.length === 20;
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
// Whose X-Forwarded-For to believe, PROXIES' addresses or CIDRs. Read on every connection, like
// ORIGINS. An entry that is none is left out, as is an empty prefix: it would be 0, all of IPv4.
function proxies() {
const list = new BlockList();
for (const entry of (process.env.PROXIES ?? '').split(/[\s,]+/).filter(Boolean)) {
const [base, prefix] = entry.split('/');
const type = { 4: 'ipv4', 6: 'ipv6' }[isIP(base)];
if (!type) continue;
if (prefix === undefined) list.addAddress(base, type);
else if (/^\d+$/.test(prefix) && prefix <= (type === 'ipv4' ? 32 : 128)) list.addSubnet(base, Number(prefix), type);
}
return list;
}
// Once: behind a proxy PROXIES doesn't cover, every client counts as the proxy and shares its limits.
let warned = false;
// The client's address for the per-IP limits. A client that reaches the tracker directly names any
// address it likes in X-Forwarded-For, so without a listed proxy only the socket's own counts. Behind
// a listed proxy, like Caddy on the compose file's network, the last entry is the client's, whatever
// the client put before it. IPv6 counts by /64: a single host usually has a whole one, every address
// in it would get an allowance of its own. IPv4, also mapped to IPv6, counts as it is.
function clientIp(req) {
const peer = req.socket.remoteAddress;
const header = req.headers['x-forwarded-for'];
// BlockList matches IPv4 rules against IPv4-mapped addresses too.
const trusted = isIP(peer) && proxies().check(peer, isIP(peer) === 4 ? 'ipv4' : 'ipv6');
if (header && !trusted && !warned) {
warned = true;
console.warn('X-Forwarded-For from an address PROXIES does not cover, ignored. Behind a proxy, add it.');
}
const forwarded = trusted ? header?.split(',').at(-1).trim() : undefined;
const ip = isIP(forwarded) ? forwarded : peer;
if (!isIP(ip)) return 'unknown';
if (ip.includes('.')) return ip.replace(/^::ffff:/i, '');
const [head, tail] = ip.split('::');
const groups = head ? head.split(':') : [];
if (tail !== undefined) {
const rest = tail ? tail.split(':') : [];
groups.push(...Array(Math.max(0, 8 - groups.length - rest.length)).fill('0'), ...rest);
}
return `${groups
.slice(0, 4)
.map((group) => parseInt(group, 16).toString(16))
.join(':')}::/64`;
}
// The address's record for the current window. Open connections stay counted across a reset, what it
// used starts over. A record without open connections is dropped by the sweep once its window is over.
function usage(ip) {
const now = Date.now();
let record = perIp.get(ip);
if (!record) {
// Room for the new one. At most MAX_CONNECTIONS records have an open connection, so with room to
// spare above that there is always a closed one to drop.
const limit = maxIps();
for (const [old, other] of perIp) {
if (perIp.size < limit) break;
if (!other.open) perIp.delete(old);
}
record = { open: 0, connects: 0, forwarded: 0, since: now };
perIp.set(ip, record);
} else if (now - record.since >= IP_WINDOW) {
record.connects = 0;
record.forwarded = 0;
record.since = now;
}
return record;
}
function refuse(socket, status) {
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
}
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
// wait for its close frame. Past maxQueuedAll() for all of them, the largest queues go first: a peer
// that reads has next to nothing queued, so one without a queue never goes for the others'.
function fits(peer, bytes) {
if (peer.ws.readyState !== peer.ws.OPEN) return false;
if (peer.ws.bufferedAmount + bytes > MAX_QUEUED) return drop(peer);
let total = bytes;
for (const other of queued) {
if (other.ws.bufferedAmount) total += other.ws.bufferedAmount;
else queued.delete(other);
}
queued.add(peer);
if (total > maxQueuedAll()) {
for (const other of [...queued].sort((a, b) => b.ws.bufferedAmount - a.ws.bufferedAmount)) {
if (total <= maxQueuedAll() || !other.ws.bufferedAmount) break;
total -= other.ws.bufferedAmount;
drop(other);
}
}
return peer.ws.readyState === peer.ws.OPEN;
}
// Its queue goes with the socket.
function drop(peer) {
peer.ws.terminate();
queued.delete(peer);
return false;
}
function send(peer, message) {
const data = JSON.stringify(message);
if (fits(peer, Buffer.byteLength(data))) peer.ws.send(data);
}
// HellCon shows the reason, the connection closes.
function reject(peer, reason) {
send(peer, { 'failure reason': reason });
peer.ws.close();
}
function forward(from, to, message, sdp) {
from.forwarded += sdp.length;
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
const used = usage(from.ip);
used.forwarded += sdp.length;
if (used.forwarded > maxForwardedPerIp()) return reject(from, 'too much signaling');
send(to, message);
}
function announce(peer, msg) {
const { info_hash: hash, peer_id: id } = msg;
if (msg.action !== 'announce' || !isId(hash) || !isId(id)) return reject(peer, 'invalid announce');
if (!peer.id) {
const swarm = swarms.get(hash) ?? new Map();
if (swarm.has(id)) return reject(peer, 'peer_id taken');
if (swarm.size >= MAX_SWARM) return reject(peer, 'swarm full');
swarms.set(hash, swarm.set(id, peer));
peer.id = id;
peer.hash = hash;
clearTimeout(peer.silent);
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
if (msg.event === 'stopped') return peer.ws.close();
peer.seeder = msg.left === 0;
const swarm = swarms.get(hash);
if (msg.offers !== undefined) {
const [offer, ...more] = Array.isArray(msg.offers) ? msg.offers : [];
if (more.length || (offer && (!isId(offer.offer_id) || !isSdp(offer.offer, 'offer')))) {
return reject(peer, 'invalid offer');
}
const senders = [...swarm.values()].filter((other) => other.seeder && other !== peer);
const sender = senders[Math.floor(Math.random() * senders.length)];
if (offer && sender) {
sender.pending.delete(offer.offer_id);
sender.pending.set(offer.offer_id, peer);
if (sender.pending.size > MAX_PENDING) sender.pending.delete(sender.pending.keys().next().value);
const { sdp } = offer.offer;
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: offer.offer_id };
forward(peer, sender, { ...message, offer: { type: 'offer', sdp } }, sdp);
}
}
if (msg.answer !== undefined) {
if (!isId(msg.to_peer_id) || !isId(msg.offer_id) || !isSdp(msg.answer, 'answer')) {
return reject(peer, 'invalid answer');
}
const receiver = peer.pending.get(msg.offer_id);
// An offer it never got, answered already or whose receiver left: dropped, a stray answer doesn't
// cost the share.
if (receiver?.id === msg.to_peer_id) {
peer.pending.delete(msg.offer_id);
const { sdp } = msg.answer;
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: msg.offer_id };
forward(peer, receiver, { ...message, answer: { type: 'answer', sdp } }, sdp);
}
}
// complete counts the seeders, HellCon's receiver moves on to its next tracker without one.
if (peer.ws.readyState === peer.ws.OPEN) {
const complete = [...swarm.values()].filter((other) => other.seeder).length;
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash, complete });
}
}
function open(ws, ip) {
const peer = {
ws,
ip,
id: undefined,
hash: undefined,
seeder: false,
pending: new Map(),
forwarded: 0,
messages: 0,
// Terminated, close would keep the slot for ws's 30 s more if the client ignores the close
// frame. A peer that never announced has nothing to say goodbye to.
silent: setTimeout(() => ws.terminate(), maxSilent()),
};
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
const age = setTimeout(() => ws.close(), MAX_AGE);
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
ws.on('error', () => {});
// Pings and pongs count as messages. ws would answer every ping on its own, past the limits.
const counted = () => ++peer.messages <= MAX_MESSAGES || reject(peer, 'too many messages');
ws.on('ping', (data) => counted() && fits(peer, data.length) && ws.pong(data));
ws.on('pong', counted);
ws.on('message', (data, binary) => {
if (!counted()) return;
let msg;
try {
msg = binary ? undefined : JSON.parse(data);
} catch {}
if (!msg || typeof msg !== 'object') return reject(peer, 'invalid message');
announce(peer, msg);
});
ws.on('close', () => {
clearInterval(rate);
clearTimeout(age);
clearTimeout(peer.silent);
queued.delete(peer);
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
peer.pending.clear();
const swarm = swarms.get(peer.hash);
if (swarm?.get(peer.id) !== peer) return;
swarm.delete(peer.id);
if (!swarm.size) swarms.delete(peer.hash);
// Its offers go only to peers of its swarm.
for (const other of swarm.values()) {
for (const [offerId, receiver] of other.pending) if (receiver === peer) other.pending.delete(offerId);
}
});
}
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
// Plain requests aren't counted below, only upgraded ones are, so Node's own limits keep them from
// piling up, each one's kernel buffers against mem_limit. Node checks headersTimeout and
// requestTimeout every connectionsCheckingInterval, 30 s unless set. headersTimeout starts only once
// something arrived, the idle timeout on every connection covers one that sends nothing, cleared
// for an accepted upgrade: HellCon's peers sit out their announce interval. The 404 closes the
// socket, nothing of it stays for a keep-alive. maxConnections caps all sockets, plain ones
// included: beyond it Node drops new ones without a response, the one place a client gets a bare
// connection error instead of a 503.
export const server = createServer({ connectionsCheckingInterval: 5_000 }, (_, res) =>
res.writeHead(404, { Connection: 'close' }).end(),
);
server.on('connection', (socket) => socket.setTimeout(10_000, () => socket.destroy()));
server.headersTimeout = 10_000;
server.requestTimeout = 30_000;
server.maxHeadersCount = 100;
server.maxConnections = 2 * MAX_CONNECTIONS;
server.on('upgrade', (req, socket, head) => {
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
// client resetting a refused connection would end the process.
socket.on('error', () => {});
const ip = clientIp(req);
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
const used = usage(ip);
if (used.open >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
// Closing a connection doesn't give the address its allowance back.
if (used.connects >= maxConnectsPerIp()) return refuse(socket, '429 Too Many Requests');
// Counted on the socket, so an upgrade that fails is released too.
connections++;
used.open++;
used.connects++;
socket.once('close', () => {
connections--;
used.open--;
});
// A peer sits out its announce interval, the idle timeout is over for it.
socket.setTimeout(0);
wss.handleUpgrade(req, socket, head, (ws) => open(ws, ip));
});
// An address's window only matters while something of it is open or recent. Once its last connection
// is gone and its window over, the record goes: nothing else would ever delete it.
const sweep = setInterval(() => {
const now = Date.now();
for (const [ip, record] of perIp) if (!record.open && now - record.since >= IP_WINDOW) perIp.delete(ip);
}, IP_WINDOW);
sweep.unref();
server.listen(PORT);