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); });