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>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-29 20:27:50 +01:00
1 parent ae1e3bef9b
commit b102e55495
5 files changed
+340 -34

No files matched your search

+164 -17
View File
@@ -1,8 +1,10 @@
// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged.
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged
// but one warning about PROXIES, without any address.
import { createServer } from 'node:http';
import { BlockList, isIP } from 'node:net';
import { WebSocketServer } from 'ws';
// Read on import, 0 picks a free one, see server.address().
@@ -24,12 +26,36 @@ const MAX_MESSAGE = 16 * 1024;
const MAX_MESSAGES = 10;
const RATE_WINDOW = 10_000;
const MAX_FORWARDED = 64 * 1024;
// A positive number from the environment, read on every use like ORIGINS, so the spec can lower it
// to a testable moment. 0 or a typo would cut every connection short, the default stands then.
const fromEnv = (name, fallback) => {
const value = Number(process.env[name]);
return value > 0 ? value : fallback;
};
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
// a peer that reads never gets near it.
const MAX_QUEUED = 32 * 1024;
// The same for all peers together: MAX_QUEUED for each of MAX_CONNECTIONS would be 32 MiB against
// mem_limit. A quarter of them can still fill theirs.
const maxQueuedAll = () => fromEnv('MAX_QUEUED_ALL', 8 * 1024 * 1024);
const MAX_AGE = 7 * 60_000;
// A connection that announced nothing by then only holds a slot: 1024 of them would serve nobody
// for MAX_AGE.
const maxSilent = () => fromEnv('MAX_SILENT', 30_000);
const MAX_CONNECTIONS = 1024;
const MAX_PER_IP = 16;
// Per address and window, across its connections: MAX_PER_IP is only at once, MAX_FORWARDED only one
// connection, so a client that reconnects would otherwise get a fresh allowance for each. The window
// is long enough for a search to walk the trackers and to reannounce, short enough to cap a relay.
// Relaying through many addresses, e.g. the /64s of one /48, is accepted: other WebTorrent trackers
// relay anything anyway, the caps only keep one address from using this one's bandwidth.
const maxConnectsPerIp = () => fromEnv('MAX_CONNECTS_PER_IP', 120);
const maxForwardedPerIp = () => fromEnv('MAX_FORWARDED_PER_IP', 1024 * 1024);
const IP_WINDOW = 60_000;
// A record without open connections lives until its window is over, a churning client could pile up
// many: past a few thousand, the oldest closed ones go. An address dropping out only forgets its
// rate, the concurrent limit still holds.
const maxIps = () => fromEnv('MAX_IPS', 4 * MAX_CONNECTIONS);
// A share has one sender, receivers keep one connection per tracker.
const MAX_SWARM = 8;
// Offers a sender got and may still answer, the oldest go first.
@@ -37,19 +63,51 @@ 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. IPv6 counts by /64: a single host usually has a whole one, every address in it
// would get MAX_PER_IP of its own. IPv4, also mapped to IPv6, counts as it is.
// 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 ip = req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
if (!ip?.includes(':') || ip.includes('.')) return ip;
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) {
@@ -62,16 +120,61 @@ function clientIp(req) {
.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.
// 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) {
@@ -88,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);
}
@@ -101,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;
@@ -145,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.
@@ -167,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);
@@ -181,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.
@@ -189,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);