Add an own tracker and STUN server in backend/
backend/ runs both as Docker Compose services, neither is needed: the client works with any WebTorrent tracker and STUN server. The tracker is one file on Node and ws that does only the part of the protocol HellCon uses. It accepts allowed origins only and messages of at most 16 KiB, only announce, one offer per announce and answers only to offers it delivered, once. Forwarded messages are rebuilt from the checked fields. It limits the message rate, the signaling each connection sends, the bytes queued for a peer that stops reading, connection age, connections per IP and in total, and peers per swarm. It logs nothing. coturn runs STUN only on the host network, pinned, read-only and without capabilities beyond the one its binary needs. backend/tracker.spec.mjs tests its rules one by one, e2e.spec.ts sends a real file through it alone in both directions between Chromium and Firefox. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bb69569b51
commit
22d794965e
10 files changed
+665
-51
No files matched your search
@@ -0,0 +1,6 @@
|
||||
FROM node:26.11.1-alpine3.23
|
||||
WORKDIR /app
|
||||
RUN npm install --no-save --omit=dev ws@8.22.0
|
||||
COPY tracker.mjs .
|
||||
USER node
|
||||
CMD ["node", "--max-old-space-size=48", "tracker.mjs"]
|
||||
@@ -0,0 +1,71 @@
|
||||
# HellCon's own servers: a tracker behind Caddy and a STUN server. Neither is needed, the client works
|
||||
# with any WebTorrent tracker and STUN server. Set ORIGINS in .env next to this file, e.g.
|
||||
# ORIGINS=https://hellcon.example.org, then `docker compose up -d --build`. Caddy, in its own compose
|
||||
# project, proxies to the tracker over its network (CADDY_NETWORK, "caddy" unless set):
|
||||
#
|
||||
# tracker.example.org {
|
||||
# reverse_proxy hellcon-tracker:8000
|
||||
# }
|
||||
|
||||
name: hellcon
|
||||
|
||||
x-logging: &logging
|
||||
driver: json-file
|
||||
options: { max-size: 10m, max-file: '2' }
|
||||
|
||||
services:
|
||||
tracker:
|
||||
build: .
|
||||
environment:
|
||||
ORIGINS: ${ORIGINS:?set ORIGINS in .env to where HellCon is served from}
|
||||
networks:
|
||||
caddy:
|
||||
aliases: [hellcon-tracker]
|
||||
init: true
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
cpus: 0.5
|
||||
mem_limit: 96m
|
||||
memswap_limit: 96m
|
||||
pids_limit: 32
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
# On the host network, so Docker's NAT can't change the source address clients get back. UDP 3478
|
||||
# on IPv4 only, stun.example.org needs an A record and no AAAA.
|
||||
coturn:
|
||||
image: coturn/coturn:4.18.0
|
||||
network_mode: host
|
||||
# Off by default since 4.18, their --no- options are gone: DTLS, the admin CLI, the software
|
||||
# attribute, the RFC 3489 MAPPED-ADDRESS and logging each binding request. The image has no config
|
||||
# file, -n would only fail with "Unknown argument".
|
||||
command:
|
||||
- --log-file=stdout
|
||||
- --listening-ip=0.0.0.0
|
||||
- --listening-port=3478
|
||||
- --stun-only
|
||||
- --no-tcp
|
||||
- --no-tls
|
||||
# One per CPU core otherwise, more than cpus allows.
|
||||
- --relay-threads=1
|
||||
# The pid file lands in /var/tmp, coturn can't write /var/run. The image declares /var/lib/coturn
|
||||
# a volume, the tmpfs keeps an anonymous one from piling up.
|
||||
tmpfs: [/var/lib/coturn, /var/tmp]
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
# turnserver has it as file capability, without it the kernel refuses to run it. 3478 doesn't need
|
||||
# it, no-new-privileges keeps it from being granted.
|
||||
cap_add: [NET_BIND_SERVICE]
|
||||
security_opt: [no-new-privileges:true]
|
||||
cpus: 1
|
||||
mem_limit: 128m
|
||||
memswap_limit: 128m
|
||||
pids_limit: 64
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
caddy:
|
||||
external: true
|
||||
name: ${CADDY_NETWORK:-caddy}
|
||||
@@ -0,0 +1,182 @@
|
||||
// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
|
||||
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
|
||||
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
|
||||
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged.
|
||||
import { createServer } from 'node:http';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
// Read on import, 0 picks a free one, see server.address().
|
||||
const PORT = Number(process.env.PORT ?? 8000);
|
||||
// Where HellCon is served from, separated by commas or spaces. Anything else is refused. Read on every
|
||||
// connection, so test files sharing one process can each allow their own.
|
||||
const allowed = (origin) =>
|
||||
(process.env.ORIGINS ?? '')
|
||||
.split(/[\s,]+/)
|
||||
.filter(Boolean)
|
||||
.includes(origin);
|
||||
// Seconds. Peers last as long as their connection, announcing again only resends a receiver's offer,
|
||||
// e.g. to a sender that was busy with another receiver.
|
||||
const INTERVAL = 60;
|
||||
// A sealed SDP is a few KiB.
|
||||
const MAX_MESSAGE = 16 * 1024;
|
||||
// Per connection: messages within RATE_WINDOW, bytes of SDP it gets forwarded and its lifetime. HellCon
|
||||
// gives up a share or a search after 6 minutes.
|
||||
const MAX_MESSAGES = 10;
|
||||
const RATE_WINDOW = 10_000;
|
||||
const MAX_FORWARDED = 64 * 1024;
|
||||
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
|
||||
// a peer that reads never gets near it.
|
||||
const MAX_QUEUED = 32 * 1024;
|
||||
const MAX_AGE = 7 * 60_000;
|
||||
const MAX_CONNECTIONS = 1024;
|
||||
const MAX_PER_IP = 16;
|
||||
// A share has one sender, receivers keep one connection per tracker.
|
||||
const MAX_SWARM = 8;
|
||||
// Offers a sender got and may still answer, the oldest go first.
|
||||
const MAX_PENDING = 32;
|
||||
|
||||
// info_hash → peer_id → peer.
|
||||
const swarms = new Map();
|
||||
const perIp = new Map();
|
||||
let connections = 0;
|
||||
|
||||
// info_hash, peer_id and offer_id are 20 byte binary strings.
|
||||
const isId = (value) => typeof value === 'string' && value.length === 20;
|
||||
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
|
||||
|
||||
// Behind Caddy, the only way in. Caddy replaces any X-Forwarded-For a client sends, the last entry is
|
||||
// its own anyway.
|
||||
function clientIp(req) {
|
||||
return req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
|
||||
}
|
||||
|
||||
function refuse(socket, status) {
|
||||
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
|
||||
}
|
||||
|
||||
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
|
||||
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
|
||||
// wait for its close frame.
|
||||
function send(peer, message) {
|
||||
const data = JSON.stringify(message);
|
||||
if (peer.ws.bufferedAmount + Buffer.byteLength(data) > MAX_QUEUED) return peer.ws.terminate();
|
||||
peer.ws.send(data);
|
||||
}
|
||||
|
||||
// HellCon shows the reason, the connection closes.
|
||||
function reject(peer, reason) {
|
||||
send(peer, { 'failure reason': reason });
|
||||
peer.ws.close();
|
||||
}
|
||||
|
||||
function forward(from, to, message, sdp) {
|
||||
from.forwarded += sdp.length;
|
||||
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
|
||||
send(to, message);
|
||||
}
|
||||
|
||||
function announce(peer, msg) {
|
||||
const { info_hash: hash, peer_id: id } = msg;
|
||||
if (msg.action !== 'announce' || !isId(hash) || !isId(id)) return reject(peer, 'invalid announce');
|
||||
if (!peer.id) {
|
||||
const swarm = swarms.get(hash) ?? new Map();
|
||||
if (swarm.has(id)) return reject(peer, 'peer_id taken');
|
||||
if (swarm.size >= MAX_SWARM) return reject(peer, 'swarm full');
|
||||
swarms.set(hash, swarm.set(id, peer));
|
||||
peer.id = id;
|
||||
peer.hash = hash;
|
||||
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
|
||||
if (msg.event === 'stopped') return peer.ws.close();
|
||||
peer.seeder = msg.left === 0;
|
||||
const swarm = swarms.get(hash);
|
||||
|
||||
if (msg.offers !== undefined) {
|
||||
const [offer, ...more] = Array.isArray(msg.offers) ? msg.offers : [];
|
||||
if (more.length || (offer && (!isId(offer.offer_id) || !isSdp(offer.offer, 'offer')))) {
|
||||
return reject(peer, 'invalid offer');
|
||||
}
|
||||
const senders = [...swarm.values()].filter((other) => other.seeder && other !== peer);
|
||||
const sender = senders[Math.floor(Math.random() * senders.length)];
|
||||
if (offer && sender) {
|
||||
sender.pending.delete(offer.offer_id);
|
||||
sender.pending.set(offer.offer_id, peer);
|
||||
if (sender.pending.size > MAX_PENDING) sender.pending.delete(sender.pending.keys().next().value);
|
||||
const { sdp } = offer.offer;
|
||||
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: offer.offer_id };
|
||||
forward(peer, sender, { ...message, offer: { type: 'offer', sdp } }, sdp);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.answer !== undefined) {
|
||||
if (!isId(msg.to_peer_id) || !isId(msg.offer_id) || !isSdp(msg.answer, 'answer')) {
|
||||
return reject(peer, 'invalid answer');
|
||||
}
|
||||
const receiver = peer.pending.get(msg.offer_id);
|
||||
// An offer it never got, answered already or whose receiver left: dropped, a stray answer doesn't
|
||||
// cost the share.
|
||||
if (receiver?.id === msg.to_peer_id) {
|
||||
peer.pending.delete(msg.offer_id);
|
||||
const { sdp } = msg.answer;
|
||||
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: msg.offer_id };
|
||||
forward(peer, receiver, { ...message, answer: { type: 'answer', sdp } }, sdp);
|
||||
}
|
||||
}
|
||||
|
||||
if (peer.ws.readyState === peer.ws.OPEN) {
|
||||
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash });
|
||||
}
|
||||
}
|
||||
|
||||
function open(ws) {
|
||||
const peer = { ws, id: undefined, hash: undefined, seeder: false, pending: new Map(), forwarded: 0, messages: 0 };
|
||||
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
|
||||
const age = setTimeout(() => ws.close(), MAX_AGE);
|
||||
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
|
||||
ws.on('error', () => {});
|
||||
ws.on('message', (data, binary) => {
|
||||
if (++peer.messages > MAX_MESSAGES) return reject(peer, 'too many messages');
|
||||
let msg;
|
||||
try {
|
||||
msg = binary ? undefined : JSON.parse(data);
|
||||
} catch {}
|
||||
if (!msg || typeof msg !== 'object') return reject(peer, 'invalid message');
|
||||
announce(peer, msg);
|
||||
});
|
||||
ws.on('close', () => {
|
||||
clearInterval(rate);
|
||||
clearTimeout(age);
|
||||
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
|
||||
peer.pending.clear();
|
||||
const swarm = swarms.get(peer.hash);
|
||||
if (swarm?.get(peer.id) !== peer) return;
|
||||
swarm.delete(peer.id);
|
||||
if (!swarm.size) swarms.delete(peer.hash);
|
||||
// Its offers go only to peers of its swarm.
|
||||
for (const other of swarm.values()) {
|
||||
for (const [offerId, receiver] of other.pending) if (receiver === peer) other.pending.delete(offerId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false });
|
||||
export const server = createServer((_, res) => res.writeHead(404).end());
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
|
||||
// client resetting a refused connection would end the process.
|
||||
socket.on('error', () => {});
|
||||
const ip = clientIp(req);
|
||||
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
|
||||
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
|
||||
if ((perIp.get(ip) ?? 0) >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
|
||||
// Counted on the socket, so an upgrade that fails is released too.
|
||||
connections++;
|
||||
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
|
||||
socket.once('close', () => {
|
||||
connections--;
|
||||
const left = perIp.get(ip) - 1;
|
||||
if (left) perIp.set(ip, left);
|
||||
else perIp.delete(ip);
|
||||
});
|
||||
wss.handleUpgrade(req, socket, head, open);
|
||||
});
|
||||
server.listen(PORT);
|
||||
@@ -0,0 +1,335 @@
|
||||
// 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 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);
|
||||
});
|
||||
Reference in new issue
Block a user