seriesoftubes/tests/mp-server.test.js
jvanvik 95aa9b6532 Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard
Off unless the page is built with MP_API set (MP_API=/api/mp npm run
build): a plain build has no door, no chip and makes no requests. The
session server is scripts/mp-server.js (npm run mp), plain node:http,
which can also serve the built site so one process sits behind the
reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups.

A session has a six-character code, one seed and one rules preset, so
every player starts in the same world, and up to twelve players with
their own AS numbers. Saves go to the server on a new game day at most
every 15 s and when the page hides, ordered by a sequence number (409 on
a stale push, and the player picks which one to keep). Tokens live in
localStorage, never in the save; the server keeps only their hash. A
#mp= link moves a network to another device. The session panel shows
the leaderboard, the feed and a short chat; each player's public card
(tier, POPs, links, exchanges, transit, peak, customers, score) carries
what in-game peering between players will need next.

Server limits: body sizes, one upload per player, uploads per address
and in total, sessions per hour, wrong-code lockout; addresses counted
per IPv6 /64, X-Forwarded-For only with --trust-proxy.
2026-11-07 00:42:39 +01:00

450 lines
32 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The multiplayer server (scripts/mp-server.js, docs/MULTIPLAYER.md), run for real on a free port with its own data
// folder: sessions, joining, who may read and write what, saves that never overwrite a newer one, cards cleaned of
// junk, limits, leaving, data that survives a restart, and the built site served without escaping its folder. The
// tests of what happens while a request is still on its way run the API in this process (inproc), where a request can
// be held half-sent and the limits made small.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { spawn, execFileSync } = require('node:child_process');
const { until, freePort, kill } = require('./net');
const { createMp, cleanCard, addrKey, limiter } = require('../scripts/lib/mp');
const root = path.join(__dirname, '..');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-'));
const children = new Set();
test.after(async () => { for (const c of children) await kill(c); fs.rmSync(tmp, { recursive: true, force: true }); });
async function start(opts = {}) {
const port = await freePort(), data = opts.data || fs.mkdtempSync(path.join(tmp, 'data-'));
const args = ['scripts/mp-server.js', '--port', String(port), '--data', data, '--create-per-hour', '50', ...(opts.args || [])];
const child = spawn(process.execPath, args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
children.add(child);
let out = '';
child.stdout.on('data', (b) => { out += b; });
child.stderr.on('data', (b) => { out += b; });
assert.ok(await until(() => /multiplayer: http/.test(out) || child.exitCode !== null), 'the server starts');
assert.equal(child.exitCode, null, out);
const url = `http://127.0.0.1:${port}`;
const api = async (method, p, body, auth, headers = {}) => {
const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body) });
const t = await r.text();
let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ }
return { status: r.status, json: j, type: r.headers.get('content-type'), text: t };
};
return { child, port, url, data, api, out: () => out, stop: async () => { await kill(child); children.delete(child); } };
}
// A raw request, so paths reach the server exactly as written (fetch would tidy up "..").
const raw = (port, p) => new Promise((res, rej) => {
const r = http.request({ host: '127.0.0.1', port, path: p, method: 'GET' }, (x) => { let b = ''; x.on('data', (c) => { b += c; }); x.on('end', () => res({ status: x.statusCode, body: b, type: x.headers['content-type'] })); });
r.on('error', rej); r.end();
});
const make = (api, name = 'Packet Pals', home = 'fra', extra = {}) => api('POST', '/sessions', { net: { name, home }, preset: 'oncall', ...extra });
// The API in this process, with its own options (small limits), on a free port.
async function inproc(t, opts = {}) {
const dir = opts.dir || fs.mkdtempSync(path.join(tmp, 'data-'));
const mp = createMp({ dir, log: () => {}, ...opts });
const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => { server.closeAllConnections(); server.close(r); }));
const port = server.address().port, url = `http://127.0.0.1:${port}`;
const api = async (method, p, body, auth, headers = {}) => {
const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });
const t = await r.text();
let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ }
return { status: r.status, json: j };
};
return { mp, dir, port, api };
}
// A request sent all but the last byte of its body: it stays on its way until release().
function held(port, method, p, body, auth, headers = {}) {
const b = Buffer.from(JSON.stringify(body));
let r;
const done = new Promise((res, rej) => {
r = http.request({ host: '127.0.0.1', port, path: '/api/mp' + p, method, headers: { 'content-type': 'application/json', 'content-length': b.length, ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers } },
(x) => { let t = ''; x.on('data', (c) => { t += c; }); x.on('end', () => { let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } res({ status: x.statusCode, json: j }); }); });
r.on('error', rej);
r.write(b.subarray(0, b.length - 1));
});
return { done, release: () => { r.end(b.subarray(b.length - 1)); return done; } };
}
const joinAs = (api, code, name, headers) => api('POST', `/sessions/${code}/join`, { net: { name, home: 'ams' } }, null, headers);
test('mp server: --help documents it; --base is a path on this server, never another host', () => {
const t = execFileSync(process.execPath, ['scripts/mp-server.js', '--help'], { cwd: root, encoding: 'utf8' });
for (const k of ['--port', '--host', '--data', '--site', '--prune-days', '--trust-proxy', '--sessions-per-hour', 'Authorization: Bearer', '/api/mp/sessions/:code/save']) assert.ok(t.includes(k), k);
for (const b of ['//evil-host/mp', '//api', 'api/mp', '/api/mp/']) assert.throws(() => execFileSync(process.execPath, ['scripts/mp-server.js', '--base', b, '--port', '1'], { cwd: root, stdio: 'pipe' }), /--base must be a path/, b);
});
test('mp server: start, join, roster; names cleaned; codes typed any way', async () => {
const s = await start();
const a = await make(s.api, ' <img src=x onerror=alert(1)> & "Co" ', 'fra', { preset: 'bgp', title: 'Friday <b>night</b>', avoid: [200000, 200001] });
assert.equal(a.status, 201);
assert.match(a.json.code, /^[0-9A-HJKMNP-TV-Z]{6}$/);
assert.match(a.json.pid, /^[a-z0-9]{8}$/);
assert.match(a.json.token, /^[0-9a-f]{64}$/);
assert.ok(Number.isInteger(a.json.seed) && a.json.seed >= -(2 ** 31) && a.json.seed < 2 ** 31);
assert.ok(a.json.asn >= 200000 && a.json.asn <= 214999);
assert.equal(a.json.preset, 'bgp');
assert.equal(a.json.title, 'Friday bnight/b');
// Joined by the code as a person types it: lower case, with a dash.
const typed = (a.json.code.slice(0, 3) + '-' + a.json.code.slice(3)).toLowerCase();
const b = await s.api('POST', `/sessions/${typed}/join`, { net: { name: 'Bee', home: 'nyc' }, preset: 'soft' });
assert.equal(b.status, 200);
assert.equal(b.json.code, a.json.code);
assert.equal(b.json.seed, a.json.seed, 'one world: the same seed');
assert.equal(b.json.preset, 'bgp', 'and the creator\'s rules');
assert.notEqual(b.json.asn, a.json.asn);
assert.notEqual(b.json.color, a.json.color);
const r = await s.api('GET', `/sessions/${a.json.code}`, undefined, a.json);
assert.equal(r.status, 200);
assert.equal(r.type, 'application/json; charset=utf-8');
assert.deepEqual(r.json.players.map((p) => p.name), ['img src=x onerror=alert(1) Co', 'Bee']);
assert.ok(r.json.players.every((p) => !('th' in p) && !('token' in p) && !('sv' in p)), 'no secrets in the roster');
assert.deepEqual(r.json.feed.map((f) => f.k), ['join', 'join']);
assert.ok(!JSON.stringify(r.json).includes(a.json.token));
// Junk names and homes are refused.
for (const net of [{ name: ' ', home: 'fra' }, { name: '<>&', home: 'fra' }, { name: 'ok', home: '../x' }, { name: 'ok' }]) assert.equal((await s.api('POST', '/sessions', { net, preset: 'oncall' })).status, 400, JSON.stringify(net));
assert.equal((await s.api('POST', '/sessions', { net: { name: 'x', home: 'fra' }, preset: 'sandbox' })).status, 400, 'only the Normal presets');
assert.equal((await s.api('POST', '/sessions', { net: { name: 'x'.repeat(80), home: 'fra' }, preset: 'soft' })).json.pid.length, 8);
await s.stop();
});
test('mp server: every call but start and join needs the player\'s token', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
const p = `/sessions/${a.code}`;
assert.equal((await s.api('GET', p)).status, 401);
assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: b.token })).status, 401, 'someone else\'s token');
assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: '0'.repeat(64) })).status, 401);
assert.equal((await s.api('GET', p, undefined, { pid: 'zzzzzzzz', token: a.token })).status, 401);
assert.equal((await s.api('GET', p, undefined, null, { authorization: 'Bearer nonsense' })).status, 401);
assert.equal((await s.api('PUT', p + '/card', { card: {} })).status, 401);
assert.equal((await s.api('PUT', p + '/save', { seq: 1, at: 1, data: '{}' })).status, 401);
assert.equal((await s.api('GET', p + '/save')).status, 401);
assert.equal((await s.api('POST', p + '/feed', { text: 'hi' })).status, 401);
assert.equal((await s.api('DELETE', p + '/me')).status, 401);
assert.equal((await s.api('GET', p, undefined, a)).status, 200);
assert.equal((await s.api('GET', '/sessions/ZZZZZZ', undefined, a)).status, 404);
assert.equal((await s.api('DELETE', p, undefined, a)).status, 405);
assert.equal((await s.api('GET', '/nope')).status, 404);
await s.stop();
});
test('mp server: a save never overwrites a newer one unless forced', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
const p = `/sessions/${a.code}/save`;
assert.equal((await s.api('GET', p, undefined, a)).status, 404, 'nothing saved yet');
const s1 = await s.api('PUT', p, { seq: 1, at: 1000, data: '{"v":1,"day":3}' }, a);
assert.equal(s1.status, 200);
assert.equal(s1.json.seq, 1);
assert.equal(s1.json.roster.players.length, 2, 'the roster rides along');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 1, at: 1000, data: '{"v":1,"day":3}' });
assert.equal((await s.api('GET', p, undefined, b)).status, 404, 'only your own save');
const stale = await s.api('PUT', p, { seq: 1, at: 2000, data: '{"v":1,"day":1}' }, a);
assert.equal(stale.status, 409);
assert.equal(stale.json.seq, 1);
assert.equal((await s.api('PUT', p, { seq: 0, at: 1, data: '{}' }, a)).status, 400);
assert.equal((await s.api('PUT', p, { seq: 1.5, at: 1, data: '{}' }, a)).status, 400);
assert.equal((await s.api('PUT', p, { seq: 9, at: 1, data: 'not a save' }, a)).status, 400);
const g = await s.api('PUT', p, { seq: 2, at: 3000, data: 'gz:H4sIAAAA' }, a);
assert.equal(g.json.seq, 2, 'compressed saves are kept as they are');
const f = await s.api('PUT', p, { seq: 1, at: 4000, data: '{"v":1,"day":9}', force: true }, a);
assert.equal(f.status, 200);
assert.equal(f.json.seq, 3, 'forced: it becomes the newest');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 3, at: 4000, data: '{"v":1,"day":9}' });
await s.stop();
});
test('mp server: cards keep only what the leaderboard needs, and tell the feed about Tier 1', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
const junk = { day: 1e12, name: 'Evil', asn: 1, tier: 't0', t1: 'yes', lvl: -5, pops: ['fra', 'fra', '<script>', 'nyc', 7], links: [['fra', 'nyc', 1e99], ['fra', 'fra', 5], ['a"b', 'nyc', 1], 'x', ['ams', 'fra', 'NaN']],
ix: ['fra', 'fra~2', '../etc'], transit: ['cog', 'x'.repeat(40)], ppol: 'evil', reach: 7, peak: -3, served: 'lots', cust: 3.7, rev: 1e20, cashB: 99, score: -1, extra: { deep: true }, __proto__x: 1 };
const r = await s.api('PUT', `/sessions/${a.code}/card`, { card: junk }, a);
assert.equal(r.status, 200);
const c = r.json.players.find((p) => p.pid === a.pid).card;
assert.deepEqual(Object.keys(c).sort(), ['cashB', 'cust', 'day', 'ix', 'links', 'lvl', 'peak', 'pops', 'ppol', 'reach', 'rev', 'score', 'served', 't1', 'tier', 'transit']);
assert.deepEqual(c, { day: 1e7, tier: 't3', t1: false, lvl: 0, pops: ['fra', 'nyc'], links: [['fra', 'nyc', 1e7], ['ams', 'fra', 0]], ix: ['fra', 'fra~2'], transit: ['cog'], ppol: 'open', reach: 1, peak: 0, served: 0, cust: 4, rev: 1e13, cashB: 20, score: 0 });
assert.equal(r.json.players.find((p) => p.pid === a.pid).name, 'Packet Pals', 'the name is the server\'s, not the card\'s');
assert.equal((await s.api('PUT', `/sessions/${a.code}/card`, { card: [1, 2] }, a)).status, 400);
// Tier 2, then Tier 1: the first in the session gets the headline, the next one a plain line.
await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't2' } }, a);
await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't1', t1: true } }, a);
await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't1', t1: true } }, a);
const f = (await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't1', t1: true } }, b)).json.feed;
assert.deepEqual(f.map((x) => x.k), ['join', 'join', 't2', 't1first', 't1']);
assert.equal(f[3].pid, a.pid);
// A network that drops out (transit again, a de-peering) and comes back is not news again: each milestone once.
for (const c of [{ tier: 't2' }, { tier: 't1', t1: true }, { tier: 't3' }, { tier: 't2' }, { tier: 't1', t1: true }]) for (const who of [a, b]) assert.equal((await s.api('PUT', `/sessions/${a.code}/card`, { card: c }, who)).status, 200);
const again = (await s.api('GET', `/sessions/${a.code}`, undefined, a)).json.feed;
assert.deepEqual(again.map((x) => x.k), ['join', 'join', 't2', 't1first', 't1'], 'the first Tier 1 is never "Tier 1 too"');
await s.stop();
});
test('mp server: chat lines are cleaned, capped and rate-limited; the feed keeps the last 100', async () => {
const s = await start();
const a = (await make(s.api)).json;
const p = `/sessions/${a.code}/feed`;
const r = await s.api('POST', p, { text: ' hello\u0000‮ <b>world</b> ' + 'x'.repeat(300) }, a);
assert.equal(r.status, 200);
const line = r.json.feed.at(-1);
assert.equal(line.k, 'chat');
assert.equal(line.text.length, 200);
assert.ok(line.text.startsWith('hello <b>world</b> x'), 'control characters go; the page escapes the rest');
assert.equal((await s.api('POST', p, { text: 'again' }, a)).status, 429, 'one line a second');
assert.equal((await s.api('POST', p, { text: ' ' }, a)).status, 400);
await s.stop();
});
test('mp server: limits: body sizes, JSON only, odd codes, twelve players', async () => {
const s = await start();
const a = (await make(s.api)).json;
const big = await s.api('PUT', `/sessions/${a.code}/save`, { seq: 1, at: 1, data: '{' + 'x'.repeat(5 * 1024 * 1024) }, a);
assert.equal(big.status, 413, 'a save over 4 MB is refused');
assert.equal((await s.api('PUT', `/sessions/${a.code}/card`, { card: { pops: Array(5000).fill('fra') } }, a)).status, 413, 'small calls take small bodies');
assert.equal((await s.api('POST', '/sessions', 'name=x', null, { 'content-type': 'application/x-www-form-urlencoded' })).status, 415);
assert.equal((await s.api('POST', '/sessions', '{"net":', null)).status, 400);
assert.equal((await s.api('POST', '/sessions', '[1]', null)).status, 400);
// A code is checked before it is ever a file name.
for (const p of ['/api/mp/sessions/..%2F..%2Fetc%2Fpasswd', '/api/mp/sessions/%2e%2e', '/api/mp/sessions/../../package.json', `/api/mp/sessions/${a.code}%00/save`, '/api/mp/sessions/%E0%A4%A']) {
const x = await raw(s.port, p);
assert.ok([404, 400].includes(x.status), `${p}: ${x.status}`);
assert.doesNotMatch(x.body, /root:|"name": "seriesoftubes"/);
}
const join = (i) => s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'P' + i, home: 'ams' } });
for (let i = 2; i <= 12; i++) assert.equal((await join(i)).status, 200, `player ${i}`);
const full = await join(13);
assert.equal(full.status, 409);
assert.equal(full.json.full, true);
const ro = (await s.api('GET', `/sessions/${a.code}`, undefined, a)).json;
assert.equal(ro.players.length, 12);
assert.equal(new Set(ro.players.map((p) => p.asn)).size, 12, 'every AS number its own');
assert.equal(new Set(ro.players.map((p) => p.color)).size, 12, 'and every colour');
assert.deepEqual(fs.readdirSync(s.data).filter((f) => !/^[0-9A-Z]{6}\.json$/.test(f)), [], 'nothing but session files in the data folder');
await s.stop();
});
test('mp server: leaving removes the player and their save; the last one out closes the session', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
await s.api('PUT', `/sessions/${a.code}/save`, { seq: 1, at: 1, data: '{}' }, b);
assert.ok(fs.existsSync(path.join(s.data, `${a.code}.${b.pid}.save`)));
assert.equal((await s.api('DELETE', `/sessions/${a.code}/me`, undefined, b)).status, 200);
assert.ok(!fs.existsSync(path.join(s.data, `${a.code}.${b.pid}.save`)), 'their save is gone');
assert.equal((await s.api('GET', `/sessions/${a.code}`, undefined, b)).status, 401, 'and so is their access');
const ro = (await s.api('GET', `/sessions/${a.code}`, undefined, a)).json;
assert.deepEqual(ro.players.map((p) => p.pid), [a.pid]);
assert.equal(ro.feed.at(-1).k, 'leave');
assert.equal((await s.api('DELETE', `/sessions/${a.code}/me`, undefined, a)).status, 200);
assert.equal((await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Late', home: 'nyc' } })).status, 404, 'an empty session is gone');
assert.ok(!fs.existsSync(path.join(s.data, `${a.code}.json`)));
await s.stop();
});
test('mp server: data survives a restart; sessions nobody touched for too long are pruned', async () => {
const s = await start();
const a = (await make(s.api)).json;
await s.api('PUT', `/sessions/${a.code}/save`, { seq: 4, at: 42, data: '{"v":1}', card: { day: 12, pops: ['fra'], tier: 't2' } }, a);
await s.api('PUT', `/sessions/${a.code}/card`, { card: { day: 13, pops: ['fra'], tier: 't2' } }, a);
// An old session left behind, untouched for 100 days.
const old = path.join(s.data, 'ABCDEF.json');
fs.writeFileSync(old, JSON.stringify({ v: 1, code: 'ABCDEF', players: [], feed: [] }));
fs.writeFileSync(path.join(s.data, 'ABCDEF.abcdabcd.save'), '{}');
const t = (Date.now() - 100 * 86400000) / 1000;
fs.utimesSync(old, t, t);
await s.stop();
const s2 = await start({ data: s.data, args: ['--prune-days', '60'] });
assert.ok(!fs.existsSync(old), 'the old session is pruned');
assert.ok(!fs.existsSync(path.join(s.data, 'ABCDEF.abcdabcd.save')), 'with its saves');
const ro = await s2.api('GET', `/sessions/${a.code}`, undefined, a);
assert.equal(ro.status, 200, 'the token still works');
assert.equal(ro.json.players[0].card.day, 13, 'a card is written a moment later, and before the server stops');
assert.deepEqual((await s2.api('GET', `/sessions/${a.code}/save`, undefined, a)).json, { seq: 4, at: 42, data: '{"v":1}' });
assert.equal((await s2.api('PUT', `/sessions/${a.code}/save`, { seq: 4, at: 43, data: '{}' }, a)).status, 409, 'and the sequence with it');
await s2.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't3' } }, a);
const fd = (await s2.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't2' } }, a)).json.feed;
assert.deepEqual(fd.map((x) => x.k), ['join', 't2'], 'and what the feed already told');
await s2.stop();
});
test('mp server: --site serves the built game like GitHub Pages, and nothing outside it', async () => {
const site = fs.mkdtempSync(path.join(tmp, 'site-'));
fs.writeFileSync(path.join(site, 'index.html'), '<!doctype html><title>game</title>');
fs.writeFileSync(path.join(site, '404.html'), '<!doctype html><title>lost</title>');
fs.writeFileSync(path.join(site, 'sw.js'), '// sw');
fs.mkdirSync(path.join(site, 'i18n'));
fs.writeFileSync(path.join(site, 'i18n', 'de.js'), '// de');
fs.writeFileSync(path.join(tmp, 'secret.txt'), 'secret');
const s = await start({ args: ['--site', site] });
const home = await raw(s.port, '/');
assert.equal(home.status, 200);
assert.match(home.type, /^text\/html/);
assert.match(home.body, /game/);
const js = await raw(s.port, '/i18n/de.js?v=1');
assert.equal(js.status, 200);
assert.match(js.type, /^text\/javascript/);
const miss = await raw(s.port, '/nope.html');
assert.equal(miss.status, 404);
assert.match(miss.body, /lost/);
for (const p of ['/../secret.txt', '/%2e%2e/secret.txt', '/..%2fsecret.txt', '/i18n/..%2F..%2Fsecret.txt', '/%2e%2e%5csecret.txt']) {
const x = await raw(s.port, p);
assert.notEqual(x.body, 'secret', p);
}
// A path the file system cannot even look at (a name too long for it) is simply not there: the 404 page, no log.
for (const p of ['/' + 'a'.repeat(300), '/x/../../' + 'a'.repeat(300) + '/b', '/i18n/' + 'b'.repeat(4000)]) {
const x = await raw(s.port, p);
assert.equal(x.status, 404, p.slice(0, 20));
assert.match(x.body, /lost/);
}
assert.doesNotMatch(s.out(), /ENAMETOOLONG|\n\s+at /, 'no stack traces from what a client asked');
assert.equal((await s.api('POST', '/sessions', { net: { name: 'x', home: 'fra' }, preset: 'soft' })).status, 201, 'the API rides along');
await s.stop();
});
test('mp server: saves and cards are throttled: one save at a time per player, a few uploads at once, a few a minute', async (t) => {
const s = await inproc(t, { trustProxy: true, maxUploads: 3, maxUploadsPerAddress: 2, savesPerMinute: 4, cardsPerMinute: 3, persistMs: 60000 });
const at = (n) => ({ 'x-forwarded-for': `198.51.100.${n}` });
const a = (await s.api('POST', '/sessions', { net: { name: 'Alpha', home: 'fra' }, preset: 'oncall' }, null, at(1))).json, code = a.code;
const [b, c, d] = await Promise.all(['Bee', 'Cee', 'Dee'].map(async (n, i) => (await joinAs(s.api, code, n, at(i + 1))).json));
const p = `/sessions/${code}/save`, save = (seq) => ({ seq, at: seq, data: `{"v":1,"day":${seq}}` });
// A save on its way holds its place: the same player's next one waits its turn (a token costs nothing, a place does).
const h1 = held(s.port, 'PUT', p, save(1), a, at(1));
assert.ok(await until(() => s.mp.uploads() === 1));
const again = await s.api('PUT', p, save(2), a, at(1));
assert.equal(again.status, 429);
assert.match(again.json.error, /still on its way/);
// Another player from the same address may upload too; a third one from there waits; the whole server takes three.
const h2 = held(s.port, 'PUT', p, save(1), b, at(1));
assert.ok(await until(() => s.mp.uploads() === 2));
assert.equal((await s.api('PUT', p, save(1), c, at(1))).status, 503, 'two at once from one address');
const h3 = held(s.port, 'PUT', p, save(1), c, at(2));
assert.ok(await until(() => s.mp.uploads() === 3));
const busy = await s.api('PUT', p, save(1), d, at(3));
assert.equal(busy.status, 503, 'three at once on the server');
assert.equal(busy.json.busy, true, 'and says it is only busy, so the game waits quietly');
for (const h of [h1, h2, h3]) assert.equal((await h.release()).status, 200);
assert.equal(s.mp.uploads(), 0, 'and the places are free again');
// Not too often: four saves a minute here (the game sends one every 15 s at most).
for (const sq of [2, 3, 4]) assert.equal((await s.api('PUT', p, save(sq), a, at(1))).status, 200);
const often = await s.api('PUT', p, save(5), a, at(1));
assert.equal(often.status, 429);
assert.equal((await s.api('GET', p, undefined, a)).json.seq, 4, 'the refused one changed nothing');
// Stored as it was sent: the save's own text, not wrapped and copied again.
assert.equal(fs.readFileSync(path.join(s.dir, `${code}.${a.pid}.save`), 'utf8'), '{"v":1,"day":4}');
// Cards: three a minute here; their session is written once a moment later, not on every push.
const file = () => JSON.parse(fs.readFileSync(path.join(s.dir, code + '.json'), 'utf8')).players.find((x) => x.pid === b.pid).card;
for (const day of [5, 6, 7]) assert.equal((await s.api('PUT', `/sessions/${code}/card`, { card: { day } }, b, at(1))).status, 200);
assert.equal((await s.api('PUT', `/sessions/${code}/card`, { card: { day: 8 } }, b, at(1))).status, 429);
assert.equal(file(), null, 'not written on every push');
await s.mp.flush();
assert.equal(file().day, 7, 'but before the server stops');
});
test('mp server: wrong codes from an address stop guessing there, never the players of a session there', async (t) => {
const s = await inproc(t, { missesPerHour: 5 });
const a = (await make(s.api)).json, p = `/sessions/${a.code}`, fake = { pid: a.pid, token: '0'.repeat(64) };
assert.equal((await s.api('PUT', p + '/save', { seq: 1, at: 1, data: '{}' }, a)).status, 200);
// A wrong token on a real code is no guess at codes: it does not count.
for (let i = 0; i < 8; i++) assert.equal((await s.api('GET', p, undefined, fake)).status, 401);
for (let i = 0; i < 5; i++) assert.equal((await s.api('GET', `/sessions/ZZZZZ${i}`)).status, 404, `wrong code ${i}`);
// Locked out here: the player who has the code and its token carries on as before.
assert.equal((await s.api('PUT', p + '/save', { seq: 2, at: 2, data: '{}' }, a)).status, 200);
assert.equal((await s.api('GET', p + '/save', undefined, a)).status, 200);
assert.equal((await s.api('GET', p, undefined, a)).status, 200);
assert.equal((await s.api('PUT', p + '/card', { card: { day: 2 } }, a)).status, 200);
assert.equal((await s.api('POST', p + '/feed', { text: 'still here' }, a)).status, 200);
// Everyone else from here gets one and the same answer, whichever way they ask: it tells nobody which codes exist.
const tries = [
s.api('GET', p), s.api('GET', p, undefined, fake), s.api('GET', p, undefined, null, { authorization: 'Bearer nonsense' }),
s.api('GET', '/sessions/ZZZZZZ', undefined, a), s.api('GET', '/sessions/ZZZZZZ', undefined, fake),
s.api('POST', p + '/join', { net: { name: 'Late', home: 'nyc' } }), s.api('POST', '/sessions/ZZZZZZ/join', { net: { name: 'Late', home: 'nyc' } }),
];
const got = await Promise.all(tries);
assert.deepEqual(got.map((x) => x.status), got.map(() => 429));
assert.equal(new Set(got.map((x) => JSON.stringify(x.json))).size, 1);
});
test('mp server: a save that is refused, or cannot be written, leaves the server\'s number as it was', async (t) => {
const s = await inproc(t);
const a = (await make(s.api)).json, p = `/sessions/${a.code}/save`;
assert.equal((await s.api('PUT', p, { seq: 1, at: 1, data: '{"v":1,"day":1}' }, a)).status, 200);
assert.equal((await s.api('PUT', p, { seq: 2, at: 2, data: '{"v":1,"day":2}', card: 5 }, a)).status, 400, 'a bad card');
const ok = await s.api('PUT', p, { seq: 2, at: 2, data: '{"v":1,"day":2}' }, a);
assert.equal(ok.status, 200, 'the same number again: the refused one never counted');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 2, at: 2, data: '{"v":1,"day":2}' });
if (process.getuid && process.getuid() === 0) return;// root writes anywhere: no way to make the disk refuse here
fs.chmodSync(s.dir, 0o555);
let r;
try { r = await s.api('PUT', p, { seq: 3, at: 3, data: '{"v":1,"day":3}' }, a); } finally { fs.chmodSync(s.dir, 0o755); }
assert.equal(r.status, 500, 'the disk said no');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 2, at: 2, data: '{"v":1,"day":2}' }, 'the server does not claim a save it does not have');
assert.equal((await s.api('PUT', p, { seq: 3, at: 3, data: '{"v":1,"day":3}' }, a)).status, 200, 'and the player is not told someone else saved');
await s.mp.flush();
assert.equal(JSON.parse(fs.readFileSync(path.join(s.dir, a.code + '.json'), 'utf8')).players[0].sv.seq, 3);
assert.equal(fs.readFileSync(path.join(s.dir, `${a.code}.${a.pid}.save`), 'utf8'), '{"v":1,"day":3}');
});
test('mp server: an IPv6 /64 counts as one address, the server fills slowly, and the limits\' memory stays bounded', async (t) => {
assert.equal(addrKey('2001:db8:1:2::5'), '2001:db8:1:2::/64');
assert.equal(addrKey('2001:DB8:1:2:aa:bb:cc:dd'), '2001:db8:1:2::/64');
assert.equal(addrKey('2001:db8::1'), '2001:db8:0:0::/64');
assert.equal(addrKey('::ffff:198.51.100.7'), '198.51.100.7', 'an IPv4 address in IPv6 clothes');
assert.equal(addrKey('fe80::1%eth0'), 'fe80:0:0:0::/64');
for (const bad of ['', 'nonsense', '1.2.3', '::g']) assert.equal(addrKey(bad), null, bad);
const s = await inproc(t, { trustProxy: true, createPerHour: 3, sessionsPerHour: 8 });
const mk = async (ip) => (await s.api('POST', '/sessions', { net: { name: 'X', home: 'fra' }, preset: 'soft' }, null, { 'x-forwarded-for': ip })).status;
const one64 = [];
for (let i = 1; i <= 6; i++) one64.push(await mk(`2001:db8:1:2::${i}`));
assert.deepEqual(one64, [201, 201, 201, 429, 429, 429], 'six addresses of one /64 are one address');
const v4 = [];
for (const ip of ['198.51.100.7', '::ffff:198.51.100.7', '198.51.100.7', '::ffff:198.51.100.7']) v4.push(await mk(ip));
assert.deepEqual(v4, [201, 201, 201, 429]);
assert.equal(await mk('2001:db8:1:3::1'), 201, 'the next /64 is someone else');
assert.equal(await mk('2001:db8:1:4::1'), 201);
assert.equal(await mk('2001:db8:1:5::1'), 503, 'eight new sessions an hour here, from everywhere together');
// Keys go oldest first above the cap, and once nobody used them for a whole window: no call walks them all.
const L = limiter(2, 1000, 50);
for (let i = 0; i < 1000; i++) L.ok('k' + i, i);
assert.ok(L.size() <= 51, `${L.size()} keys`);
assert.equal(L.ok('k999', 1000), true);
assert.equal(L.ok('k999', 1000), false, 'still counting');
L.ok('late', 5000);
assert.equal(L.size(), 1, 'the old ones went');
});
test('mp server: a save still on its way when its player leaves is dropped, and never brings the session back', async (t) => {
const s = await inproc(t);
const a = (await make(s.api)).json, b = (await joinAs(s.api, a.code, 'Bee')).json, p = `/sessions/${a.code}`;
const big = { seq: 1, at: 1, data: '{"x":"' + 'y'.repeat(100000) + '"}', card: { tier: 't2' } };
const hb = held(s.port, 'PUT', p + '/save', big, b);
assert.ok(await until(() => s.mp.uploads() === 1));
assert.equal((await s.api('DELETE', p + '/me', undefined, b)).status, 200);
assert.equal((await hb.release()).status, 401, 'the player left meanwhile');
await s.mp.flush();
assert.deepEqual(fs.readdirSync(s.dir), [a.code + '.json'], 'no save left behind');
assert.deepEqual((await s.api('GET', p, undefined, a)).json.feed.map((f) => f.k), ['join', 'join', 'leave'], 'nor news from someone gone');
// The last one out, with a save on its way.
const ha = held(s.port, 'PUT', p + '/save', big, a);
assert.ok(await until(() => s.mp.uploads() === 1));
assert.equal((await s.api('DELETE', p + '/me', undefined, a)).status, 200);
assert.equal((await ha.release()).status, 401);
await s.mp.flush();
assert.deepEqual(fs.readdirSync(s.dir), [], 'the session is gone, files and all');
assert.equal(createMp({ dir: s.dir, log: () => {} }).sessions(), 0, 'and stays gone after a restart');
});
test('mp server: a card padded with copies costs no more than an honest one', () => {
const ids = Array.from({ length: 499 }, (_, i) => 'c' + i);
let looked = 0;
const spy = (a) => new Proxy(a, { get(o, k) { if (typeof k === 'string' && /^\d+$/.test(k)) looked++; return o[k]; } });
const c = cleanCard({ pops: spy([...ids, ...Array(400000).fill('c498')]), ix: spy([...ids, ...Array(400000).fill('c498')]), links: spy(Array(400000).fill(['fra', 'fra', 1])) });
assert.deepEqual(c.pops, ids);
assert.deepEqual(c.ix, ids);
assert.deepEqual(c.links, []);
assert.ok(looked <= 2 * 4 * 500 + 1200, `${looked} entries looked at`);
});