// 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 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}`; const { server } = await import('./tracker.mjs'); if (!server.listening) await once(server, 'listening'); url = `ws://127.0.0.1:${server.address().port}`; }); 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 = []; }); 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 } = {}) { return new Promise((resolve) => { const ws = new WebSocket(url, { headers: { origin, 'x-forwarded-for': ip } }); 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 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, }); }); 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('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('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('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); });