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

+6
View File
@@ -0,0 +1,6 @@
*
!package.json
!package-lock.json
!server.mjs
!healthcheck.mjs
!test.mjs
+24
View File
@@ -0,0 +1,24 @@
# Official Node image; update the digest deliberately alongside tracker checks.
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS dependencies
WORKDIR /app
COPY package.json package-lock.json ./
# Only the server entry point is used. Native client/optional accelerators and
# package lifecycle scripts are unnecessary for WebSocket tracker operation.
RUN npm ci --omit=dev --omit=optional --ignore-scripts --no-audit --no-fund \
&& npm cache clean --force
FROM dependencies AS test
COPY server.mjs healthcheck.mjs test.mjs ./
USER node
RUN node --test test.mjs
FROM node:24-bookworm-slim@sha256:a5f4366e834695d5f363b920c104953a535d3a9864d1bdf74566a0ebe01daee5 AS runtime
ENV NODE_ENV=production PORT=8000 DEBUG=""
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY package.json server.mjs healthcheck.mjs ./
USER node
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD ["node", "healthcheck.mjs"]
CMD ["node", "server.mjs"]
+125
View File
@@ -0,0 +1,125 @@
# HellCon WebTorrent tracker container
Our Dockerfile builds directly from the official Node image and the upstream
`bittorrent-tracker` npm package. The Node base is pinned by digest, the tracker
by version (11.2.3), and transitive dependencies by `package-lock.json`. There
is no third-party tracker image, Trystero dependency or browser package change.
The tracker container is implemented. HellCon's automatic reconnect UI and
client adapter are still [planned](../docs/webtorrent-reconnect.md); starting
this service does not change the app's current manual-code connection flow.
## Local development
Start Docker, then run from the repository root:
```sh
bun run tracker:up
bun run test:tracker
docker compose -f compose.tracker.yaml logs --tail=30 tracker
bun run tracker:down
```
The service listens at `ws://127.0.0.1:8000`. Choose a different host port with
`TRACKER_PORT=8001 bun run tracker:up`. Compose builds our Dockerfile and waits for
its health check; it does not start coturn or require `.env.development`. Vite
continues to run on the host. No service is enabled at boot and the development
container has no automatic restart policy.
`test:tracker` builds the Dockerfile's test target and runs native Node WebSocket
clients against the actual tracker server. It tests both arrival orders, counts
in announce replies, a 64 KiB code after AES-GCM/base64 encoding, answer routing,
disconnect cleanup, graceful termination, disabled HTTP and WebSocket scrape,
malformed/oversized messages, swarm/rate limits, per-socket swarm and peer ID
limits (including pipelined frames), idle timeouts, origins, untrusted and
trusted forwarded IP headers and IPv6 prefix grouping. Tests do not depend on public trackers. They establish tracker
interoperability, not a complete browser reconnect or Internet NAT test.
If you started Docker only for these checks, stop it afterward:
```sh
sudo systemctl stop docker.service docker.socket containerd.service
```
## VPS deployment
Use the same Dockerfile and `compose.tracker.yaml`. The service binds its host
port to loopback; an HTTPS reverse proxy on the host terminates TLS and forwards
WebSocket upgrades to port 8000. A Caddy example for a dedicated hostname:
```caddyfile
tracker.example.com {
reverse_proxy 127.0.0.1:8000
}
```
Clients then use `wss://tracker.example.com`. Keep access logging disabled for
this endpoint, including any logging configured elsewhere. If the proxy is
containerized, use a shared private Docker network and the service name instead
of the proxy container's loopback address.
Set `TRACKER_ALLOWED_ORIGINS=https://your-app.example` for browser origin checks.
These checks are not client authentication. The wrapper rate-limits the socket's
source IP by default. For a proxy deployment, set `TRACKER_TRUSTED_PROXY_IPS` to
the exact source addresses the tracker sees from your proxy. The wrapper uses
the rightmost `X-Forwarded-For` entry, which must be the address your proxy saw;
proxies that replace the header (Caddy's default) or append to it both work.
Docker bridge addresses can differ from `127.0.0.1`. Without this configuration, all proxied
clients share the proxy IP's limits. Never expose the backend directly while
trusting arbitrary forwarded headers.
Production restart behavior is an explicit operator choice. For example, add a
Compose override containing `services: {tracker: {restart: unless-stopped}}` and
pass it after `-f compose.tracker.yaml`. This does not change local development's
no-restart policy. This repository does not deploy DNS, TLS or the proxy for you.
## Configuration
Pass these environment variables to the container. The Compose file exposes
the origin/proxy settings through the `TRACKER_` variables above; use an override
file for the other container settings.
| Variable | Default | Purpose |
| --- | --- | --- |
| `PORT` | `8000` | Internal HTTP/WebSocket port; keep Compose mapping in sync |
| `ANNOUNCE_INTERVAL_SECONDS` | `5` | Interval advertised to WebSocket clients |
| `MAX_PAYLOAD_BYTES` | `131072` | Maximum WebSocket message size |
| `MAX_CONNECTIONS` | `200` | Global WebSocket connection cap |
| `MAX_CONNECTIONS_PER_IP` | `8` | Connections per effective source IP; IPv6 per /64 |
| `MESSAGES_PER_MINUTE` | `120` | Handshake attempts and incoming messages per IP or /64 |
| `MAX_SWARMS` | `1000` | Discovery identifiers admitted at once |
| `MAX_PEERS_PER_SWARM` | `32` | Upstream LRU peer-cache bound; excess peers evict older entries |
| `PEER_TTL_SECONDS` | `300` | Idle socket timeout and peer cache lifetime |
| `ALLOWED_ORIGINS` | empty | Comma-separated browser origins; empty permits all |
| `TRUSTED_PROXY_IPS` | empty | Exact proxy source IPs allowed to supply forwarded addresses |
The container runs as the unprivileged Node user. Compose applies a read-only
filesystem, drops capabilities, prevents privilege escalation and bounds CPU,
memory and process count. No persistent volume is required. Stale sockets,
expired swarm memberships, empty swarms and expired rate buckets are cleaned
periodically. `/healthz` returns 204; other ordinary HTTP routes return 404.
UDP and HTTP tracker APIs,
public statistics and WebSocket scrape requests are disabled.
The wrapper emits a startup line and generic fatal server errors, not peer IDs,
IPs, payloads or upstream warning text. Leave `DEBUG` empty. The operator can
still observe connection metadata; this is not an anonymity service.
## Updating
Update `tracker/package.json` deliberately, regenerate the lockfile, and rerun
`bun run test:tracker` before rebuilding the runtime image. With npm available:
```sh
npm install --package-lock-only --ignore-scripts --prefix tracker
```
Alternatively run npm inside the official Node image with this directory mounted
as its workdir. The image build uses `npm ci --omit=dev --omit=optional
--ignore-scripts`; native client components and optional accelerators are not
needed by the server entry point. The wrapper uses pinned upstream connection
hooks, so review those hooks when upgrading the tracker. Update the official
Node image digest in both Dockerfile stages for base-image security updates.
Sources: [upstream tracker](https://github.com/webtorrent/bittorrent-tracker),
[official Node container](https://github.com/nodejs/docker-node).
+4
View File
@@ -0,0 +1,4 @@
try {
const response = await fetch(`http://127.0.0.1:${process.env.PORT || 8000}/healthz`, { signal: AbortSignal.timeout(2000) });
process.exit(response.status === 204 ? 0 : 1);
} catch { process.exit(1); }
+1055
View File
File diff suppressed because it is too large. Load diff
+12
View File
@@ -0,0 +1,12 @@
{
"name": "hellcon-tracker",
"private": true,
"type": "module",
"scripts": {
"start": "node server.mjs",
"test": "node --test test.mjs"
},
"dependencies": {
"bittorrent-tracker": "11.2.3"
}
}
+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}`));
+284
View File
@@ -0,0 +1,284 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { randomBytes, webcrypto } from 'node:crypto';
import { createConnection, createServer } from 'node:net';
import { setTimeout as delay } from 'node:timers/promises';
import { test } from 'node:test';
const id = () => randomBytes(20).toString('latin1');
async function start(t, env = {}) {
const reservation = createServer();
await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve));
const port = reservation.address().port;
await new Promise(resolve => reservation.close(resolve));
const child = spawn(process.execPath, ['server.mjs'], {
cwd: import.meta.dirname,
env: { ...process.env, PORT: String(port), ...env },
stdio: ['ignore', 'pipe', 'pipe'],
});
let output = '';
child.stdout.on('data', data => { output += data; });
child.stderr.on('data', data => { output += data; });
const exited = new Promise(resolve => child.once('exit', (code, signal) => resolve({ code, signal })));
t.after(async () => {
child.kill('SIGTERM');
const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
const result = await exited;
clearTimeout(timer);
assert.deepEqual(result, { code: 0, signal: null }, output);
assert.match(output, /^WebSocket tracker listening on port \d+\n$/);
});
const http = `http://127.0.0.1:${port}`;
for (let n = 0; n < 100; n++) {
if (child.exitCode !== null) throw new Error(output);
try {
if ((await fetch(http + '/healthz')).status === 204) return { http, ws: `ws://127.0.0.1:${port}` };
} catch { /* startup */ }
await delay(25);
}
throw new Error('Tracker did not become healthy: ' + output);
}
async function connect(t, url) {
const socket = new WebSocket(url);
const frames = [];
socket.addEventListener('message', event => frames.push(JSON.parse(event.data)));
const closed = new Promise(resolve => socket.addEventListener('close', resolve, { once: true }));
t.after(async () => { socket.close(); await closed; });
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', () => reject(new Error('WebSocket connection failed')), { once: true });
});
return {
socket, closed,
send(data) { socket.send(JSON.stringify(data)); },
async next(predicate) {
for (let n = 0; n < 200; n++) {
const index = frames.findIndex(predicate);
if (index >= 0) return frames.splice(index, 1)[0];
if (socket.readyState === WebSocket.CLOSED) throw new Error('Socket closed before expected frame');
await delay(10);
}
throw new Error('Expected tracker frame did not arrive');
},
};
}
const announce = (peer, hash, extra = {}) => ({
action: 'announce', info_hash: hash, peer_id: peer, uploaded: 0, downloaded: 0,
left: 1, numwant: 0, offers: [], ...extra,
});
for (const offererFirst of [false, true]) {
test(`encrypted signaling survives tracker routing, offerer arrives ${offererFirst ? 'first' : 'second'}`, { timeout: 15000 }, async t => {
const endpoint = await start(t);
const first = await connect(t, endpoint.ws);
const second = await connect(t, endpoint.ws);
const hash = id(), offerId = id(), sender = id(), receiver = id();
const key = await webcrypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
// A maximum-size connection code plus envelope metadata must fit after
// encryption/base64, even though its sdp field is deliberately opaque.
const plaintext = JSON.stringify({ version: 1, code: 'a'.repeat(64 * 1024), nonce: randomBytes(32).toString('hex') });
const iv = randomBytes(12);
const cipher = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, Buffer.from(plaintext));
const encrypted = Buffer.concat([iv, Buffer.from(cipher)]).toString('base64url');
const offered = { type: 'offer', sdp: encrypted };
const offerFrame = announce(sender, hash, { offers: [{ offer_id: offerId, offer: offered }], numwant: 1 });
if (offererFirst) {
first.send(offerFrame);
const alone = await first.next(frame => frame.interval);
assert.equal(alone.complete + alone.incomplete, 1);
}
second.send(announce(receiver, hash));
await second.next(frame => frame.interval);
first.send(offerFrame);
const offer = await second.next(frame => frame.offer);
assert.deepEqual(offer.offer, offered);
assert.equal(offer.peer_id, sender);
assert.equal(offer.info_hash, hash);
assert.equal(offer.offer_id, offerId);
const wire = Buffer.from(offer.offer.sdp, 'base64url');
const decrypted = await webcrypto.subtle.decrypt({ name: 'AES-GCM', iv: wire.subarray(0, 12) }, key, wire.subarray(12));
assert.equal(Buffer.from(decrypted).toString(), plaintext);
const answer = { type: 'answer', sdp: encrypted };
second.send(announce(receiver, hash, { answer, offer_id: offerId, to_peer_id: sender }));
const response = await first.next(frame => frame.answer);
assert.deepEqual(response.answer, answer);
assert.equal(response.peer_id, receiver);
const counts = await first.next(frame => frame.interval);
assert.equal(counts.interval, 5);
assert.equal(counts.complete + counts.incomplete, 2);
second.socket.close();
await second.closed;
first.send(announce(sender, hash));
const afterClose = await first.next(frame => frame.interval);
assert.equal(afterClose.complete + afterClose.incomplete, 1);
});
}
test('health is public; HTTP APIs, WebSocket scrape and malformed frames are disabled', { timeout: 15000 }, async t => {
const endpoint = await start(t);
for (const path of ['/stats', '/stats.json', '/announce', '/scrape']) {
assert.equal((await fetch(endpoint.http + path)).status, 404);
}
for (const payload of [{ action: 'scrape' }, { action: 'announce', info_hash: 'bad' }, null]) {
const client = await connect(t, endpoint.ws);
client.send(payload);
assert.equal((await client.closed).code, 1008);
}
const badJson = await connect(t, endpoint.ws);
badJson.socket.send('{');
assert.equal((await badJson.closed).code, 1008);
const oversized = await connect(t, endpoint.ws);
oversized.socket.send('x'.repeat(128 * 1024 + 1));
assert.equal((await oversized.closed).code, 1009);
assert.equal((await fetch(endpoint.http + '/healthz')).status, 204);
});
test('swarm capacity and message rate are bounded', { timeout: 15000 }, async t => {
const endpoint = await start(t, { MAX_SWARMS: '1', MESSAGES_PER_MINUTE: '4' });
const client = await connect(t, endpoint.ws);
const peer = id(), hash = id();
client.send(announce(peer, hash));
await client.next(frame => frame.interval);
client.send(announce(peer, id()));
assert.equal((await client.next(frame => frame['failure reason']))['failure reason'], 'Tracker capacity reached');
client.send(announce(peer, hash));
await client.next(frame => frame.interval);
client.send(announce(peer, hash));
assert.equal((await client.closed).code, 1008);
});
// Node's WebSocket accepts non-standard headers, which browsers cannot set.
const attempt = (t, url, origin, forwarded) => new Promise(resolve => {
const headers = {};
if (origin) headers.Origin = origin;
if (forwarded) headers['X-Forwarded-For'] = forwarded;
const socket = new WebSocket(url, { headers });
socket.addEventListener('open', () => resolve(socket), { once: true });
socket.addEventListener('error', () => resolve(null), { once: true });
t.after(() => socket.close());
});
const closeOf = socket => new Promise(resolve => socket.addEventListener('close', ({ code, reason }) => resolve({ code, reason }), { once: true }));
// WebSocket clients cannot force several frames into one TCP write, so this
// speaks just enough RFC 6455 to pipeline masked text frames.
function pipeline(t, url, messages) {
const { hostname, port } = new URL(url);
const socket = createConnection(Number(port), hostname);
t.after(() => socket.destroy());
const frame = text => {
const payload = Buffer.from(text);
const length = payload.length < 126 ? [payload.length] : [126, payload.length >> 8, payload.length & 0xff];
// A zero masking key leaves the payload unchanged.
return Buffer.concat([Buffer.from([0x81, 0x80 | length[0], ...length.slice(1)]), Buffer.alloc(4), payload]);
};
socket.write(`GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
`Sec-WebSocket-Key: ${randomBytes(16).toString('base64')}\r\nSec-WebSocket-Version: 13\r\n\r\n`);
return new Promise((resolve, reject) => {
let buffer = Buffer.alloc(0), upgraded = false;
socket.on('error', reject);
socket.on('close', () => reject(new Error('Socket closed without a close frame')));
socket.on('data', data => {
buffer = Buffer.concat([buffer, data]);
if (!upgraded) {
const end = buffer.indexOf('\r\n\r\n');
if (end < 0) return;
if (!buffer.toString('latin1', 0, end).startsWith('HTTP/1.1 101')) { reject(new Error('Upgrade refused')); return; }
upgraded = true;
buffer = buffer.subarray(end + 4);
socket.write(Buffer.concat(messages.map(message => frame(JSON.stringify(message)))));
}
// Server frames are unmasked; tracker replies stay below 64 KiB.
while (buffer.length >= 2) {
let length = buffer[1] & 0x7f, start = 2;
if (length === 126) {
if (buffer.length < 4) return;
length = buffer.readUInt16BE(2); start = 4;
}
if (buffer.length < start + length) return;
if ((buffer[0] & 0x0f) === 8) {
resolve({ code: buffer.readUInt16BE(start), reason: buffer.toString('utf8', start + 2, start + length) });
socket.destroy(); return;
}
buffer = buffer.subarray(start + length);
}
});
});
}
test('origin and per-IP connection checks apply; untrusted forwarded IPs cannot bypass the limit', { timeout: 15000 }, async t => {
const endpoint = await start(t, { ALLOWED_ORIGINS: 'https://other.example , https://hellcon.example', MAX_CONNECTIONS_PER_IP: '1' });
assert.equal(await attempt(t, endpoint.ws, 'https://evil.example', '192.0.2.1'), null);
const accepted = await attempt(t, endpoint.ws, 'https://hellcon.example', '192.0.2.1');
assert.ok(accepted);
assert.equal(await attempt(t, endpoint.ws, 'https://hellcon.example', '192.0.2.2'), null);
});
test('trusted proxies supply the rightmost forwarded IP; IPv6 limits apply per /64', { timeout: 15000 }, async t => {
const endpoint = await start(t, { TRUSTED_PROXY_IPS: ' ::ffff:127.0.0.1 ', MAX_CONNECTIONS_PER_IP: '1' });
const connect = forwarded => attempt(t, endpoint.ws, undefined, forwarded);
assert.ok(await connect('198.51.100.7, 192.0.2.1'));
// Spoofed leftmost entries do not create a fresh limit bucket.
assert.equal(await connect('198.51.100.8, 192.0.2.1'), null);
assert.ok(await connect('192.0.2.2'));
assert.ok(await connect('2001:db8::1'));
assert.equal(await connect('2001:db8:0:0:ffff::2'), null);
assert.equal(await connect('2001:DB8:0000::1.2.3.4'), null);
assert.ok(await connect('2001:db8:0:1::1'));
});
test('a socket keeps one peer ID and joins at most four swarms, even with pipelined frames', { timeout: 15000 }, async t => {
const endpoint = await start(t);
const sequential = await attempt(t, endpoint.ws);
const replies = [];
sequential.addEventListener('message', event => replies.push(JSON.parse(event.data)));
const peer = id(), hashes = [id(), id(), id(), id()];
for (const hash of [...hashes, hashes[0]]) sequential.send(JSON.stringify(announce(peer, hash)));
for (let n = 0; replies.filter(frame => frame.interval).length < 5; n++) {
assert.ok(n < 200, 'Expected five announce replies');
await delay(10);
}
const fifth = closeOf(sequential);
sequential.send(JSON.stringify(announce(peer, id())));
assert.deepEqual(await fifth, { code: 1008, reason: 'Too many swarms' });
const batchPeer = id();
const batch = Array.from({ length: 8 }, () => announce(batchPeer, id()));
assert.deepEqual(await pipeline(t, endpoint.ws, batch), { code: 1008, reason: 'Too many swarms' });
const changing = await attempt(t, endpoint.ws);
const changed = closeOf(changing);
const hash = id();
changing.send(JSON.stringify(announce(id(), hash)));
changing.send(JSON.stringify(announce(id(), hash)));
assert.deepEqual(await changed, { code: 1008, reason: 'Peer ID changed' });
});
test('memberships a live socket stops refreshing expire after the peer TTL', { timeout: 15000 }, async t => {
const endpoint = await start(t, { PEER_TTL_SECONDS: '1' });
const active = await connect(t, endpoint.ws);
const peer = id(), kept = id(), abandoned = id();
active.send(announce(peer, kept));
active.send(announce(peer, abandoned));
await active.next(frame => frame.interval);
await active.next(frame => frame.interval);
const keepAlive = setInterval(() => active.send(announce(peer, kept)), 250);
t.after(() => clearInterval(keepAlive));
await delay(2500);
const late = await connect(t, endpoint.ws);
late.send(announce(id(), abandoned));
const counts = await late.next(frame => frame.interval);
assert.equal(counts.complete + counts.incomplete, 1);
assert.equal(active.socket.readyState, WebSocket.OPEN);
});
test('idle sockets are terminated after the peer TTL', { timeout: 15000 }, async t => {
const endpoint = await start(t, { PEER_TTL_SECONDS: '1' });
const client = await connect(t, endpoint.ws);
client.send(announce(id(), id()));
await client.next(frame => frame.interval);
const started = Date.now();
assert.equal((await client.closed).code, 1006);
assert.ok(Date.now() - started < 3000);
});