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

790
tests/multiplayer.test.js Normal file
View file

@ -0,0 +1,790 @@
// Multiplayer in the page (src/game/60-features/89-multiplayer.js, docs/MULTIPLAYER.md): off in every plain build, and
// with MP_API stamped, starting and joining sessions, the public card, when saves go to the server, a newer save from
// another device, the #mp= link, other players' data shown as text, the session panel on a phone, and old saves.
// The server is faked here (its own tests: tests/mp-server.test.js), except in the last test, which plays two pages
// against the real one.
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 { execFileSync } = require('node:child_process');
const { load, flush, browser } = require('./harness');
const { until } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
const MPA = '/api/mp', CODE = 'K7Q2XD', PID = 'abcd1234', TOK = 'a1'.repeat(32);
const JOINED = { code: CODE, pid: PID, token: TOK, seed: 424242, asn: 201234, preset: 'bgp', color: '#3a86ff', title: 'Friday' };
const roster = (players = [], feed = []) => ({ code: CODE, title: 'Friday', preset: 'bgp', seed: 424242, created: 1, players, feed });
const me = (card = null) => ({ pid: PID, name: 'Packet Pals', asn: 201234, color: '#3a86ff', card, seen: Date.now(), joined: 1 });
// A fake session server: routes are [regexp on "METHOD url", reply | (call) => reply], a reply {status, json}, an Error,
// or a promise of either (an answer still on its way; a call the page aborts meanwhile fails, as fetch does).
function fake(routes = []) {
const calls = [];
const res = (r) => r instanceof Error ? Promise.reject(r) : Promise.resolve({ ok: r.status < 400, status: r.status, json: () => Promise.resolve(r.json) });
const f = (url, o = {}) => {
const c = { url: String(url), method: o.method || 'GET', raw: o.body, body: o.body ? JSON.parse(o.body) : undefined, headers: o.headers || {}, keepalive: !!o.keepalive, signal: o.signal };
calls.push(c);
for (const [re, h] of f.routes) if (re.test(`${c.method} ${c.url}`)) {
const r = typeof h === 'function' ? h(c) : h;
if (!r || typeof r.then !== 'function') return res(r);
return new Promise((ok, no) => { if (o.signal) o.signal.addEventListener('abort', () => no(new Error('aborted'))); r.then((x) => res(x).then(ok, no)); });
}
return Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({ error: 'not here' }) });
};
f.routes = routes; f.calls = calls;
f.saves = () => calls.filter((c) => c.method === 'PUT' && /\/save$/.test(c.url));
return f;
}
const okSave = [/^PUT \/api\/mp\/sessions\/K7Q2XD\/save$/, (c) => ({ status: 200, json: { ok: true, seq: c.body.seq, at: c.body.at, roster: roster([me(c.body.card)]) } })];
const okStart = [/^POST \/api\/mp\/sessions$/, { status: 201, json: JOINED }];
// A small model of the real server's saves: a number must grow unless forced (409 with the server's number otherwise).
// st.hold: the next save's answer waits until st.go() (an upload still on its way).
function store() {
const st = { save: null, hold: false, go: null };
const put = (c) => {
const old = st.save;
if (old && c.body.seq <= old.seq && c.body.force !== true) return { status: 409, json: { error: 'newer', seq: old.seq, at: old.at } };
const sq = old && c.body.seq <= old.seq ? old.seq + 1 : c.body.seq;
st.save = { seq: sq, at: c.body.at, data: c.body.data };
return { status: 200, json: { ok: true, seq: sq, at: c.body.at, roster: roster([me(c.body.card)]) } };
};
const routes = [okStart,
[/^PUT \/api\/mp\/sessions\/K7Q2XD\/save$/, (c) => { if (!st.hold || c.keepalive) return put(c); st.hold = false; return new Promise((r) => { st.go = () => r(put(c)); }); }],
[/^PUT \/api\/mp\/sessions\/K7Q2XD\/card$/, (c) => ({ status: 200, json: roster([me(c.body.card)]) })],
[/^GET \/api\/mp\/sessions\/K7Q2XD\/save$/, () => st.save ? { status: 200, json: st.save } : { status: 404, json: { error: 'no save yet' } }],
[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me()]) }]];
return { st, routes, day: () => JSON.parse(st.save.data).day };
}
const storageOf = (h) => { const o = {}; for (const k of JSON.parse(h.ev('JSON.stringify(Object.keys(localStorage))'))) if (!k.startsWith('sot-open:')) o[k] = h.ev(`localStorage.getItem(${lit(k)})`); return o; };
const hide = (on = true) => `Object.defineProperty(document,'visibilityState',{configurable:true,get:()=>${lit(on ? 'hidden' : 'visible')}});document.dispatchEvent(new Event('visibilitychange'));`;
const quiet = 'S.nextFail=S.nextEvent=1e9;UI.speed=0;closeModal();';
// Start a session from the title screen, as a player does.
async function started(opts = {}) {
const f = opts.fetch || fake([okStart, okSave]);
const h = load({ mp: MPA, fetch: f, ...opts.load });
h.ev(`UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value=${lit(opts.name || 'Packet Pals')};ACT.presetSet({p:'bgp'});ACT.mpStart({})`);
assert.ok(await until(() => h.ev('!!(S&&S.mp)')), 'the game started');
await until(() => h.ev('!MP.busy'));
h.ev(quiet);
return { ...h, f };
}
test('multiplayer: a plain build has no door, no chip, no tile and makes no request at all', async () => {
const f = fake();
const { dom, ev, errors } = load({ fetch: f });
const doc = dom.window.document;
assert.equal(ev('MP_API'), '');
assert.equal(doc.querySelector('.mpdoor'), null, 'no door on the title screen');
ev(`ACT.start({});if(UI.pendGame)ACT.pitchSkip();${quiet}ACT.launchBB({city:'fra'});for(let i=0;i<5;i++)dayTick();save(true);ACT.menu({})`);
assert.equal(doc.querySelector('[data-act=mpOpen]'), null, 'no session tile in the menu');
assert.equal(doc.getElementById('hMp'), null, 'no chip in the HUD');
ev('ACT.mpDoor({});ACT.mpOpen({});mpPush("{}",{now:true});mpResume();mpRefresh()');
// A save carrying a session (from a copy that has one) loads and plays, and still talks to nobody.
ev(`S.mp={code:'${CODE}',pid:'${PID}',asn:201234,seed:1,preset:'bgp',color:'#3a86ff',title:'',seq:3};S=migrate(JSON.parse(JSON.stringify(S)));dayTick();save(true);renderAll()`);
assert.equal(ev('S.mp.code'), CODE, 'the session stays in the save');
assert.equal(doc.getElementById('hMp'), null);
await flush();
assert.deepEqual(f.calls, [], 'not one request');
assert.deepEqual(errors, []);
});
test('multiplayer: the build stamps MP_API only when asked, and only a same-origin path', () => {
const root = path.join(__dirname, '..'), OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-build-'));
const build = (env) => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.2.3', BUILD_DATE: '2026-11-06', ...env } });
build({ MP_API: '/api/mp' });
const html = fs.readFileSync(path.join(OUT, 'index.html'), 'utf8');
assert.match(html, /const MP_API='\/api\/mp';/);
assert.doesNotMatch(html, /__MP_API__/);
const { ev, errors } = load({ file: path.join(OUT, 'index.html'), fetch: fake() });
assert.equal(ev('MP_API'), '/api/mp');
assert.ok(ev("!!document.querySelector('.mpdoor')"), 'the built page has the door');
assert.deepEqual(errors, []);
build({ MP_API: '' });
assert.match(fs.readFileSync(path.join(OUT, 'index.html'), 'utf8'), /const MP_API='';/, 'a plain build stays off');
// "//host/path" is another host to a browser, and the player's token would go there.
for (const bad of ['https://evil.example/api', "/api'+alert(1)+'", 'api/mp', '/api/mp/', '/a b', '//evil-host/mp', '//api/mp']) assert.throws(() => build({ MP_API: bad }), bad);
fs.rmSync(OUT, { recursive: true, force: true });
});
test('multiplayer: starting a session takes the server\'s code, seed, rules and AS number; the token stays out of the save', async () => {
const { dom, ev, errors, f } = await started();
const create = f.calls[0];
assert.equal(create.url, '/api/mp/sessions');
assert.equal(create.body.net.name, 'Packet Pals');
assert.equal(create.body.net.home, 'fra');
assert.equal(create.body.preset, 'bgp');
assert.deepEqual(create.body.avoid, JSON.parse(ev('JSON.stringify(NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn))')), 'the catalog\'s own AS numbers are off limits');
assert.equal(create.headers.authorization, undefined, 'starting needs no token');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.mp)')), { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'bgp', color: '#3a86ff', title: 'Friday', seq: 1 });
assert.equal(ev('S.asn'), 201234);
assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('S.rules.preset'), 'bgp');
assert.equal(ev('typeof S.rng'), 'number', 'a seeded world');
assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), TOK);
assert.ok(!ev('JSON.stringify(S)').includes(TOK), 'the token is not in the game');
assert.ok(!ev('localStorage.getItem(SLOT_K+UI.slot)').includes(TOK), 'nor in its save');
// The first save went at once, with the card, so the player is on the leaderboard (and a link works) from day 0.
const s = f.saves();
assert.equal(s.length, 1);
assert.equal(s[0].body.seq, 1);
assert.equal(s[0].headers.authorization, `Bearer ${PID}.${TOK}`);
assert.equal(JSON.parse(s[0].body.data).mp.code, CODE);
assert.equal(s[0].body.card.day, 0);
assert.ok(ev("$('toasts').textContent").includes('K7Q-2XD'), 'the code to share');
assert.equal(ev("$('hMpRank').textContent"), '🌐 #1/1');
assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), `${CODE}.${PID}`, 'the slot list knows the session');
assert.match(ev('slotListHtml()'), /🌐 K7Q-2XD/);
ev('ACT.toTitle({})');
assert.equal(ev("$('hMp').hidden"), true, 'back on the title screen, the chip goes');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: one session, one world: the same seed makes the same days whatever the browser\'s own luck', async () => {
const run = async (seed) => {
const h = await started({ load: { seed } });
const out = h.ev("ACT.launchBB({city:'fra'});S.nextFail=5;S.nextEvent=5;for(let i=0;i<40;i++)dayTick();JSON.stringify({o:S.offers.map(o=>o.name+o.bw),inc:S.inc.map(i=>i.type),log:S.log.map(l=>l.t).slice(0,20)})");
assert.deepEqual(h.errors, []);
h.dom.window.close();
return out;
};
assert.equal(await run(11), await run(99991));
});
test('multiplayer: joining by a typed code; the session\'s rules win; errors are told plainly', async () => {
const f = fake([[/^POST \/api\/mp\/sessions\/K7Q2XD\/join$/, { status: 200, json: { ...JOINED, preset: 'soft', title: '' } }], okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f });
ev("UI.pitched=true;ACT.mpDoor({});ACT.presetSet({p:'bgp'});document.getElementById('mpCode').value='zz';ACT.mpJoin({})");
assert.equal(f.calls.length, 0, 'a code that is not one never leaves the page');
assert.match(ev("$('toasts').textContent"), /six letters/);
ev("document.getElementById('mpCode').value=' k7q-2xd ';ACT.mpJoin({})");
assert.ok(await until(() => ev('!!(S&&S.mp)')));
assert.equal(f.calls[0].url, '/api/mp/sessions/K7Q2XD/join');
assert.equal(f.calls[0].body.preset, undefined, 'a joiner does not pick the rules');
assert.equal(ev('S.rules.preset'), 'soft', 'the creator did');
assert.match(ev("$('toasts').textContent"), /You joined session K7Q-2XD/);
// "Full" names no number: the server may take fewer than twelve (--max-players).
for (const [status, re] of [[404, /no session with that code/], [409, /^That session is full: every seat in it is taken\.$/], [429, /Too many tries/], [503, /not taking new sessions/], [0, /cannot be reached/]]) {
f.routes = [[/join$/, status ? { status, json: { error: 'x' } } : new Error('offline')]];
ev("UI.mpBusy=false;openModal(mpStartHtml());document.getElementById('mpCode').value='K7Q2XD';$('toasts').innerHTML='';ACT.mpJoin({})");
assert.ok(await until(() => re.test(ev("$('toasts').textContent"))), `${status}: ${ev("$('toasts').textContent")}`);
assert.equal(ev('UI.mpBusy'), false, 'the buttons work again');
}
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: the card carries what the leaderboard needs and nothing more', async () => {
const { dom, ev, errors } = await started();
ev("S.cash=1e8;S.lvl=3;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});ACT.buyIx({city:'fra',tier:0,signed:true});for(let i=0;i<120;i++)dayTick();compute()");
const c = JSON.parse(ev('JSON.stringify(mpCard())'));
assert.deepEqual(Object.keys(c).sort(), ['asn', 'cashB', 'cust', 'day', 'ix', 'links', 'lvl', 'name', 'peak', 'pops', 'ppol', 'reach', 'rev', 'score', 'served', 't1', 'tier', 'transit']);
assert.equal(c.day, ev('S.day'));
assert.deepEqual(c.pops.sort(), ['ams', 'fra']);
assert.deepEqual(c.transit, ['cog']);
assert.deepEqual(c.ix, ['fra']);
assert.equal(c.links.length, 1);
assert.deepEqual(c.links[0].slice(0, 2).sort(), ['ams', 'fra']);
assert.ok(c.links[0][2] > 0);
assert.ok(['t1', 't2', 't3'].includes(c.tier));
assert.equal(c.cashB, Math.floor(Math.log10(ev('S.cash'))), 'cash as an order of magnitude, not the figure');
assert.equal(c.cust, ev('S.biz.length'));
// What comes back is checked against the page's own catalogs.
const back = JSON.parse(ev(`JSON.stringify(mpCardOk(${lit({ ...c, pops: [...c.pops, 'zzz', '<b>'], transit: ['cog', 'nope'], ix: ['fra', 'atlantis'], links: [...c.links, ['fra', 'zzz', 5]], tier: 't9', reach: 9, extra: 1 })}))`));
assert.deepEqual(back.pops.sort(), ['ams', 'fra']);
assert.deepEqual(back.transit, ['cog']);
assert.deepEqual(back.ix, ['fra']);
assert.equal(back.links.length, 1);
assert.equal(back.tier, 't3');
assert.equal(back.reach, 1);
assert.equal(back.extra, undefined);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: saves go to the server on a new day, at most every 15 s, never mid-day or in a puzzle; big ones gzipped; on hide a keepalive', async () => {
const { dom, ev, errors, f } = await started({ load: { gzip: true } });
const n = () => f.saves().length;
assert.equal(n(), 1, 'day 0 went at start');
ev('save(true)');
assert.equal(n(), 1, 'same day: nothing new');
ev('dayTick();save(true)');
assert.equal(n(), 1, 'a new day, but not 15 s yet');
ev('MP.last-=16000;save(true)');
assert.equal(n(), 2, 'a new day and 15 s: it goes');
assert.equal(f.saves()[1].body.seq, 2);
await until(() => ev('!MP.busy'));
assert.equal(ev('S.mp.seq'), 2, 'the server\'s number is kept');
ev('dayTick();MP.last-=16000;RW.job={};save(true);RW.job=null');
assert.equal(n(), 2, 'never half a day');
// Starting a puzzle saves the network it sets aside first (that day goes); in the puzzle nothing does.
ev("ACT.pzStart({id:'hello'})");
assert.equal(ev('pzOn()'), true);
await until(() => ev('!MP.busy'));
const k = n();
ev('MP.last-=16000;save(true);UI.pzKeep.day++;MP.last-=16000;save(true)');
assert.equal(n(), k, 'never a puzzle, nor the network set aside for it from here');
ev('pzLeave();closeModal();dayTick();MP.last-=16000;save(true)');
assert.equal(n(), k + 1, 'back from the puzzle, the new day goes');
await until(() => ev('!MP.busy'));
ev(`S.mp.seq++;mpPush('{"x":"'+'a'.repeat(50000)+'"}')`);
assert.ok(await until(() => n() === k + 2), 'a big save');
assert.match(f.saves().at(-1).body.data, /^gz:/, 'goes compressed');
assert.ok(f.saves().at(-1).body.data.length < 5000);
await until(() => ev('!MP.busy'));
// The page is going away: one keepalive request, the save when it fits, else the card alone.
ev("dayTick();window.dispatchEvent(new Event('pagehide'))");
assert.equal(f.calls.at(-1).keepalive, true, 'closing the tab: the page\'s own save on the way out goes as a keepalive');
assert.match(f.calls.at(-1).url, /\/save$/);
await until(() => ev('!MP.busy'));
ev("window.dispatchEvent(new Event('pageshow'))");
assert.equal(ev('MP.leaving'), false);
ev("Object.defineProperty(document,'visibilityState',{configurable:true,get:()=>'hidden'});dayTick();save(true)");
const last = f.calls.at(-1);
assert.equal(last.keepalive, true);
assert.match(last.url, /\/save$/);
await until(() => ev('!MP.busy'));
ev(`dayTick();S.mp.seq++;mpPush('{"x":"'+'a'.repeat(70000)+'"}')`);
assert.equal(f.calls.at(-1).keepalive, true);
assert.match(f.calls.at(-1).url, /\/card$/, 'too big for a keepalive: the card');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: when another device moved on, the player hears it once and chooses', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f });
f.routes = [[/save$/, (c) => c.body && c.body.force ? { status: 200, json: { ok: true, seq: 9, roster: roster([me()]) } } : { status: 409, json: { error: 'newer', seq: 8 } }], [/^GET /, { status: 200, json: roster([me()]) }]];
ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.stale')));
assert.match(ev("$('toasts').textContent"), /moved on elsewhere/);
assert.ok(ev("!!document.querySelector('#toasts [data-act=mpNewer]')&&!!document.querySelector('#toasts [data-act=mpKeep]')"));
const k = f.saves().length;
ev('dayTick();MP.last-=16000;save(true)');
assert.equal(f.saves().length, k, 'and nothing is pushed over it meanwhile');
// The toast goes after a few seconds; the choice waits in the session panel.
ev("$('toasts').innerHTML='';ACT.mpOpen({})");
assert.match(ev("$('mpBoard').textContent"), /moved on elsewhere/);
assert.ok(ev("!!document.querySelector('#mpBoard [data-act=mpNewer]')&&!!document.querySelector('#mpBoard [data-act=mpKeep]')"));
ev('closeModal()');
ev('ACT.mpKeep({})');
assert.equal(f.saves().at(-1).body.force, true);
assert.ok(await until(() => ev('S.mp.seq===9&&!MP.stale')), 'keeping this one overwrites, and takes the server\'s number');
// The other choice: load what the other device saved.
const srv = JSON.parse(ev('JSON.stringify(packSave(S))'));
srv.day = 77; srv.cash = 4242;
f.routes = [[/^GET .*\/save$/, { status: 200, json: { seq: 12, at: 1, data: JSON.stringify(srv) } }], [/^GET /, { status: 200, json: roster([me()]) }]];
ev('ACT.mpNewer({})');
assert.ok(await until(() => ev('S.day===77')));
assert.equal(ev('S.cash'), 4242);
assert.equal(ev('S.mp.seq'), 12);
// A save that is some other network is never loaded over this one.
srv.mp.pid = 'zzzzzzzz'; srv.day = 99;
f.routes = [[/^GET .*\/save$/, { status: 200, json: { seq: 13, at: 1, data: JSON.stringify(srv) } }]];
ev("$('toasts').innerHTML='';ACT.mpNewer({})");
assert.ok(await until(() => /could not be read/.test(ev("$('toasts').textContent"))));
assert.equal(ev('S.day'), 77);
assert.deepEqual(errors.filter((e) => !/loading the session save failed/.test(e)), []);
dom.window.close();
});
test('multiplayer: a session network on a device without its token plays on alone, and can leave', async () => {
const a = await started();
const save = a.ev('JSON.stringify(packSave(S))');
a.dom.window.close();
// The same network imported from a file on another device: the session is in the save, the token is not.
const f = fake([[/./, { status: 500, json: {} }]]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f });
ev(`UI.pitched=true;UI.importing=JSON.parse(${lit(save)});ACT.importGo({});${quiet}`);
assert.equal(ev('S.mp.code'), CODE);
// Importing it checks in with the session at once.
assert.ok(await until(() => ev('MP.gone')));
assert.deepEqual(f.calls, [], 'without a token nothing is even asked');
assert.match(ev("$('toasts').textContent"), /no longer in its session/);
ev('dayTick();MP.last-=16000;save(true)');
assert.deepEqual(f.calls, [], 'nor pushed');
ev('ACT.mpOpen({})');
assert.match(ev("$('mpBoard').textContent"), /no longer in its session/);
ev('ACT.mpLeave({})');
assert.ok(await until(() => ev('S.mp===null')), 'leaving works without the server');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: opening a session network loads the newer save another device pushed', async () => {
const a = await started();
a.ev("ACT.launchBB({city:'fra'});for(let i=0;i<3;i++)dayTick();save(true)");
const storage = {};
for (const k of JSON.parse(a.ev('JSON.stringify(Object.keys(localStorage))'))) if (!k.startsWith('sot-open:')) storage[k] = a.ev(`localStorage.getItem(${lit(k)})`);
// The server's copy: the same network, played on to day 30 elsewhere.
const srv = JSON.parse(a.ev('JSON.stringify(packSave(S))'));
srv.day = 30; srv.cash = 7654321; srv.mp.seq = 6;
a.dom.window.close();
const f = fake([[/^GET \/api\/mp\/sessions\/K7Q2XD\/save$/, { status: 200, json: { seq: 7, at: 1, data: JSON.stringify(srv) } }], [/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me()]) }], okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f, storage });
assert.equal(ev('S.day'), 3, 'this device had day 3');
assert.equal(f.calls[0].url, '/api/mp/sessions/K7Q2XD/save', 'and asked the server first');
assert.ok(await until(() => ev('S.day===30')));
assert.equal(ev('S.cash'), 7654321);
assert.equal(ev('S.mp.seq'), 7);
assert.match(ev("$('toasts').textContent"), /Loaded the newer save/);
assert.ok(f.calls.every((c) => c.method === 'GET'), 'nothing was pushed over it');
assert.ok(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).day === 30, 'and it is this device\'s save now');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: a #mp= link moves the network to this device; a bad one says so', async () => {
const a = await started();
a.ev("ACT.launchBB({city:'fra'});for(let i=0;i<4;i++)dayTick()");
const data = a.ev('JSON.stringify(packSave(S))'), link = a.ev('mpLink(S.mp)');
a.dom.window.close();
assert.equal(link, `https://tests.invalid/#mp=${CODE}.${PID}.${TOK}`);
const f = fake([[/^GET \/api\/mp\/sessions\/K7Q2XD\/save$/, { status: 200, json: { seq: 4, at: 1, data } }], [/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me()]) }], okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f, url: link });
assert.ok(await until(() => ev('!!(S&&UI.started)')), 'the network opened');
assert.equal(ev('location.hash'), '', 'the secret is gone from the address bar');
assert.equal(ev('S.name'), 'Packet Pals');
assert.equal(ev('S.day'), 4);
assert.equal(ev('S.mp.seq'), 4);
assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), TOK);
assert.equal(ev('slotIdx().length'), 1);
assert.equal(ev('slotIdx()[0].mp'), `${CODE}.${PID}`);
assert.equal(f.calls[0].headers.authorization, `Bearer ${PID}.${TOK}`);
assert.match(ev("$('toasts').textContent"), /moved to this device/);
dom.window.close();
const g = fake([[/save$/, { status: 401, json: { error: 'unauthorized' } }]]);
const b = load({ mp: MPA, fetch: g, url: `https://tests.invalid/#mp=${CODE}.${PID}.${'0'.repeat(64)}` });
assert.ok(await until(() => /did not work/.test(b.ev("$('toasts').textContent"))));
assert.equal(b.ev('S'), null, 'the title screen, nothing loaded');
assert.equal(b.ev('slotIdx().length'), 0);
assert.equal(b.ev('location.hash'), '');
assert.deepEqual(errors, []);
assert.deepEqual(b.errors, []);
b.dom.window.close();
});
test('multiplayer: other players\' names, chat and colours are text, never markup', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f });
const doc = dom.window.document;
const evil = {
pid: 'eeeeeeee', name: '<img src=x onerror=__xss=1>', asn: 210000, color: 'red;background:url(//evil)', seen: 1, joined: 2,
card: { day: 9, tier: 't1', t1: true, pops: ['fra', 'nyc', '<b>x</b>', 'zzz'], links: [['fra', 'nyc', 5]], ix: [], transit: [], ppol: 'open', reach: 1, peak: 12, served: 1e99, cust: 4, rev: 1, cashB: 3, score: 1 },
};
const feed = [{ k: 'chat', pid: 'eeeeeeee', name: '<script>window.__xss=2</script>', text: '<img src=y onerror="window.__xss=3">', at: 1 }, { k: 'join', pid: 'eeeeeeee', name: '<i>x</i>', at: 1 }, { k: 'evil', name: 'x', at: 1 }];
f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me(), evil, { pid: '../../x', name: 'bad' }], feed) }]];
ev('ACT.mpOpen({})');
assert.ok(await until(() => ev("document.querySelectorAll('#mpBoard .mprow').length===2")));
for (const id of ['mpBoard', 'mpFeed']) {
const el = doc.getElementById(id);
assert.equal(el.querySelector('img,script,i:not(.mpdot)'), null, `${id}: no markup from the server`);
}
assert.ok(doc.getElementById('mpBoard').textContent.includes('<img src=x onerror=__xss=1>'), 'the name shows as text');
assert.ok(doc.getElementById('mpFeed').textContent.includes('<img src=y'), 'and the chat line');
assert.equal(doc.querySelectorAll('#mpBoard .mprow').length, 2, 'a player without a proper id is dropped');
assert.equal(doc.querySelectorAll('#mpFeed .mpf').length, 2, 'and an unknown kind of feed line');
assert.ok([...doc.querySelectorAll('.mpdot')].every((d) => /^background: ?#[0-9a-f]{6};?$/i.test(d.getAttribute('style'))), 'colours are colours');
assert.match(doc.querySelector('#mpBoard .mprow').textContent, /Tier 1/, 'Tier 1 leads the board');
assert.match(doc.querySelector('#mpBoard .mprow').textContent, /2 POPs/, 'with only real cities');
assert.equal(ev('window.__xss'), undefined);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: the session panel and the chip on a phone; chat, leaving', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f, load: { gzip: false } });
const doc = dom.window.document;
ev('window.innerWidth=360;window.innerHeight=740;renderAll()');
assert.equal(ev('isPhone()'), true);
const chip = doc.getElementById('hMp');
assert.ok(chip && !chip.hidden, 'the chip is there');
assert.match(chip.textContent, /K7Q-2XD/);
// A phone's top bar has no room for it (cash and the date would be cut): hide-sm. Where you stand is a badge on the
// menu button instead, there and on a tablet whose top bar still wraps at fitHud's last step (no layout in jsdom).
assert.ok(chip.classList.contains('hide-sm'), 'not in a phone\'s top bar');
const badge = doc.querySelector('#hud .menubtn #hMpB');
assert.ok(badge && !badge.hidden, 'a badge on the menu button');
const css = [...doc.querySelectorAll('style')].map((x) => x.textContent).join('');
assert.match(css, /#hud\.fit3 \.mpchip\{display:none !important\}/, 'a tablet drops the chip before the top bar wraps');
assert.match(css, /\.mpbadge\{display:block\}/);
ev('ACT.menu({})');
assert.ok(doc.querySelector('#modalCard .mtile[data-act=mpOpen]'), 'the menu has the session');
f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me({ day: 1, tier: 't2', t1: false, pops: ['fra'], links: [], ix: [], transit: [], ppol: 'open', reach: 0.5, peak: 3, served: 2, cust: 1, rev: 1, cashB: 5, score: 1 }), { ...me(null), pid: 'bbbbbbbb', name: 'Bee', color: '#ff4f9a' }], [{ k: 'join', pid: PID, name: 'Packet Pals', at: Date.now() }]) }],
[/feed$/, (c) => c.body.text === 'fast' ? { status: 429, json: { error: 'slow' } } : { status: 200, json: roster([me()], [{ k: 'chat', pid: PID, name: 'Packet Pals', text: c.body.text, at: Date.now() }]) }],
[/^DELETE .*\/me$/, { status: 200, json: { ok: true } }]];
doc.querySelector('#modalCard .mtile[data-act=mpOpen]').click();
assert.ok(await until(() => doc.querySelectorAll('#mpBoard .mprow').length === 2));
const card = doc.getElementById('modalCard');
assert.ok(card.querySelector('.btns.cta'), 'the main buttons stay in reach (sticky on a phone)');
assert.equal(card.querySelector('.mpcode b').textContent, 'K7Q-2XD');
assert.ok(card.querySelector('details.mpmove #mpLink'), 'the link to another device, folded away');
assert.match(card.querySelector('#mpLink').value, /#mp=K7Q2XD\.abcd1234\.[0-9a-f]{64}$/);
assert.match(doc.querySelector('#mpBoard .mprow.me').textContent, /you/);
assert.match(doc.getElementById('mpBoard').textContent, /has not finished a day yet/);
assert.equal(ev("$('hMpRank').textContent"), '🌐 #1/2');
assert.equal(badge.textContent, '#1');
// Chat.
ev("document.getElementById('mpSay').value='hello there';ACT.mpChat({})");
assert.ok(await until(() => /hello there/.test(doc.getElementById('mpFeed').textContent)));
assert.equal(doc.getElementById('mpSay').value, '', 'the line went');
ev("$('toasts').innerHTML='';document.getElementById('mpSay').value='fast';ACT.mpChat({})");
assert.ok(await until(() => /Slow down/.test(ev("$('toasts').textContent"))));
// Landscape on a phone: still a phone layout.
ev('window.innerWidth=740;window.innerHeight=360;renderAll()');
assert.ok(doc.getElementById('mpPanel'));
// Leaving: the network stays, the session and the token go.
ev('ACT.mpLeaveAsk({})');
assert.match(doc.getElementById('modalCard').textContent, /Leave session K7Q-2XD\?/);
ev('ACT.mpLeave({})');
assert.ok(await until(() => ev('S.mp===null')));
assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), null);
assert.equal(doc.getElementById('hMp').hidden, true);
assert.equal(badge.hidden, true);
assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp, null, 'saved without it');
assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'and the list of networks forgets the session too');
assert.doesNotMatch(ev('slotListHtml()'), /K7Q-2XD/);
ev('dayTick();save(true)');
assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'for good');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: the server away: the game plays on, backs off, says so once', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f });
f.routes = [[/./, new Error('offline')]];
ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.fails===1')));
assert.ok(ev('MP.wait>performance.now()'), 'it waits before the next try');
assert.match(ev("$('toasts').textContent"), /server is away/);
ev('dayTick();MP.last-=16000;save(true)');
assert.equal(f.saves().length, 2, 'not while it waits');
ev("$('toasts').innerHTML='';MP.wait=0;dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.fails===2')));
assert.equal(ev("$('toasts').textContent"), '', 'told once');
// Too many at once (429, or the server's own 503 "busy") is not "away": a short wait, quietly, and the back-off stays
// where it was. Behind a proxy without --trust-proxy every player is one address, so this happens to honest players.
for (const r of [{ status: 429, json: { error: 'slow down' } }, { status: 503, json: { error: 'busy', busy: true } }]) {
f.routes = [[/save$/, r]];
ev("MP.told=false;MP.wait=0;dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('!MP.busy&&MP.wait>performance.now()')));
assert.equal(ev('MP.fails'), 2, String(r.status));
assert.ok(ev('MP.wait-performance.now()') <= 30000);
assert.equal(ev("$('toasts').textContent"), '', 'nothing to tell');
}
// A proxy's own 503 (the server behind it is down) is "away".
f.routes = [[/save$/, { status: 503, json: null }]];
ev("MP.wait=0;dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.fails===3')));
assert.match(ev("$('toasts').textContent"), /server is away/);
f.routes = [okSave];
ev('MP.wait=0;dayTick();MP.last-=16000;save(true)');
assert.ok(await until(() => ev('MP.fails===0&&!MP.told')), 'back: all forgotten');
assert.ok(ev('S.day') >= 4, 'and the game went on all along');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: S.mp from a save is checked; saves without it load as before', () => {
const { ev, errors } = load({ mp: MPA, fetch: fake() });
ev(`ACT.start({});if(UI.pendGame)ACT.pitchSkip();${quiet}`);
assert.equal(ev('S.mp'), null, 'a game outside a session');
const fix = (m, mode = 'normal') => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mode=${lit(mode)};s.mp=${lit(m)};return JSON.stringify(sanitize(s).mp);})()`));
assert.deepEqual(fix({ code: CODE, pid: PID, asn: 999, seed: 1e12, preset: 'sandbox', color: 'javascript:x', title: 'x'.repeat(99), seq: -4, token: TOK, extra: 1 }),
{ code: CODE, pid: PID, asn: 200000, seed: 2147483647, preset: 'oncall', color: '#ff4f9a', title: 'x'.repeat(40), seq: 0 });
for (const bad of [null, 7, 'K7Q2XD', [], { code: '../../x', pid: PID }, { code: CODE, pid: 'ABC' }, { code: 'k7q2xd', pid: PID }]) assert.equal(fix(bad), null, JSON.stringify(bad));
assert.equal(fix({ code: CODE, pid: PID }, 'sandbox'), null, 'only a Normal game can be in a session');
// An old save: no mp at all.
ev('const s=JSON.parse(JSON.stringify(S));delete s.mp;S=migrate(s);compute();dayTick();save(true)');
assert.equal(ev('S.mp'), null);
assert.equal(ev("'mp' in S"), true);
ev('S=sanitize(JSON.parse(JSON.stringify(S)))');
assert.equal(ev('S.mp'), null, 'and it round-trips');
assert.equal(ev("slotClean({id:'abc',mp:'K7Q2XD.abcd1234'}).mp"), 'K7Q2XD.abcd1234');
assert.equal(ev("slotClean({id:'abc',mp:'<b>.x'}).mp"), undefined, 'the slot list checks it too');
assert.deepEqual(errors, []);
});
test('multiplayer: two players against the real server: start, join, see each other', async (t) => {
const { createMp } = require('../scripts/lib/mp');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-e2e-'));
const mp = createMp({ dir, log: () => {} });
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(() => { server.close(); fs.rmSync(dir, { recursive: true, force: true }); });
const base = `http://127.0.0.1:${server.address().port}`;
// The page's fetch, on the real network (the page's own AbortSignal stays behind: it belongs to another realm).
const net = (u, o = {}) => { const { signal, ...rest } = o; return fetch(base + u, rest); };
const a = await started({ fetch: net, name: 'Alpha Net' });
const code = a.ev('S.mp.code');
const b = load({ mp: MPA, fetch: net, seed: 777 });
b.ev(`UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Beta <b>Net</b>';ACT.pickStart({city:'nyc'});document.getElementById('mpCode').value=${lit(code.toLowerCase())};ACT.mpJoin({})`);
assert.ok(await until(() => b.ev('!!(S&&S.mp)')), 'B joined');
b.ev(quiet);
assert.equal(b.ev('S.mp.seed'), a.ev('S.mp.seed'), 'one world');
assert.equal(b.ev('S.rules.preset'), 'bgp', 'one set of rules');
assert.notEqual(b.ev('S.asn'), a.ev('S.asn'));
assert.equal(b.ev('S.home'), 'nyc');
await until(() => b.ev('!MP.busy'));
a.ev('mpRefresh()');
assert.ok(await until(() => a.ev('MP.roster&&MP.roster.players.length===2')), 'A sees B');
assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.players.map(p=>p.name))')), ['Alpha Net', 'Beta bNet/b']);
assert.equal(a.ev("MP.roster.players[1].card&&MP.roster.players[1].card.pops.join()"), 'nyc', 'and B\'s card');
assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.feed.map(f=>f.k))')), ['join', 'join']);
// A plays on a few days and pushes; B's panel shows it.
a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)");
await until(() => a.ev('!MP.busy'));
assert.equal(a.ev('S.mp.seq'), 2);
b.ev('ACT.mpOpen({})');
assert.ok(await until(() => /Alpha Net/.test(b.ev("document.getElementById('mpBoard').textContent"))));
b.ev("document.getElementById('mpSay').value='hi from B';ACT.mpChat({})");
assert.ok(await until(() => /hi from B/.test(b.ev("document.getElementById('mpFeed').textContent"))));
// B moves to another device by its link.
const link = b.ev('mpLink(S.mp)');
await until(() => b.ev('!MP.busy'));
const c = load({ mp: MPA, fetch: net, url: link });
assert.ok(await until(() => c.ev('!!(S&&S.mp&&UI.started)')), 'B on the other device');
assert.equal(c.ev('S.name'), 'Beta <b>Net</b>');
assert.equal(c.ev('S.home'), 'nyc');
for (const h of [a, b, c]) { assert.deepEqual(h.errors, []); h.dom.window.close(); }
await mp.flush();
});
test('multiplayer: the save here and the one on the server carry the same number: reopening finds nothing newer', async () => {
const srv = store(), f = fake(srv.routes);
const a = await started({ fetch: f });
const slot = (h) => JSON.parse(h.ev('localStorage.getItem(SLOT_K+UI.slot)'));
a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)");
await until(() => a.ev('!MP.busy'));
assert.equal(srv.st.save.seq, 2);
assert.equal(JSON.parse(srv.st.save.data).mp.seq, 2, 'the server\'s copy says 2');
assert.equal(slot(a).mp.seq, 2, 'and so does the one here: the number was picked before the save was written');
// Closing the tab after a new day: the last save goes as a keepalive request, numbered the same here and there.
a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))");
assert.equal(f.calls.at(-1).keepalive, true);
await until(() => a.ev('!MP.busy'));
assert.equal(srv.st.save.seq, 3);
assert.equal(slot(a).mp.seq, 3);
assert.equal(slot(a).day, srv.day());
const storage = storageOf(a);
a.dom.window.close();
// Reopened on the same device: nothing newer on the server, nothing loaded, nothing said.
const g = fake(srv.routes);
const b = load({ mp: MPA, fetch: g, storage });
assert.ok(await until(() => g.calls.some((c) => /K7Q2XD$/.test(c.url))), 'asked, then took the roster');
await flush();
assert.doesNotMatch(b.ev("$('toasts').textContent"), /Loaded the newer save/);
// A push still on its way when the page goes away: the newer save goes anyway, and cuts the slower one short.
b.ev(quiet);
srv.st.hold = true;
b.ev('dayTick();MP.last-=16000;save(true)');
const slow = g.calls.at(-1);
assert.equal(slow.keepalive, false);
assert.equal(b.ev('MP.busy'), true);
const k = g.calls.length;
b.ev('for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)');
assert.equal(g.calls.length, k, 'one push at a time while the page is on screen');
b.ev("window.dispatchEvent(new Event('pagehide'))");
const last = g.calls.at(-1);
assert.equal(last.keepalive, true);
assert.equal(last.body.seq, slow.body.seq + 1);
assert.equal(JSON.parse(last.body.data).day, b.ev('S.day'), 'the days played meanwhile go too');
assert.equal(slow.signal.aborted, true, 'the slower one was cut short');
await until(() => b.ev('!MP.busy'));
assert.equal(srv.day(), b.ev('S.day'));
assert.equal(slot(b).mp.seq, srv.st.save.seq);
// Reopened once more: the server's copy is this one, so the days stay.
const day = b.ev('S.day'), again = storageOf(b);
b.dom.window.close();
const c = load({ mp: MPA, fetch: fake(srv.routes), storage: again });
await flush(10);
assert.equal(c.ev('S.day'), day);
assert.doesNotMatch(c.ev("$('toasts').textContent"), /Loaded the newer save|moved on elsewhere/);
for (const h of [b, c]) assert.deepEqual(h.errors, []);
assert.deepEqual(a.errors, []);
c.dom.window.close();
});
test('multiplayer: the server briefly away when the network opens is no conflict later', async () => {
const srv = store(), a = await started({ fetch: fake(srv.routes) });
a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)");
await until(() => a.ev('!MP.busy'));
a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))");
await until(() => a.ev('!MP.busy'));
const storage = storageOf(a);
a.dom.window.close();
const g = fake([[/./, new Error('offline')]]);
const b = load({ mp: MPA, fetch: g, storage });
assert.ok(await until(() => b.ev('MP.fails===1')));
b.ev(quiet + "for(let i=0;i<10;i++)dayTick();MP.wait=0;MP.last-=16000");
g.routes = srv.routes;
b.ev('save(true)');
await until(() => b.ev('!MP.busy'));
assert.equal(b.ev('MP.stale'), false, 'one device, so no "moved on elsewhere"');
assert.equal(srv.day(), b.ev('S.day'));
assert.deepEqual(b.errors, []);
b.dom.window.close();
});
test('multiplayer: hiding the page sends what changed on the same game day, only then, in a request that fits', async () => {
const srv = store(), f = fake(srv.routes);
const { dom, ev, errors } = await started({ fetch: f });
const n = () => f.saves().length, k = n();
// A paused game: the player builds, and the day never moves.
ev("ACT.launchBB({city:'fra'})");
assert.equal(n(), k, 'same day, page on screen: nothing yet');
ev(hide());
assert.equal(n(), k + 1, 'hidden: what changed goes');
assert.equal(f.saves().at(-1).keepalive, true);
assert.ok(JSON.parse(f.saves().at(-1).body.data).pops.fra.bb, 'with the change');
await until(() => ev('!MP.busy'));
ev(hide());
assert.equal(n(), k + 1, 'hidden again, nothing changed: nothing sent');
// Moving to another device: the link goes with what this one has now.
ev(hide(false) + "S.name='Packet Pals Two';ACT.mpOpen({});ACT.mpCopyLink({})");
assert.equal(n(), k + 2);
assert.equal(JSON.parse(f.saves().at(-1).body.data).name, 'Packet Pals Two');
await until(() => ev('!MP.busy'));
ev("S.name='Packet Pals Three';const d=document.querySelector('#mpPanel details.mpmove');d.open=true;d.dispatchEvent(new Event('toggle'))");
assert.equal(n(), k + 3, 'opening "Move to another device" pushes too');
await until(() => ev('!MP.busy'));
// A keepalive request may carry 64 KiB in all: the request is measured, in bytes, quotes escaped, card and all.
ev('closeModal();' + hide());
const send = (t) => { ev(`dayTick();S.mp.seq++;mpPush(${lit(t)})`); const c = f.calls.at(-1); return c.url.replace(/.*\//, ''); };
assert.equal(send('{"x":"' + 'a'.repeat(50000) + '"}'), 'save', '50 kB of plain text fits');
await until(() => ev('!MP.busy'));
assert.equal(send('{"x":[' + Array(10000).fill('"ab"').join(',') + ']}'), 'card', '50 kB of text with quotes does not');
await until(() => ev('!MP.busy'));
assert.equal(send('{"x":"' + 'é'.repeat(40000) + '"}'), 'card', '40 000 characters of two bytes do not');
await until(() => ev('!MP.busy'));
for (const c of f.calls.filter((x) => x.keepalive)) assert.ok(Buffer.byteLength(c.raw) < 63000, `${c.url}: ${Buffer.byteLength(c.raw)} bytes`);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: "Load the newer save" never loads an older one; "Keep this one" waits for the day to end', async () => {
const srv = store(), f = fake(srv.routes);
const { dom, ev, errors } = await started({ fetch: f });
const day0 = srv.st.save;
ev("ACT.launchBB({city:'fra'});for(let i=0;i<5;i++)dayTick();MP.last-=16000;save(true)");
await until(() => ev('!MP.busy'));
// The server says it has a newer save (409, number 3) but holds an older one (number 1, day 0).
srv.st.save = day0;
f.routes = [[/^PUT .*\/save$/, { status: 409, json: { error: 'newer', seq: 3, at: 1 } }], ...srv.routes];
ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.stale')));
const day = ev('S.day');
ev('ACT.mpNewer({})');
assert.ok(await until(() => /no newer save/.test(ev("$('toasts').textContent"))));
assert.equal(ev('S.day'), day, 'not rolled back to day 0');
assert.equal(ev('MP.stale'), false);
f.routes = srv.routes;
ev('dayTick();MP.last-=16000;save(true)');
await until(() => ev('!MP.busy'));
assert.equal(srv.day(), ev('S.day'), 'and the next push puts this one on the server');
// Another device pushed number 9 meanwhile; the player keeps theirs, clicking while the day is still routing.
srv.st.save = { ...srv.st.save, seq: 9 };
ev('dayTick();MP.last-=16000;save(true)');
assert.ok(await until(() => ev('MP.stale&&MP.staleSeq===9')));
const k = f.saves().length;
ev('RW.job={};ACT.mpKeep({})');
assert.equal(f.saves().length, k, 'never half a day');
ev('RW.job=null;rwDayDone()');
const kept = f.saves().at(-1);
assert.equal(f.saves().length, k + 1, 'the day\'s end pushes it');
assert.equal(kept.body.force, true);
assert.equal(kept.body.seq, 10, 'past the server\'s number, so it keeps the one it was sent');
await until(() => ev('!MP.busy'));
assert.equal(srv.st.save.seq, 10);
assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp.seq, 10);
assert.equal(ev('MP.force'), false);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: a #mp= link never replaces nor deletes the token this browser has; a busy network is not copied', async () => {
const srv = store(), b = browser(), tab1 = new Map();
const real = (c) => c.method === 'POST' || c.headers.authorization === `Bearer ${PID}.${TOK}`;
const guarded = srv.routes.map(([re, h]) => [re, (c) => (real(c) ? (typeof h === 'function' ? h(c) : h) : { status: 401, json: { error: 'unauthorized' } })]);
const f1 = fake(guarded);
const t1 = await started({ fetch: f1, load: { browser: b, tab: tab1 } });
t1.ev("ACT.launchBB({city:'fra'});for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)");
await until(() => t1.ev('!MP.busy'));
const link = t1.ev('mpLink(S.mp)'), wrong = link.replace(/[0-9a-f]{64}$/, '0'.repeat(64)), tok = () => b.ls.get(`sot-mp:${CODE}:${PID}`);
const slots = () => JSON.parse(b.ls.get('sot-slots')).slots.length;
// A wrong link (a rival's, or one mistyped character) while the game is open in another tab.
const t2 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong });
assert.ok(await until(() => /did not work/.test(t2.ev("$('toasts').textContent"))));
assert.equal(tok(), TOK, 'the real token stays');
assert.equal(slots(), 1);
t1.ev('dayTick();MP.last-=16000;save(true)');
assert.equal(f1.calls.at(-1).headers.authorization, `Bearer ${PID}.${TOK}`, 'and the open tab plays on in its session');
await until(() => t1.ev('!MP.busy'));
assert.equal(t1.ev('MP.gone'), false);
// The right link, while the network is open in the other tab: no second copy, the choice to take it over.
const t3 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: link });
assert.ok(await until(() => t3.ev("!!document.querySelector('#modal [data-act=slotTake]')")), 'offered to take it over');
assert.equal(slots(), 1, 'not copied into a second slot');
// The server away: the link may be fine, so it is not called bad, stays for a reload, and no token changes.
b.close(t1.dom.window);
const t4 = load({ mp: MPA, fetch: fake([[/./, new Error('offline')]]), browser: b, tab: new Map(), url: wrong });
assert.ok(await until(() => /cannot be reached/.test(t4.ev("$('toasts').textContent"))));
assert.equal(t4.ev('location.hash'), new URL(wrong).hash, 'kept for a reload');
assert.equal(tok(), TOK);
// A wrong link once the game's tab is closed: still told, still the real token.
const t5 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong });
assert.ok(await until(() => /did not work/.test(t5.ev("$('toasts').textContent"))));
assert.equal(tok(), TOK);
assert.equal(t5.ev('location.hash'), '', 'a bad link is gone from the address bar');
// A fresh browser, server away: nothing stored at all.
const b2 = browser(), t6 = load({ mp: MPA, fetch: fake([[/./, { status: 503, json: { error: 'busy' } }]]), browser: b2, tab: new Map(), url: link });
assert.ok(await until(() => /cannot be reached/.test(t6.ev("$('toasts').textContent"))));
assert.equal(b2.ls.get(`sot-mp:${CODE}:${PID}`), undefined);
for (const h of [t1, t2, t3, t4, t5, t6]) assert.deepEqual(h.errors.filter((e) => !/moving the network here failed/.test(e)), []);
for (const h of [t1, t2, t3, t4, t5, t6]) h.dom.window.close();
});
test('multiplayer: the session panel\'s refresh while the server is away says so once and never stretches the wait', async () => {
const f = fake([okStart, okSave, [/^GET /, { status: 200, json: roster([me()]) }]]);
const { dom, ev, errors } = await started({ fetch: f });
ev('ACT.mpOpen({})');
await flush();
f.routes = [[/./, new Error('offline')]];
ev("$('toasts').innerHTML=''");
for (let i = 0; i < 6; i++) { ev('mpPollTick()'); await flush(); }
assert.equal(f.calls.filter((c) => c.method === 'GET').length >= 6, true, 'it still looks every few seconds');
assert.equal(ev('MP.fails'), 1);
assert.ok(ev('MP.wait-performance.now()') <= 30000, 'the push back-off stays at its first step');
assert.equal(ev("$('toasts').textContent.split('server is away').length-1"), 1, 'said once');
f.routes = [okSave, [/^GET /, { status: 200, json: roster([me()]) }]];
ev('mpPollTick()');
assert.ok(await until(() => ev('MP.fails===0&&MP.wait===0')), 'back: all forgotten');
const k = f.calls.length;
ev('closeModal();mpPollTick()');
assert.equal(f.calls.length, k, 'a closed panel stops asking');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: with a charter to sign first, the session code and its Share button wait for it', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f });
const doc = dom.window.document;
ev("window.__TUBES_CHARTER__=true;UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Packet Pals';ACT.presetSet({p:'bgp'});ACT.mpStart({})");
assert.ok(await until(() => ev('!!(S&&S.mp)')));
assert.equal(ev("$('modal').className"), 'charter', 'the charter comes first');
assert.equal(doc.querySelector('#toasts [data-act=mpShare]'), null, 'no buttons under it that cannot be pressed');
ev('ACT.charter({k:Object.keys(CHARTERS)[0]})');
const share = doc.querySelector('#toasts [data-act=mpShare]');
assert.ok(share, 'signed: the code to share');
assert.match(doc.getElementById('toasts').textContent, /K7Q-2XD/);
share.click();
assert.match(doc.getElementById('toasts').textContent, /Join my Series of Tubes session K7Q-2XD/, 'and its button works');
assert.deepEqual(errors, []);
dom.window.close();
});