seriesoftubes/scripts/lib/mp.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

448 lines
26 KiB
JavaScript
Raw Permalink 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 API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the
// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies.
// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the
// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API.
//
// Storage: one JSON file per session (DIR/<CODE>.json: settings, players, cards, feed) and one file per player's save
// (DIR/<CODE>.<pid>.save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are
// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes
// part of a file name, and so is a player id.
const fs = require('node:fs');
const path = require('node:path');
const net = require('node:net');
const crypto = require('node:crypto');
// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up.
const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
const PID_RE = /^[a-z0-9]{8}$/;
const TOKEN_RE = /^[0-9a-f]{64}$/;
const PRESETS = ['soft', 'freeze', 'oncall', 'bgp'];
const PPOL = ['open', 'selective', 'closed'];
const TIERS = ['t1', 't2', 't3'];
const ASN_LO = 200000, ASN_HI = 214999;
const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d'];
const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON)
const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 };
const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places)
const FEED_MAX = 100, CHAT_MAX = 200;
const DAY = 86400000;
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant.
function normCode(s) {
if (typeof s !== 'string' || s.length > 20) return null;
const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0');
return CODE_RE.test(c) ? c : null;
}
const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3);
const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; };
const randPid = () => crypto.randomBytes(4).toString('hex');
const sha = (t) => crypto.createHash('sha256').update(t).digest();
// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one
// space between words, at most max characters (whole characters, never half an emoji).
function cleanText(v, max) {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩<>&"'`]/g, '').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, max).join('').trim();
}
const cleanChat = (v) => {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, CHAT_MAX).join('').trim();
};
const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); };
const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d));
// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one.
const ids = (v, re, max) => {
if (!Array.isArray(v)) return [];
const out = new Set();
for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; }
return [...out];
};
const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/;
/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its
catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */
function cleanCard(c) {
if (!c || typeof c !== 'object' || Array.isArray(c)) return null;
const links = [];
if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) {
if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue;
links.push([l[0], l[1], num(l[2], 0, 1e7)]);
if (links.length >= 300) break;
}
return {
day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99),
pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64),
ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9),
cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15),
};
}
/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the
order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above
cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */
function limiter(n, ms, cap = 20000) {
const m = new Map();
const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; };
return {
// Counts one more, unless the key is already at its limit.
ok(k, now) {
const a = live(k, now), ok = a.length < n;
if (ok) a.push(now);
m.delete(k); m.set(k, a);
for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; }
return ok;
},
full: (k, now) => live(k, now).length >= n,
size: () => m.size,
};
}
/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an
IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */
function addrKey(a) {
a = String(a || '').trim();
if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0);
const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z);
const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1];
const v = net.isIP(a);
if (v === 4) return a;
if (v !== 6) return null;
const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : [];
// The groups :: stands for (a dotted IPv4 at the end is two of them).
const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0);
const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail];
return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64';
}
class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } }
const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); };
// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that
// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes.
function readJson(req, max, ms = 30000) {
return new Promise((resolve, reject) => {
const ct = String(req.headers['content-type'] || '');
if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); }
const len = +req.headers['content-length'];
if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); }
let parts = [], n = 0, done = false;
const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); };
const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms);
req.on('data', (b) => {
if (done) return;
n += b.length;
if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; }
parts.push(b);
});
req.on('end', () => {
if (done) return; done = true; clearTimeout(tm);
let j;
try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); }
if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object'));
resolve(j);
});
req.on('error', () => stop(new HttpError(400, 'request failed')));
req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); });
});
}
function send(res, status, body) {
if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; }
const txt = JSON.stringify(body);
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) });
res.end(txt);
}
/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API.
handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */
function createMp(o = {}) {
const dir = path.resolve(o.dir || 'mp-data');
const base = (o.base || '/api/mp').replace(/\/+$/, '');
const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60;
const now = o.now || Date.now, log = o.log || ((s) => console.log(s));
fs.mkdirSync(dir, { recursive: true });
const file = (code) => path.join(dir, code + '.json');
const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`);
const cache = new Map(), chains = new Map(), soon = new Map();
let codes = new Set(), tmpN = 0;
const HOUR = 3600000, MIN = 60000;
const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR);
// However many addresses ask, the server fills up slowly: a full server takes days, not minutes.
const createAll = limiter(o.sessionsPerHour || 100, HOUR);
const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000);
// Wrong codes, counted per address: guessing codes runs out long before it finds one.
const missRate = limiter(o.missesPerHour || 120, HOUR);
// A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they
// stop one player from keeping the disk busy rewriting their session.
const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN);
// Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes.
const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4;
// Atomic: write a temporary file next to it, then rename over the old one.
const writeAtomic = async (f, txt) => {
const tmp = `${f}.${process.pid}.${++tmpN}.tmp`;
await fs.promises.writeFile(tmp, txt);
await fs.promises.rename(tmp, f);
};
// One session's writes happen one after another, in the order they were asked for.
const queue = (code, job) => {
const p = (chains.get(code) || Promise.resolve()).then(job, job);
const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); });
chains.set(code, q);
q.then(() => { if (chains.get(code) === q) chains.delete(code); });
return p;
};
// A session that is gone (its last player left) is never written again, whatever was still on its way.
const persist = (s) => {
const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); }
s.touched = now();
if (s.dead) return Promise.resolve();
return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s)));
};
// Cards change often and matter little: their session is written a moment later, once for all of that moment's.
const persistSoon = (s) => {
s.touched = now();
if (s.dead || soon.has(s.code)) return;
const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000);
if (tm.unref) tm.unref();
soon.set(s.code, tm);
};
function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } }
// Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes.
function prune() {
const cut = now() - pruneDays * DAY; let n = 0;
for (const f of fs.readdirSync(dir)) {
const p = path.join(dir, f);
let st; try { st = fs.statSync(p); } catch (e) { continue; }
if (!st.isFile()) continue;
if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; }
const m = /^([0-9A-Z]{6})\.json$/.exec(f);
const live = m && cache.get(m[1]);
if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; }
}
for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); }
scan();
return n;
}
function drop(code) {
const s = cache.get(code); if (s) s.dead = true;
const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); }
for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true });
cache.delete(code); codes.delete(code);
}
function load(code) {
if (!CODE_RE.test(code)) return null;
if (cache.has(code)) return cache.get(code);
if (!codes.has(code)) return null;
let s = null;
try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; }
if (!s || s.code !== code || !Array.isArray(s.players)) return null;
// A hand-edited or damaged file: players without an id or a token hash cannot be anyone.
s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string');
for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) };
if (!Array.isArray(s.feed)) s.feed = [];
cache.set(code, s);
return s;
}
prune();
// The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last.
const ipOf = (req) => {
if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; }
return addrKey(req.socket.remoteAddress) || '?';
};
// The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for
// a player who is not there.
function player(req, s) {
const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || ''));
if (!m) return null;
const p = s.players.find((x) => x.pid === m[1]);
const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]);
return crypto.timingSafeEqual(want, got) && p ? p : null;
}
const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; };
// Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them.
const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p));
const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); };
const roster = (s) => ({
code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created,
players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })),
feed: s.feed,
});
// A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets
// the headline). A network that drops out and comes back is not news again.
function applyCard(s, p, c) {
const hit = p.hit || (p.hit = {});
if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); }
else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); }
p.card = c;
}
function newPlayer(s, body, ip) {
const net = body.net && typeof body.net === 'object' ? body.net : {};
const name = cleanText(net.name, 32);
if (!name) fail(400, 'name your network');
const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null;
if (!home) fail(400, 'pick a home city');
let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid));
const token = crypto.randomBytes(32).toString('hex');
const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a)));
for (const p of s.players) avoid.add(p.asn);
let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn));
const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length];
const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} };
s.players.push(p);
event(s, 'join', p);
return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title };
}
// The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped.
const readSave = async (code, pid) => {
const t = await fs.promises.readFile(saveFile(code, pid), 'utf8');
if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } }
return t;
};
// A save upload holds a place until it is done: one per player, a few per address and on the whole server.
function upTake(key, ip) {
if (up.has(key)) fail(429, 'a save of yours is still on its way');
if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true });
up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1);
return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); };
}
async function route(req, res, url) {
const rest = url.pathname.slice(base.length);
const t = now(), ip = ipOf(req), M = req.method;
if (rest === '/sessions') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now');
if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later');
if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now');
const preset = PRESETS.includes(body.preset) ? body.preset : null;
if (!preset) fail(400, 'unknown rules preset');
let code; do code = randCode(); while (codes.has(code));
const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] };
const out = newPlayer(s, body, ip);
codes.add(code); cache.set(code, s);
await persist(s);
return send(res, 201, out);
}
const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest);
if (!m) fail(404, 'not found');
const sub = m[2] || '';
let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ }
const code = normCode(raw), s = code && load(code);
// A player of this very session, with their token, is never held up by somebody else's wrong codes from the same
// address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either.
const me = s ? player(req, s) : null;
if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later');
if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later');
if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); }
if (sub === '/join') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (!still(s)) fail(404, 'no such session');
if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true });
const out = newPlayer(s, body, ip);
await persist(s);
return send(res, 200, out);
}
if (sub === '') {
if (M !== 'GET') fail(405, 'method not allowed');
authed(me);
return send(res, 200, roster(s));
}
if (sub === '/card') {
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me);
if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down');
const body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const c = cleanCard(body.card);
if (!c) fail(400, 'bad card');
applyCard(s, p, c);
persistSoon(s);
return send(res, 200, roster(s));
}
if (sub === '/save') {
if (M === 'GET') {
const p = authed(me);
if (!p.sv) fail(404, 'no save yet');
let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); }
return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data });
}
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me), key = code + '.' + p.pid;
const free = upTake(key, ip);
try {
if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down');
const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS);
if (!still(s, p)) fail(401, 'unauthorized');
const seq = body.seq, data = body.data;
if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer');
if (typeof data !== 'string' || !data.length) fail(400, 'no save data');
if (data.length > MAX_SAVE) fail(413, 'save too large');
if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save');
const card = body.card === undefined ? undefined : cleanCard(body.card);
if (card === null) fail(400, 'bad card');
const old = p.sv;
// Another device of the same player saved a newer game: never overwrite it unless the player says so.
if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at });
const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq;
// The session says it has this save only once the save is on disk.
await queue(code, () => writeAtomic(saveFile(code, p.pid), data));
if (!still(s, p)) fail(401, 'unauthorized');
p.sv = { seq: sq, at, size: data.length };
if (card) applyCard(s, p, card);
await persist(s);
return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) });
} finally { free(); }
}
if (sub === '/feed') {
if (M !== 'POST') fail(405, 'method not allowed');
const p = authed(me), body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const text = cleanChat(body.text);
if (!text) fail(400, 'say something');
if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little');
event(s, 'chat', p, { text });
await persist(s);
return send(res, 200, roster(s));
}
if (sub === '/me') {
if (M !== 'DELETE') fail(405, 'method not allowed');
const p = authed(me);
s.players = s.players.filter((x) => x !== p);
await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true }));
if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); }
event(s, 'leave', p);
await persist(s);
return send(res, 200, { ok: true });
}
fail(404, 'not found');
}
function handle(req, res) {
let url;
try { url = new URL(req.url, 'http://x'); } catch (e) { return false; }
if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false;
const t0 = Date.now();
res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); });
route(req, res, url).catch((e) => {
// A body nobody read (refused before it was needed) is drained, so the client still gets its answer.
if (!req.complete && !req.destroyed) req.resume();
if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) });
log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`);
send(res, 500, { error: 'server error' });
});
return true;
}
// Everything written before the process goes, sessions waiting for their moment too.
const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); };
return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size };
}
module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE };