Add self-hosted WebTorrent tracker container and reconnect plan

Build a WebSocket-only tracker from the official Node image and a locked
bittorrent-tracker 11.2.3, run via compose.tracker.yaml and the
tracker:up/tracker:down/test:tracker scripts. A small wrapper disables
scrape and stats and bounds input: frame validation, per-IP connection
and message limits (IPv6 grouped per /64), origin checks, a fixed peer ID
and at most four swarms per socket (tracked synchronously, so pipelined
frames cannot bypass it), swarm and peer caps, idle-socket timeout and
explicit expiry of stale swarm memberships. Forwarded addresses are taken
from the rightmost X-Forwarded-For entry and only from trusted proxies.

Integration tests use only Node built-ins. Document the planned tracker
reconnect design; the app still uses manual connection codes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-19 21:03:45 +02:00
1 parent 8665d04f2c
commit e3af2de051
13 files changed
+2003 -2

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
import { isIP } from 'node:net';
import Server from 'bittorrent-tracker/server';
function integer(name, fallback, max = 1_000_000) {
const value = Number(process.env[name] ?? fallback);
if (!Number.isSafeInteger(value) || value < 1 || value > max) throw new Error(`Invalid ${name}`);
return value;
}
const port = integer('PORT', 8000, 65535);
const interval = integer('ANNOUNCE_INTERVAL_SECONDS', 5, 600);
const maxPayload = integer('MAX_PAYLOAD_BYTES', 128 * 1024);
const maxConnections = integer('MAX_CONNECTIONS', 200);
const maxPerIp = integer('MAX_CONNECTIONS_PER_IP', 8);
const maxMessages = integer('MESSAGES_PER_MINUTE', 120);
const maxSwarms = integer('MAX_SWARMS', 1000);
const maxPeers = integer('MAX_PEERS_PER_SWARM', 32);
const peerAge = integer('PEER_TTL_SECONDS', 300);
const list = name => (process.env[name] || '').split(',').map(item => item.trim()).filter(Boolean);
const normalizeIp = ip => ip?.replace(/^::ffff:/, '') || '';
const origins = new Set(list('ALLOWED_ORIGINS'));
const proxies = new Set(list('TRUSTED_PROXY_IPS').map(normalizeIp));
const clientsPerIp = new Map();
const rates = new Map();
const admittedSwarms = new Set();
function allowRequest(ip) {
const now = Date.now();
let bucket = rates.get(ip);
if (!bucket || now >= bucket.until) {
bucket = { count: 0, until: now + 60_000 };
rates.set(ip, bucket);
}
return ++bucket.count <= maxMessages;
}
function clientIp(req) {
const remote = normalizeIp(req.socket.remoteAddress);
const forwarded = req.headers['x-forwarded-for'];
if (proxies.has(remote) && typeof forwarded === 'string') {
// The trusted proxy's observed address is last; earlier entries are client-supplied.
const last = forwarded.split(',').at(-1).trim();
if (isIP(last)) return normalizeIp(last);
}
return remote;
}
// IPv6 hosts commonly control a whole /64, so limits apply per prefix.
function limitKey(ip) {
if (isIP(ip) !== 6) return ip;
const [head, tail] = ip.replace(/%.*$/, '').split('::');
// An embedded IPv4 suffix fills the last two groups, never the prefix.
const groups = part => part ? part.split(':').flatMap(group => group.includes('.') ? ['0', '0'] : [group]) : [];
const start = groups(head), end = groups(tail);
const all = tail === undefined ? start : [...start, ...Array(8 - start.length - end.length).fill('0'), ...end];
return all.slice(0, 4).map(group => parseInt(group, 16).toString(16)).join(':') + '::/64';
}
const binaryId = value => typeof value === 'string' && value.length === 20 && !/[^\x00-\xff]/.test(value);
const description = (value, type) => value && value.type === type && typeof value.sdp === 'string' && value.sdp.length <= maxPayload;
// These hooks are tied to the pinned upstream release. Keep the integration
// tests when upgrading: upstream owns routing, this wrapper bounds its input.
class Tracker extends Server {
onWebSocketConnection(socket, opts) {
const ip = socket.upgradeReq.hellconIp;
socket.hellconIp = ip;
socket.hellconSeen = Date.now();
// Upstream records joined swarms only after async routing, so pipelined
// frames would all pass a check against socket.infoHashes.
socket.hellconHashes = new Set();
clientsPerIp.set(ip, (clientsPerIp.get(ip) || 0) + 1);
socket.once('close', () => {
const remaining = (clientsPerIp.get(ip) || 1) - 1;
if (remaining) clientsPerIp.set(ip, remaining);
else clientsPerIp.delete(ip);
});
super.onWebSocketConnection(socket, opts);
}
_onWebSocketRequest(socket, opts, raw) {
if (!allowRequest(socket.hellconIp)) { socket.close(1008, 'Rate limit'); return; }
let data;
try { data = JSON.parse(raw); } catch { socket.close(1008, 'Invalid JSON'); return; }
// Scraping can enumerate private discovery identifiers. No scrape API is
// exposed, including over WebSocket when HTTP statistics are disabled.
if (!data || data.action !== 'announce' || !binaryId(data.info_hash) || !binaryId(data.peer_id) ||
(data.event && !['started', 'stopped', 'completed', 'update', 'paused'].includes(data.event)) ||
(data.offers !== undefined && (!Array.isArray(data.offers) || data.offers.length > 8 ||
data.offers.some(item => !item || !binaryId(item.offer_id) || !description(item.offer, 'offer')))) ||
(data.answer !== undefined && (!description(data.answer, 'answer') || !binaryId(data.offer_id) || !binaryId(data.to_peer_id)))) {
socket.close(1008, 'Invalid announce'); return;
}
if (socket.peerId && socket.peerId !== Buffer.from(data.peer_id, 'latin1').toString('hex')) {
socket.close(1008, 'Peer ID changed'); return;
}
const hash = Buffer.from(data.info_hash, 'latin1').toString('hex');
if (!socket.hellconHashes.has(hash)) {
if (socket.hellconHashes.size >= 4) { socket.close(1008, 'Too many swarms'); return; }
socket.hellconHashes.add(hash);
}
socket.hellconSeen = Date.now();
super._onWebSocketRequest(socket, opts, raw);
}
}
const server = new Tracker({
http: false, udp: false, stats: false, trustProxy: false,
// Upstream divides the configured interval by five for WebSocket responses.
interval: interval * 5000,
peersCacheLength: maxPeers,
peersCacheTtl: peerAge * 1000,
ws: {
clientTracking: true,
maxPayload,
verifyClient({ req, origin }) {
const ip = limitKey(clientIp(req));
req.hellconIp = ip;
return (!origins.size || origins.has(origin)) &&
server.ws.clients.size < maxConnections && (clientsPerIp.get(ip) || 0) < maxPerIp && allowRequest(ip);
},
},
filter(hash, params, done) {
if (!admittedSwarms.has(hash) && admittedSwarms.size >= maxSwarms) {
done(new Error('Tracker capacity reached')); return;
}
admittedSwarms.add(hash);
done(null);
},
});
server.http.on('request', (req, res) => {
if (req.method === 'GET' && req.url === '/healthz') {
res.writeHead(204, { 'Cache-Control': 'no-store' }); res.end();
}
});
// Never log raw upstream errors: they can contain attacker-controlled fields.
server.on('warning', () => {});
server.on('error', () => { console.error('Tracker server error'); shutdown(1); });
const cleanup = setInterval(() => {
const now = Date.now();
for (const socket of server.ws.clients) {
if (now - socket.hellconSeen > peerAge * 1000) socket.terminate();
}
for (const hash of admittedSwarms) {
const swarm = server.torrents[hash];
// Upstream's LRU expires peers only when read; peeking evicts stale entries
// through its synthetic 'stopped' handling before the emptiness check.
swarm?.peers.keys.forEach(key => swarm.peers.peek(key));
if (!swarm || !swarm.peers.keys.length) {
delete server.torrents[hash]; admittedSwarms.delete(hash);
}
}
for (const [ip, bucket] of rates) if (now >= bucket.until) rates.delete(ip);
}, Math.min(10_000, peerAge * 1000));
cleanup.unref();
let stopping = false;
function shutdown(code = 0) {
if (stopping) return;
stopping = true;
clearInterval(cleanup);
const deadline = setTimeout(() => process.exit(code), 3000);
deadline.unref();
for (const socket of server.ws.clients) socket.terminate();
server.close(() => process.exit(code));
}
process.on('SIGTERM', () => shutdown());
process.on('SIGINT', () => shutdown());
server.listen(port, '0.0.0.0', () => console.log(`WebSocket tracker listening on port ${port}`));