// The tracker on its own, without browsers: what it forwards, what it refuses and what it keeps. // tracker.mjs runs in the worker on a free port. e2e.spec.ts sends a real file through it. import { once } from 'node:events'; import { connect as connectTcp } from 'node:net'; import { queryObjects } from 'node:v8'; import { expect, test } from '@playwright/test'; import { WebSocket as ServerSocket } from 'ws'; const ORIGIN = 'https://hellcon.test'; let server; let url; // Every connection a test opened, closed after it. let clients = []; // Each test connects from its own address, the tracker takes it from X-Forwarded-For. Otherwise // connections of the previous test, still closing, would count against the per-IP limit. let ip; let tests = 0; test.beforeAll(async () => { process.env.PORT = '0'; process.env.ORIGINS = `${process.env.ORIGINS ?? ''} ${ORIGIN}`; // The tracker believes this test's X-Forwarded-For like Caddy's. process.env.PROXIES = '127.0.0.1'; // Reconnecting tests pass the per-address limits on purpose, the ones about them lower them. process.env.MAX_CONNECTS_PER_IP = '100000'; process.env.MAX_FORWARDED_PER_IP = String(64 * 1024 * 1024); ({ server } = await import('./tracker.mjs')); if (!server.listening) await once(server, 'listening'); url = `ws://127.0.0.1:${server.address().port}`; }); // e2e.spec.ts may run next in this worker, with the tracker as it is deployed. test.afterAll(() => { delete process.env.PROXIES; delete process.env.MAX_CONNECTS_PER_IP; delete process.env.MAX_FORWARDED_PER_IP; }); test.beforeEach(() => { ip = `198.51.100.${++tests}`; }); test.afterEach(async () => { for (const client of clients) client.ws.close(); await Promise.all(clients.map((client) => client.closed)); clients = []; }); // fn with the environment variables in vars, undefined for unset, as they were again after it. async function withEnv(vars, fn) { const set = (name, value) => { if (value === undefined) delete process.env[name]; else process.env[name] = value; }; const was = Object.keys(vars).map((name) => [name, process.env[name]]); for (const [name, value] of Object.entries(vars)) set(name, value); try { return await fn(); } finally { for (const [name, value] of was) set(name, value); } } const id = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(20))); const sdp = (type, text = type) => ({ type, sdp: text }); // A connection like HellCon's, without one if the tracker refused it. Its messages queue up in // messages, closed resolves with the close code. function open({ origin = ORIGIN, xff = ip } = {}) { return new Promise((resolve) => { const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': xff } }); const client = { ws, messages: [], closed: once(ws, 'close').then(([event]) => event.code) }; ws.addEventListener('message', ({ data }) => client.messages.push(JSON.parse(data))); ws.addEventListener('open', () => { clients.push(client); resolve(client); }); ws.addEventListener('error', () => resolve(undefined)); }); } // Takes the first message that matches, once one came. open queues each before this sees it. async function take(client, match) { while (!client.messages.some(match)) await once(client.ws, 'message'); return client.messages.splice(client.messages.findIndex(match), 1)[0]; } // Announces and waits for the tracker's reply. Whatever it forwarded to this peer before is in // messages by then, so a test can tell that something was not forwarded. async function announce(client, fields) { client.ws.send(JSON.stringify({ action: 'announce', numwant: 0, uploaded: 0, downloaded: 0, ...fields })); return take(client, (msg) => 'interval' in msg); } // Sends raw and expects the tracker to reject it with reason, then close. async function rejected(client, data, reason) { client.ws.send(typeof data === 'string' || data instanceof Uint8Array ? data : JSON.stringify(data)); expect((await take(client, (msg) => 'failure reason' in msg))['failure reason']).toBe(reason); await client.closed; } // A swarm with a sender, a receiver and their peer ids. async function swarm() { const hash = id(); const sender = { ...(await open()), id: id() }; const receiver = { ...(await open()), id: id() }; await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0, event: 'started' }); await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, event: 'started' }); return { hash, sender, receiver }; } // The receiver's offer, as the sender got it. async function offer({ hash, sender, receiver }, offerId = id()) { await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, offers: [{ offer_id: offerId, offer: sdp('offer') }], }); return take(sender, (msg) => msg.offer); } const answer = ({ hash, sender }, to, offerId, text = 'answer') => announce(sender, { info_hash: hash, peer_id: sender.id, left: 0, to_peer_id: to, offer_id: offerId, answer: sdp('answer', text), }); test('refuses connections from other origins', async () => { expect(await open({ origin: 'https://evil.test' })).toBeUndefined(); expect(await open({ origin: '' })).toBeUndefined(); }); test('acknowledges an announce with the interval and the seeders only', async () => { const client = await open(); const hash = id(); expect(await announce(client, { info_hash: hash, peer_id: id(), left: 0 })).toEqual({ action: 'announce', interval: 60, info_hash: hash, complete: 1, }); }); test('counts the seeders of the swarm in complete', async () => { const hash = id(); const receiver = { ...(await open()), id: id() }; const seeders = async () => (await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1 })).complete; expect(await seeders()).toBe(0); // Another swarm's sender doesn't count. await announce(await open(), { info_hash: id(), peer_id: id(), left: 0 }); const sender = { ...(await open()), id: id() }; await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0 }); expect(await seeders()).toBe(1); // Gone once the tracker saw the connection close, which may be after the client did. sender.ws.close(); await expect.poll(seeders).toBe(0); }); test('forwards an offer to the sender only, rebuilt from its checked fields', async () => { const peers = await swarm(); const other = { ...(await open()), id: id() }; await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 }); const offerId = id(); await announce(peers.receiver, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1, offers: [{ offer_id: offerId, offer: { ...sdp('offer'), extra: 1 } }], extra: 1, }); expect(await take(peers.sender, (msg) => msg.offer)).toEqual({ action: 'announce', info_hash: peers.hash, peer_id: peers.receiver.id, offer_id: offerId, offer: sdp('offer'), }); await announce(other, { info_hash: peers.hash, peer_id: other.id, left: 1 }); expect(other.messages).toEqual([]); }); test('forwards an answer once, only to whoever sent the offer', async () => { const peers = await swarm(); const { offer_id } = await offer(peers); // Unknown offer, wrong receiver: dropped, and the sender stays connected. await answer(peers, peers.receiver.id, id()); await answer(peers, id(), offer_id); await answer(peers, peers.receiver.id, offer_id, 'sealed'); expect(await take(peers.receiver, (msg) => msg.answer)).toEqual({ action: 'announce', info_hash: peers.hash, peer_id: peers.sender.id, offer_id, answer: sdp('answer', 'sealed'), }); await answer(peers, peers.receiver.id, offer_id, 'again'); await announce(peers.receiver, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 }); expect(peers.receiver.messages).toEqual([]); }); test('drops an answer to a receiver that left', async () => { const peers = await swarm(); const { offer_id } = await offer(peers); peers.receiver.ws.close(); await peers.receiver.closed; // Its peer_id comes back with a new connection, the old offer stays gone. const again = await open(); await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 }); await answer(peers, peers.receiver.id, offer_id); await announce(again, { info_hash: peers.hash, peer_id: peers.receiver.id, left: 1 }); expect(again.messages).toEqual([]); }); for (const [name, data, reason] of [ ['text that is no JSON', 'nope', 'invalid message'], ['binary messages', new Uint8Array([1]), 'invalid message'], ['scrape', { action: 'scrape', info_hash: id() }, 'invalid announce'], ['a short info_hash', { action: 'announce', info_hash: 'x', peer_id: id() }, 'invalid announce'], [ 'two offers in one announce', { action: 'announce', info_hash: id(), peer_id: id(), left: 1, offers: [1, 2].map(() => ({ offer_id: id(), offer: sdp('offer') })), }, 'invalid offer', ], [ 'an offer that is an answer', { action: 'announce', info_hash: id(), peer_id: id(), left: 1, offers: [{ offer_id: id(), offer: sdp('answer') }] }, 'invalid offer', ], [ 'an answer without to_peer_id', { action: 'announce', info_hash: id(), peer_id: id(), left: 0, offer_id: id(), answer: sdp('answer') }, 'invalid answer', ], ]) { test(`rejects ${name}`, async () => { await rejected(await open(), data, reason); }); } test('rejects a taken peer_id and a second swarm', async () => { const { hash, sender } = await swarm(); await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: sender.id, left: 0 }, 'peer_id taken'); await rejected( sender, { action: 'announce', info_hash: id(), peer_id: sender.id, left: 0 }, 'one swarm per connection', ); }); test('frees a peer_id once its connection closed', async () => { const { hash, sender } = await swarm(); sender.ws.close(); await sender.closed; expect(await announce(await open(), { info_hash: hash, peer_id: sender.id, left: 0 })).toBeTruthy(); }); test('closes on a message beyond 16 KiB', async () => { const client = await open(); client.ws.send('x'.repeat(16 * 1024 + 1)); expect(await client.closed).toBe(1009); }); test('limits the message rate', async () => { const client = await open(); const fields = { action: 'announce', info_hash: id(), peer_id: id(), left: 0 }; for (let i = 0; i < 10; i++) client.ws.send(JSON.stringify(fields)); await rejected(client, fields, 'too many messages'); }); test('limits pings like messages, also from a peer that stops reading', async () => { // ws's client, browsers send no pings. ws used to answer every one, its pongs piled up in the tracker. const client = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } }); const closed = once(client, 'close'); const reasons = []; client.on('message', (data) => reasons.push(JSON.parse(data)['failure reason'])); await once(client, 'open'); client.ping('x'); expect(String((await once(client, 'pong'))[0])).toBe('x'); client._socket.pause(); for (let i = 0; i < 1000; i++) client.ping('x'.repeat(125)); client._socket.resume(); await closed; expect(reasons).toEqual(['too many messages']); }); test('limits the signaling forwarded per connection', async () => { const { hash, receiver } = await swarm(); const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) }); for (let i = 0; i < 4; i++) await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] }); await rejected( receiver, { action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1, offers: [big()] }, 'too much signaling', ); }); test('limits the signaling from one address across connections', () => withEnv({ MAX_FORWARDED_PER_IP: '20' }, async () => { const { hash, receiver } = await swarm(); const fields = { action: 'announce', info_hash: hash, peer_id: receiver.id, left: 1 }; // Five bytes each, four fit, the fifth is past the limit though the connection's own is far off. const offer = { offer_id: id(), offer: sdp('offer') }; for (let i = 0; i < 4; i++) await announce(receiver, { ...fields, offers: [offer] }); await rejected(receiver, { ...fields, offers: [offer] }, 'too much signaling'); // A new connection from the same address doesn't get a fresh allowance. const again = await open(); const second = { action: 'announce', info_hash: hash, peer_id: id(), left: 1 }; await announce(again, second); await rejected(again, { ...second, offers: [offer] }, 'too much signaling'); })); test('limits connections from one address over time, not only at once', () => withEnv({ MAX_CONNECTS_PER_IP: '3' }, async () => { for (let i = 0; i < 3; i++) expect(await open()).toBeTruthy(); // Below MAX_PER_IP, and closing them doesn't reset the rate. const opened = clients.splice(0); for (const client of opened) client.ws.close(); await Promise.all(opened.map((client) => client.closed)); expect(await open()).toBeUndefined(); })); test('forgets the oldest address once too many records pile up', () => withEnv({ MAX_IPS: '2', MAX_CONNECTS_PER_IP: '1' }, async () => { const close = async (address) => { ip = address; const client = await open(); client.ws.close(); await client.closed; // The tracker only evicts closed records, let it see the close first. await new Promise((resolve) => setTimeout(resolve, 50)); }; await close('192.0.2.1'); await close('192.0.2.2'); // The third record pushes the first out, which may connect again; the second stays limited. await close('192.0.2.3'); ip = '192.0.2.2'; expect(await open()).toBeUndefined(); ip = '192.0.2.1'; expect(await open()).toBeTruthy(); })); test('drops a peer that stops reading', async () => { const hash = id(); const slowId = id(); // ws's client, its socket can stop reading. What the tracker sends then piles up in the kernel's // buffers first, then in the tracker. const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } }); const closed = once(slow, 'close').then(([code]) => code); await once(slow, 'open'); slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0, numwant: 0 })); await once(slow, 'message'); slow._socket.pause(); const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) }); // Receivers that reconnect over and over, each within its own limit. The slow sender's peer_id is // free again once the tracker dropped it. let dropped = false; for (let i = 0; i < 1000 && !dropped; i++) { const receiver = await open(); const fields = { info_hash: hash, peer_id: id(), left: 1 }; for (let j = 0; j < 4; j++) await announce(receiver, { ...fields, offers: [big()] }); receiver.ws.close(); await receiver.closed; const probe = await open(); probe.ws.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: slowId, left: 0 })); dropped = 'interval' in (await take(probe, (msg) => 'interval' in msg || 'failure reason' in msg)); if (!dropped) await probe.closed; } expect(dropped).toBe(true); slow._socket.resume(); // Terminated, without a close frame. expect(await closed).toBe(1006); }); test('drops the largest queues once all of them together pass MAX_QUEUED_ALL', async () => { // The tracker's side of the slow sender's connection: what its socket holds is queued, the kernel's // buffers are full by then. let queue; const track = (_, socket) => (queue = socket); server.on('upgrade', track); const hash = id(); const slow = new ServerSocket(url, { headers: { origin: ORIGIN, 'x-forwarded-for': ip } }); const closed = once(slow, 'close').then(([code]) => code); await once(slow, 'open'); server.off('upgrade', track); slow.send(JSON.stringify({ action: 'announce', info_hash: hash, peer_id: id(), left: 0, numwant: 0 })); await once(slow, 'message'); slow._socket.pause(); // Budget lowered first: once the kernel's buffers are full, the next offer leaves a queue, and // the reply to the receiver right after it is past the budget. Checked later, the kernel could // have taken the queue in by then. The slow sender's queue goes, the receiver's reply arrives. const big = () => ({ offer_id: id(), offer: sdp('offer', 'x'.repeat(15_000)) }); await withEnv({ MAX_QUEUED_ALL: '1' }, async () => { for (let i = 0; i < 1000 && !queue.destroyed; i++) { const receiver = await open(); const fields = { info_hash: hash, peer_id: id(), left: 1 }; for (let j = 0; j < 4 && !queue.destroyed; j++) { await announce(receiver, { ...fields, offers: [big()] }); // Gone with its first queue, not once it grew to MAX_QUEUED. expect(queue.destroyed || !queue.writableLength).toBe(true); } receiver.ws.close(); await receiver.closed; } }); expect(queue.destroyed).toBe(true); slow._socket.resume(); expect(await closed).toBe(1006); }); test('limits a swarm to 8 peers', async () => { const hash = id(); for (let i = 0; i < 8; i++) await announce(await open(), { info_hash: hash, peer_id: id(), left: 1 }); await rejected(await open(), { action: 'announce', info_hash: hash, peer_id: id(), left: 1 }, 'swarm full'); }); test('limits connections per IP to 16', async () => { for (let i = 0; i < 16; i++) expect(await open()).toBeTruthy(); expect(await open()).toBeUndefined(); ip = '198.51.100.250'; expect(await open()).toBeTruthy(); }); test('counts IPv6 by /64, however it is written', async () => { for (let i = 1; i <= 16; i++) { ip = [`2001:db8:${tests}::${i.toString(16)}`, `2001:0DB8:${tests}:0:${i}::`][i % 2]; expect(await open()).toBeTruthy(); } ip = `2001:db8:${tests}:0:ffff:ffff:ffff:ffff`; expect(await open()).toBeUndefined(); ip = `2001:db8:${tests}:1::1`; expect(await open()).toBeTruthy(); }); test('ignores X-Forwarded-For without a trusted proxy', () => // Without PROXIES the socket's address counts, a client can't hand-pick a fresh one per // connection. All these come from 127.0.0.1. withEnv({ PROXIES: undefined }, async () => { for (let i = 0; i < 16; i++) expect(await open({ xff: `203.0.113.${i + 1}` })).toBeTruthy(); expect(await open({ xff: '203.0.113.250' })).toBeUndefined(); // With the peer trusted again, the forwarded address counts once more. One that is no address // counts as the peer's, full by now. process.env.PROXIES = '127.0.0.1'; for (const xff of ['203.0.113.250:1234', '2001:db8::1::1']) expect(await open({ xff })).toBeUndefined(); expect(await open({ xff: '203.0.113.250' })).toBeTruthy(); // Also as a CIDR, however the proxy's address is written. An IPv4 prefix counts in IPv4's 32 // bits, an empty one is no range at all. for (const proxies of ['10.0.0.0/8', '10.0.0.0/']) { process.env.PROXIES = proxies; expect(await open({ xff: '203.0.113.251' })).toBeUndefined(); } for (const [i, proxies] of ['127.0.0.0/8', '::ffff:127.0.0.0/120'].entries()) { process.env.PROXIES = proxies; expect(await open({ xff: `203.0.113.${251 + i}` })).toBeTruthy(); } })); // MAX_SILENT lowered only here: the tests holding 16 silent connections would lose the first ones // on a busy machine. test('closes a connection that announces nothing', () => // One that only holds a slot goes. Terminated, without a close frame it could ignore. withEnv({ MAX_SILENT: '500' }, async () => { const client = await open(); expect(await client.closed).toBe(1006); })); test('keeps a connection that announced', () => // Also past MAX_SILENT, announcing is the first thing a peer does. withEnv({ MAX_SILENT: '500' }, async () => { const client = await open(); const fields = { info_hash: id(), peer_id: id(), left: 0 }; await announce(client, fields); await new Promise((resolve) => setTimeout(resolve, 750)); await announce(client, fields); })); test('answers plain HTTP with a 404 and closes the socket', async () => { const socket = connectTcp(new URL(url).port, '127.0.0.1'); await once(socket, 'connect'); socket.write('GET / HTTP/1.1\r\nHost: x\r\n\r\n'); const [data] = await once(socket, 'data'); expect(String(data)).toContain('404'); // Connection: close, so unlimited sequential 404s on one connection are over. expect(String(data).toLowerCase()).toContain('connection: close'); await once(socket, 'close'); }); test('survives clients resetting refused connections', async () => { for (let i = 0; i < 100; i++) { const socket = connectTcp(new URL(url).port, '127.0.0.1'); await once(socket, 'connect'); socket.write( 'GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\n' + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: https://evil.test\r\n\r\n', ); socket.resetAndDestroy(); } // An unhandled error would have ended this worker. expect(await open()).toBeTruthy(); }); test('keeps no peer that left', async () => { // The root stays and gets the first offer, then every peer gets the next one's offer and leaves. // Held offers used to keep all of them alive, through the root. const hash = id(); const root = { ...(await open()), id: id() }; await announce(root, { info_hash: hash, peer_id: root.id, left: 0 }); let holder = root; for (let i = 0; i < 50; i++) { const peer = { ...(await open()), id: id() }; await announce(peer, { info_hash: hash, peer_id: peer.id, left: 1, offers: [{ offer_id: id(), offer: sdp('offer') }], }); await take(holder, (msg) => msg.offer); // The only sender for the next offer. await announce(peer, { info_hash: hash, peer_id: peer.id, left: 0 }); if (holder === root) await announce(root, { info_hash: hash, peer_id: root.id, left: 1 }); else { holder.ws.close(); await holder.closed; } holder = peer; } // queryObjects collects garbage first. await expect.poll(() => queryObjects(ServerSocket, { format: 'count' })).toBeLessThanOrEqual(2); });