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