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.
This commit is contained in:
jvanvik 2026-11-07 00:42:39 +01:00
parent 2b48a6ad65
commit 95aa9b6532
39 changed files with 2757 additions and 24 deletions

117
scripts/mp-server.js Normal file
View file

@ -0,0 +1,117 @@
#!/usr/bin/env node
// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es
// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build.
// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so
// one process can sit behind a reverse proxy.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { createMp } = require('./lib/mp');
const HELP = `Series of Tubes multiplayer server
node scripts/mp-server.js [options] (npm run mp -- [options])
--port N port to listen on (default 8090, or $PORT)
--host H address to bind (default 127.0.0.1: put a reverse proxy in front)
--data DIR where sessions and saves are kept (default ./mp-data, created if missing)
--site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build)
--base PATH the API's path (default /api/mp; the page's MP_API must match)
--prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60)
--max-sessions N at most N sessions on this server (default 1000)
--max-players N at most N players per session (default 12, at most 12)
--create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64)
--sessions-per-hour N new sessions on the whole server per hour (default 100)
--trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy)
--verbose log one line per API request (never tokens)
--help this text
Storage: DIR/<CODE>.json per session and DIR/<CODE>.<pid>.save per player's save. Back up DIR.
API (JSON; every call but create and join needs Authorization: Bearer <pid>.<token>):
POST /api/mp/sessions {net:{name,home},preset,title?} start a session
POST /api/mp/sessions/:code/join {net:{name,home}} join one
GET /api/mp/sessions/:code roster, cards and feed
PUT /api/mp/sessions/:code/card {card} your public card
PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one)
GET /api/mp/sessions/:code/save your save
POST /api/mp/sessions/:code/feed {text} a chat line
DELETE /api/mp/sessions/:code/me leave
`;
const argv = process.argv.slice(2);
if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); }
const die = (m) => { console.error(`error: ${m}`); process.exit(2); };
const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']);
for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`);
const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; };
const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; };
const PORT = pos('--port', +process.env.PORT || 8090, 65535);
const HOST = opt('--host') || '127.0.0.1';
const DATA = path.resolve(opt('--data') || 'mp-data');
const SITE = opt('--site') ? path.resolve(opt('--site')) : null;
const BASE = opt('--base') || '/api/mp';
// A path, never "//host/..." (which a browser reads as another host).
if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp');
if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`);
if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`);
const mp = createMp({
dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000),
maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100),
trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'),
});
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' };
// The page, the service worker and the files that change between releases are always checked; the rest may be cached.
const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//;
// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either.
const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } };
const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); };
// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE.
function serveSite(req, res) {
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); }
let rel;
try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; }
let file = null;
if (rel !== null && !rel.includes('\0')) {
if (rel.endsWith('/')) rel += 'index.html';
const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel));
if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); }
}
const status = file ? 200 : 404;
if (!file) file = path.join(SITE, '404.html');
if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); }
const r = path.relative(SITE, file).split(path.sep).join('/');
res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' });
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).on('error', () => res.destroy()).pipe(res);
}
const server = http.createServer((req, res) => {
try {
if (mp.handle(req, res)) return;
if (SITE) return serveSite(req, res);
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"not found"}');
} catch (e) {
// One line, never a stack: whatever went wrong, a request should not be able to fill the log.
console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`);
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"server error"}');
}
});
server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } });
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
server.listen(PORT, HOST, () => {
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`);
});
setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref();
const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);