// 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, ' & "Co" ', 'fra', { preset: 'bgp', title: 'Friday night', 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', '