Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending

Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push
(docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels.
Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js,
rankings DoS, static headers, ...): fixes follow in the next commit.
NOT done: bots/balance, e2e suite, real-device checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 19:05:03 +02:00
parent 249818a7aa
commit b18645dca1
87 changed files with 10201 additions and 71 deletions

View file

@ -3,6 +3,10 @@ const test = require('node:test');
const assert = require('node:assert');
const I = require('../public/js/i18n.js');
const D = require('../public/js/data.js');
// Strings added by later screens: public/js/strings/*.js, loaded for the parity test the same way the browser loads them.
for (const f of require('fs').readdirSync(require('path').join(__dirname, '..', 'public', 'js', 'strings')).sort()) {
if (f.endsWith('.js')) require('../public/js/strings/' + f);
}
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(',');

83
test/client-mil.test.js Normal file
View file

@ -0,0 +1,83 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const M = require('../public/js/milcore.js');
const D = require('../public/js/data.js');
const land = (settle) => ({ x: 3, y: 4, type: 'land', settle: Object.assign({ possible: true, code: null, footprint: 100, footprintNeeded: 50, maxDistance: 15 }, settle) });
const rival = (owner) => ({ x: 5, y: 5, type: 'pop', town: { id: 9, name: 'R', mine: false, owner: Object.assign({ id: 2, protected: false, allianceId: null }, owner) } });
const types = (o) => o.map((x) => x.type + (x.ok ? '' : '!'));
test('unitsForType: roles, fixed units and zero counts are filtered', () => {
const home = { script_crew: 5, honeypot: 3, port_scanner: 2, soc_analyst: 0, rollout_crew: 3 };
assert.deepStrictEqual(M.unitsForType('raid', home).map((u) => u.unit), ['script_crew']); // honeypot is fixed, scanner is a scout
assert.deepStrictEqual(M.unitsForType('scan', home).map((u) => u.unit), ['port_scanner']);
assert.deepStrictEqual(M.unitsForType('settle', home).map((u) => u.unit), ['rollout_crew']);
assert.deepStrictEqual(M.unitsForType('reinforce', home).map((u) => u.unit), ['port_scanner', 'script_crew', 'rollout_crew']);
assert.deepStrictEqual(M.unitsForType('transport', home), []);
});
test('moveOptions on a rival POP: hostile types need units, protection blocks them, takeover needs an M&A team', () => {
const home = { script_crew: 10, port_scanner: 1 };
assert.deepStrictEqual(types(M.moveOptions({ tile: rival(), home })), ['scan', 'raid', 'attack', 'takeover!']);
assert.strictEqual(M.moveOptions({ tile: rival(), home }).find((o) => o.type === 'takeover').reason, 'needs_ma_team');
const prot = M.moveOptions({ tile: rival({ protected: true }), home });
assert.deepStrictEqual(types(prot), ['scan', 'raid!', 'attack!', 'takeover!']);
assert.strictEqual(prot[1].reason, 'target_protected');
assert.deepStrictEqual(types(M.moveOptions({ tile: rival(), home: {} })), ['scan!', 'raid!', 'attack!', 'takeover!']);
assert.ok(M.moveOptions({ tile: rival(), home: { ma_team: 1, script_crew: 1 } }).find((o) => o.type === 'takeover').ok);
});
test('moveOptions: reinforce only for the same alliance; own POP offers reinforce and transport', () => {
const home = { soc_analyst: 4 };
const ally = rival({ allianceId: 7 });
assert.ok(!M.moveOptions({ tile: ally, home, allianceId: 5 }).some((o) => o.type === 'reinforce'));
assert.ok(M.moveOptions({ tile: ally, home, allianceId: 7 }).some((o) => o.type === 'reinforce' && o.ok));
const mine = { x: 1, y: 1, type: 'pop', town: { id: 3, mine: true, owner: { id: 1 } } };
assert.deepStrictEqual(types(M.moveOptions({ tile: mine, home, transport: { links: 2, active: 2 } })), ['reinforce', 'transport!']);
assert.strictEqual(M.moveOptions({ tile: mine, home, transport: { links: 0, active: 0 } })[1].reason, 'no_link');
assert.deepStrictEqual(types(M.moveOptions({ tile: mine, home, transport: { links: 2, active: 1 } })), ['reinforce', 'transport']);
});
test('moveOptions: incumbent sites take scan and attack; land offers settle with its reason; rural nothing', () => {
assert.deepStrictEqual(types(M.moveOptions({ tile: { type: 'incumbent' }, home: { port_scanner: 1, script_crew: 1 } })), ['scan', 'attack']);
assert.deepStrictEqual(types(M.moveOptions({ tile: land(), home: {}, crews: 3 })), ['settle']);
assert.deepStrictEqual(types(M.moveOptions({ tile: land(), home: {}, crews: 2 })), ['settle!']);
const far = M.moveOptions({ tile: land({ possible: false, code: 'out_of_range' }), home: {}, crews: 3 });
assert.strictEqual(far[0].reason, 'settle:out_of_range');
assert.deepStrictEqual(M.moveOptions({ tile: { type: 'rural' }, home: { script_crew: 1 } }), []);
});
test('defaultUnits / cleanSelection / preview', () => {
assert.deepStrictEqual(M.defaultUnits('settle', {}), { rollout_crew: D.EXPANSION.crews });
assert.deepStrictEqual(M.defaultUnits('raid', {}), {});
assert.deepStrictEqual(M.cleanSelection({ a: 0, script_crew: 99, botnet: 2.7 }, { script_crew: 5, botnet: 1 }), { script_crew: 5, botnet: 1 });
const p = M.preview('raid', { x: 0, y: 0 }, { x: 16, y: 0 }, { script_crew: 10, botnet: 1 }, {}, 1);
assert.strictEqual(p.dist, 16);
assert.strictEqual(p.slowest, 8); // script crew 8 tiles/h
assert.strictEqual(p.ms, 2 * 3600 * 1000);
assert.strictEqual(p.carry, 10 * 50 + 150);
assert.strictEqual(M.preview('transport', { x: 0, y: 0 }, { x: 12, y: 0 }, {}, { fiber: 5 }, 2).ms, 30 * 60 * 1000); // 12 tiles at 12/h and speed 2x = 30 min
});
test('perspective: the report role decides who won', () => {
assert.strictEqual(M.perspective('attacker', 'attacker_won'), 'victory');
assert.strictEqual(M.perspective('attacker', 'defender_won'), 'defeat');
assert.strictEqual(M.perspective('defender', 'attacker_won'), 'defeat');
assert.strictEqual(M.perspective('reinforcer', 'defender_won'), 'victory');
});
test('backoffMs grows to a 60 s cap with +-25% jitter', () => {
assert.strictEqual(M.backoffMs(0, 0.5), 1000);
assert.strictEqual(M.backoffMs(1, 0.5), 2000);
assert.strictEqual(M.backoffMs(3, 0.5), 8000);
assert.strictEqual(M.backoffMs(20, 0.5), 60000);
assert.strictEqual(M.backoffMs(2, 0), 3000);
assert.ok(M.backoffMs(2, 0.999) >= 4990 && M.backoffMs(2, 0.999) <= 5000);
});
test('siegeTargets are infrastructure types only', () => {
const t = M.siegeTargets();
assert.ok(t.includes('firewall') && t.includes('core_router'));
assert.ok(!t.includes('backbone_node') && !t.some((k) => D.BUILDINGS[k].kind !== 'infra'));
});

161
test/client-social.test.js Normal file
View file

@ -0,0 +1,161 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const I = require('../public/js/i18n.js');
const D = require('../public/js/data.js');
const Soc = require('../public/js/social.js');
for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
const S = D.SOCIAL;
test('selfActions follows the permission table and the leader-must-transfer rule', () => {
const leader = Soc.selfActions('leader', 4), officer = Soc.selfActions('officer', 4), diplomat = Soc.selfActions('diplomat', 4), member = Soc.selfActions('member', 4);
assert.ok(leader.invite && leader.disband && leader.diplomacy && leader.editNotes && leader.transfer && leader.setRole);
assert.ok(leader.leaveNeedsTransfer);
assert.ok(!Soc.selfActions('leader', 1).leaveNeedsTransfer, 'alone: leaving disbands, no transfer needed');
assert.ok(officer.invite && officer.viewInvites && officer.editNotes && !officer.diplomacy && !officer.disband && !officer.setRole);
assert.ok(diplomat.diplomacy && diplomat.editNotes && !diplomat.invite);
assert.ok(member.broadcast && !member.invite && !member.editNotes && !member.diplomacy && member.leave && !member.leaveNeedsTransfer);
const none = Soc.selfActions(null, 0);
assert.ok(!none.leave && !none.invite && !none.broadcast);
// every key of SOCIAL.permissions the screens use is derived, not copied
for (const [k, roles] of Object.entries(S.permissions)) {
for (const r of S.roles) {
const a = Soc.selfActions(r, 3);
if (a[k] !== undefined) assert.strictEqual(a[k], roles.includes(r), k + ' for ' + r);
}
}
});
test('memberActions: kick needs permission and strictly higher rank, roles and transfer are leader-only, never on yourself', () => {
const m = (role, id) => ({ operatorId: id || 7, role });
const lead = Soc.memberActions('leader', m('officer'), 1);
assert.ok(lead.kick && lead.transfer && lead.message);
assert.deepStrictEqual(lead.roles.sort(), ['diplomat', 'member']);
assert.deepStrictEqual(Soc.memberActions('leader', m('member'), 1).roles.sort(), ['diplomat', 'officer']);
const off = Soc.memberActions('officer', m('member'), 1);
assert.ok(off.kick && !off.transfer && off.roles.length === 0);
assert.ok(!Soc.memberActions('officer', m('officer'), 1).kick, 'equal rank');
assert.ok(!Soc.memberActions('officer', m('leader'), 1).kick, 'higher rank');
assert.ok(!Soc.memberActions('diplomat', m('member'), 1).kick, 'no kick permission');
assert.ok(!Soc.memberActions('member', m('member'), 1).kick);
const self = Soc.memberActions('leader', m('leader', 1), 1);
assert.ok(self.self && !self.kick && !self.transfer && !self.message && self.roles.length === 0);
assert.strictEqual(Soc.memberActions('leader', m('leader', 9), 1).roles.length, 0, 'the leader role is only moved by transfer');
});
test('diplomacyOptions mirrors SOCIAL.diplomacyMoves and locks pending pairs', () => {
const kinds = (from) => Object.fromEntries(Soc.diplomacyOptions(from, null).map((o) => [o.state, o.kind]));
assert.deepStrictEqual(kinds('neutral'), { war: 'immediate', nap: 'proposal', confed: 'proposal' });
assert.deepStrictEqual(kinds('nap'), { war: 'delayed', neutral: 'delayed', confed: 'proposal' });
assert.deepStrictEqual(kinds('confed'), { war: 'delayed', neutral: 'delayed', nap: 'delayed' });
assert.deepStrictEqual(kinds('war'), { neutral: 'proposal', nap: 'proposal' }, 'war -> confed is not allowed');
assert.deepStrictEqual(Soc.diplomacyOptions('nap', { to: 'neutral' }), []);
});
test('relationTo defaults to neutral and exposes pending changes', () => {
const rels = [{ other: { id: 5 }, state: 'nap', since: 10, pending: { to: 'neutral', effectiveAt: 99, byUs: true } }];
assert.deepStrictEqual(Soc.relationTo(rels, 6), { state: 'neutral', since: null, pending: null });
assert.strictEqual(Soc.relationTo(rels, 5).state, 'nap');
assert.strictEqual(Soc.relationTo(rels, 5).pending.byUs, true);
assert.strictEqual(Soc.pendingRemaining({ effectiveAt: 1000 }, 400), 600);
assert.strictEqual(Soc.pendingRemaining({ effectiveAt: 1000 }, 5000), 0);
assert.strictEqual(Soc.pendingRemaining(null, 5), 0);
});
test('character counting matches the server: code points, CRLF as one', () => {
assert.strictEqual(Soc.charCount('abc'), 3);
assert.strictEqual(Soc.charCount('a\r\nb'), 3);
assert.strictEqual(Soc.charCount('\u{1F680}\u{1F680}'), 2, 'astral characters count once');
assert.strictEqual(Soc.charCount(null), 0);
const ok = Soc.composeState('x'.repeat(S.messageMax));
assert.ok(!ok.over && ok.left === 0 && !ok.empty);
assert.ok(Soc.composeState('x'.repeat(S.messageMax + 1)).over);
assert.ok(Soc.composeState(' \n ').empty);
assert.ok(Soc.composeState('').empty);
assert.strictEqual(Soc.composeState('abc', 10).left, 7);
});
test('retrySeconds is at least 1 and rounds up', () => {
assert.strictEqual(Soc.retrySeconds({ retryAfter: 12.2 }), 13);
assert.strictEqual(Soc.retrySeconds({ retryAfter: 0 }), 1);
assert.strictEqual(Soc.retrySeconds(null), 1);
});
test('message lists merge without duplicates, newest first; conversations read oldest first', () => {
const a = [{ id: 9 }, { id: 8 }], b = [{ id: 8 }, { id: 7 }, { id: 6 }];
assert.deepStrictEqual(Soc.mergeMessages(a, b).map((m) => m.id), [9, 8, 7, 6]);
assert.deepStrictEqual(Soc.chronological([{ id: 3 }, { id: 1 }, { id: 2 }]).map((m) => m.id), [1, 2, 3]);
assert.deepStrictEqual(a.map((m) => m.id), [9, 8], 'inputs are not mutated');
});
test('peerOf and unreadIds', () => {
const inMsg = { id: 1, direction: 'in', from: { operatorId: 2, name: 'b' }, to: { operatorId: 1, name: 'a' }, readAt: null };
const outMsg = { id: 2, direction: 'out', from: { operatorId: 1, name: 'a' }, to: { operatorId: 2, name: 'b' }, readAt: null };
const read = { id: 3, direction: 'in', readAt: 5 };
assert.strictEqual(Soc.peerOf(inMsg).operatorId, 2);
assert.strictEqual(Soc.peerOf(outMsg).operatorId, 2);
assert.deepStrictEqual(Soc.unreadIds([inMsg, outMsg, read]), [1], 'own messages and read ones are not unread');
});
test('ranking pages merge by rank and your row is recognised per kind', () => {
const p1 = [{ rank: 1 }, { rank: 2 }], p2 = [{ rank: 2 }, { rank: 3 }];
assert.deepStrictEqual(Soc.mergeRanks(p1, p2).map((r) => r.rank), [1, 2, 3]);
assert.ok(Soc.isYou('operators', { operatorId: 4 }, { operatorId: 4, rank: 9 }));
assert.ok(!Soc.isYou('operators', { operatorId: 5 }, { operatorId: 4 }));
assert.ok(Soc.isYou('alliances', { allianceId: 2 }, { allianceId: 2 }));
assert.ok(Soc.isYou('battles', { operatorId: 4 }, { operatorId: 4 }));
assert.ok(!Soc.isYou('operators', { operatorId: 4 }, null));
const r = { attackPoints: 30, defensePoints: 12 };
assert.deepStrictEqual(['attack', 'defense', 'total'].map((by) => Soc.battlePoints(r, by)), [30, 12, 42]);
});
test('cleanName collapses whitespace; sinceMs handles never-online', () => {
assert.strictEqual(Soc.cleanName(' Bob the Builder '), 'Bob the Builder');
assert.strictEqual(Soc.cleanName(null), '');
assert.strictEqual(Soc.sinceMs(null, 100), null);
assert.strictEqual(Soc.sinceMs(40, 100), 60);
assert.strictEqual(Soc.sinceMs(400, 100), 0);
});
// ---- strings: every key the three screens use exists in both languages, every role/state/kind has a name
const dir = path.join(__dirname, '..', 'public', 'js', 'screens');
const SRC = ['alliance.js', 'messages.js', 'rankings.js', 'social-ui.js'].map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join('\n');
test('every static i18n key used by the social screens exists in en and nb', () => {
const used = new Set();
for (const m of SRC.matchAll(/\bApp\.t\('([a-zA-Z0-9_.]+)'/g)) if (!m[1].endsWith('.')) used.add(m[1]);
for (const m of SRC.matchAll(/\bt: '([a-zA-Z0-9_.]+)'/g)) used.add(m[1]);
assert.ok(used.size > 100, 'found the keys (' + used.size + ')');
for (const l of I.LANGS) for (const k of used) assert.ok(I.strings[l][k], l + ' is missing ' + k);
});
test('dynamic i18n key families are complete', () => {
const need = [];
for (const r of S.roles) need.push('soc.role.' + r);
for (const s of S.diplomacyStates) need.push('soc.state.' + s);
for (const k of ['immediate', 'proposal', 'delayed']) need.push('soc.kind.' + k, 'soc.kind.' + k + '.hint');
for (const k of ['applied', 'proposed', 'scheduled']) need.push('soc.dip.result.' + k);
for (const k of ['inbox', 'sent', 'alliance']) need.push('soc.msg.empty.' + k);
for (const k of ['attack', 'defense', 'total']) need.push('soc.rank.by.' + k);
for (const k of ['inbox', 'sent', 'alliance', 'blocked']) need.push('soc.msg.tab.' + k);
for (const k of ['operators', 'alliances', 'battles']) need.push('soc.rank.tab.' + k);
for (const k of ['overview', 'members', 'diplomacy']) need.push('soc.tab.' + k);
for (const l of I.LANGS) for (const k of need) assert.ok(I.strings[l][k], l + ' is missing ' + k);
});
test('every error code the social routes can return is translated', () => {
const errors = require('../server/errors');
const social = ['peering_office_required', 'already_in_alliance', 'not_in_alliance', 'alliance_name_taken', 'alliance_tag_taken', 'alliance_full', 'invite_expired',
'leader_must_transfer', 'notes_full', 'diplomacy_invalid', 'diplomacy_pending', 'proposal_exists', 'proposal_expired', 'forbidden', 'not_found', 'conflict', 'rate_limited', 'validation_failed'];
for (const l of I.LANGS) for (const c of social) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c);
const defined = Object.keys(errors.CODES || errors.codes || {});
if (defined.length) for (const c of defined.filter((x) => social.includes(x))) assert.ok(I.strings.en['err.' + c]);
});
test('screens never put player-controlled text through innerHTML', () => {
const code = SRC.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
assert.ok(!/innerHTML|insertAdjacentHTML|outerHTML|document\.write/.test(code), 'no HTML injection sinks in the social screens');
});

137
test/client-ws.test.js Normal file
View file

@ -0,0 +1,137 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createSocketClient } = require('../public/js/ws.js');
// A fake WebSocket and a manual clock: no real timers, no network.
function rig(over) {
const socks = [];
class FakeWS {
constructor(url) { this.url = url; this.sent = []; this.closed = false; socks.push(this); }
send(s) { this.sent.push(JSON.parse(s)); }
close() { this.closed = true; }
// test helpers
open() { this.onopen(); }
recv(o) { this.onmessage({ data: JSON.stringify(o) }); }
drop() { this.onclose(); }
}
const timers = []; let t = 0, seq = 0;
const setTimeout_ = (fn, ms) => { const id = ++seq; timers.push({ id, at: t + ms, fn }); return id; };
const clearTimeout_ = (id) => { const i = timers.findIndex((x) => x.id === id); if (i >= 0) timers.splice(i, 1); };
const advance = (ms) => {
const end = t + ms;
for (;;) {
timers.sort((a, b) => a.at - b.at);
if (!timers.length || timers[0].at > end) break;
const x = timers.shift(); t = x.at; x.fn();
}
t = end;
};
const got = [], states = [];
const client = createSocketClient(Object.assign({
WebSocket: FakeWS, url: () => 'ws://x/ws', token: () => 'tok', random: () => 0.5,
setTimeout: setTimeout_, clearTimeout: clearTimeout_, onMessage: (m) => got.push(m), onState: (s) => states.push(s),
}, over || {}));
return { client, socks, advance, got, states };
}
test('auth is the first message, ready opens the client, hints are passed on', () => {
const r = rig();
r.client.start();
assert.strictEqual(r.socks.length, 1);
r.socks[0].open();
assert.deepStrictEqual(r.socks[0].sent, [{ type: 'auth', token: 'tok' }]);
assert.strictEqual(r.client.open, false);
r.socks[0].recv({ type: 'ready', serverTime: 5 });
assert.strictEqual(r.client.open, true);
r.socks[0].recv({ type: 'town', townId: 3 });
r.socks[0].recv({ type: 'pong' }); // pong is plumbing, not a hint
r.socks[0].onmessage({ data: 'not json' }); // garbage is ignored
assert.deepStrictEqual(r.got, [{ type: 'town', townId: 3 }]);
assert.ok(!JSON.stringify(r.socks[0].url).includes('tok'), 'the token never goes into the URL');
});
test('pings every 25 s; a missing pong drops the socket and reconnects with backoff', () => {
const r = rig();
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
r.advance(25000);
assert.deepStrictEqual(r.socks[0].sent.slice(-1), [{ type: 'ping' }]);
r.socks[0].recv({ type: 'pong' });
r.advance(25000);
assert.strictEqual(r.socks[0].sent.filter((m) => m.type === 'ping').length, 2);
r.advance(8000); // no pong for the second ping
assert.strictEqual(r.socks[0].closed, true);
assert.strictEqual(r.client.open, false);
assert.strictEqual(r.socks.length, 1);
r.advance(1000); // backoff for attempt 0 = 1 s at jitter 0.5
assert.strictEqual(r.socks.length, 2);
});
test('reconnect backoff grows while the server is down and resets after ready', () => {
const r = rig();
r.client.start();
r.socks[0].drop(); // never got ready
r.advance(999); assert.strictEqual(r.socks.length, 1);
r.advance(1); assert.strictEqual(r.socks.length, 2);
r.socks[1].drop();
r.advance(1999); assert.strictEqual(r.socks.length, 2);
r.advance(1); assert.strictEqual(r.socks.length, 3);
r.socks[2].open(); r.socks[2].recv({ type: 'ready' });
assert.strictEqual(r.client.attempts, 0);
r.socks[2].drop();
r.advance(1000); assert.strictEqual(r.socks.length, 4);
});
test('stop() closes for good; kick() connects now; no token means no socket', () => {
const r = rig();
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
r.client.stop();
assert.strictEqual(r.socks[0].closed, true);
r.advance(120000); assert.strictEqual(r.socks.length, 1);
assert.strictEqual(r.client.state, 'idle');
const r2 = rig();
r2.client.start(); r2.socks[0].drop();
r2.client.kick();
assert.strictEqual(r2.socks.length, 2);
const r3 = rig({ token: () => null });
r3.client.start();
assert.strictEqual(r3.socks.length, 0);
});
test('a throwing WebSocket constructor degrades silently and retries', () => {
let n = 0;
const r = rig({ WebSocket: class { constructor() { n++; throw new Error('blocked'); } } });
r.client.start();
assert.strictEqual(n, 1);
r.advance(1000);
assert.strictEqual(n, 2);
});
test('close codes: 4401/4400/1009 stop for good, 4429 waits 30 s, others reconnect', () => {
const fatal = [];
const r = rig({ onFatal: (c) => fatal.push(c) });
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
r.socks[0].onclose({ code: 4401 });
r.advance(300000);
assert.strictEqual(r.socks.length, 1, 'no reconnect after 4401');
assert.deepStrictEqual(fatal, [4401]);
assert.strictEqual(r.client.state, 'idle');
r.client.start(); // a fresh session starts again
assert.strictEqual(r.socks.length, 2);
r.socks[1].onclose({ code: 4429 });
r.advance(29000); assert.strictEqual(r.socks.length, 2);
r.advance(2000); assert.strictEqual(r.socks.length, 3);
r.socks[2].onclose({ code: 1006 });
r.advance(3000); assert.strictEqual(r.socks.length, 4);
});
test('onReady tells a re-connect from the first connect', () => {
const seen = [];
const r = rig({ onReady: (m, again) => seen.push(again) });
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
r.socks[0].onclose({ code: 1006 });
r.advance(1000); r.socks[1].open(); r.socks[1].recv({ type: 'ready' });
assert.deepStrictEqual(seen, [false, true]);
});

501
test/endgame-flow.test.js Normal file
View file

@ -0,0 +1,501 @@
'use strict';
/* End game on the server: sites open at day 100, taking them, shipping, building the node, winning, the end of the world.
* Fake clock, in-memory db; the world is moved to day 100 by advancing the clock (nothing else is pending in these worlds). */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const A = require('../server/alliances');
const E = require('../server/endgame');
const { createEndgameQueries } = require('../server/endgameQueries');
const { R, D, H } = T;
const DAY = 24 * H;
function alliance(h, name, leader, members) {
const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid);
A.addMember(h.db, id, leader.opId, 'leader', h.clock.now());
for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now());
return id;
}
const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); };
// A world at day `day`, with the sites at fixed positions; operators are created AFTER the clock moved so their POPs are fresh.
function world(day, o) {
const h = T.setup(Object.assign({ seed: 4242, radius: 50 }, o));
h.advanceTo(h.world.start_at + Math.round(day * DAY / (h.world.speed || 1)));
h.eg = createEndgameQueries(h);
h.sites = R.backboneSites(h.world.seed, h.world.map_radius);
return h;
}
// An operator next to site `i` with plenty of power so that its units stay online; no production unless asked.
function near(h, name, i, o) {
const s = h.sites[i];
const op = T.addOperator(h, name, Object.assign({ x: s.x - 4, y: s.y, power: 25 }, o || {}));
if (!(o && o.produce)) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%' AND key NOT IN ('f13','f14','f15','f16')", op.townId);
return op;
}
const siteOf = (h, i) => h.db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', h.worldId, i);
const attack = (h, who, i, units, type) => h.run('sendMovement', { userId: who.userId, fromTownId: who.townId, type: type || 'attack', x: h.sites[i].x, y: h.sites[i].y, units });
const defenceNow = (h, i, level) => R.backboneDefence(h.world.seed, h.sites[i].x, h.sites[i].y, R.worldAgeDays(h.world.start_at, h.clock.now(), h.world.speed), level || 0);
test('before day 100: the sites are plain land - cannot be attacked, settled or seen; status says running', () => {
const h = world(99.9);
const a = near(h, 'alice', 0, { units: { script_crew: 50 } });
alliance(h, 'Alpha', a);
const s0 = h.sites[0];
assert.equal(err(() => attack(h, a, 0, { script_crew: 10 })).code, 'backbone_closed');
assert.equal(err(() => attack(h, a, 0, { script_crew: 10 }, 'raid')).code, 'backbone_closed');
// settling the tile is refused although it looks like land: (the crews would otherwise found a POP on the future site)
T.giveUnits(h, a.townId, { rollout_crew: 3 });
h.db.run('UPDATE towns SET footprint = 1e9 WHERE id = ?', a.townId);
const e = err(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: s0.x, y: s0.y, units: { rollout_crew: 3 } }));
assert.equal(e.code, 'invalid_target');
assert.equal(e.details.reason, 'backbone_site');
const st = h.eg.status(a.userId, h.worldId);
assert.equal(st.phase, 'running');
assert.deepEqual(st.sites, []);
assert.equal(st.winner, null);
assert.equal(st.ageDays < 100, true);
assert.equal(h.mq.tileInfo(a.userId, { x: s0.x, y: s0.y }).type, 'land');
assert.equal(h.queries.map(a.userId, { x: s0.x, y: s0.y, r: 2 }).specials.some((s) => s.type === 'backbone'), false);
h.advanceTo(h.world.start_at + 100 * DAY);
assert.equal(h.eg.status(a.userId, h.worldId).phase, 'backbone_open');
});
test('day 100: 7 sites appear (status, map, tile), held by the incumbent; a scan reports the heavy defence', () => {
const h = world(100);
const a = near(h, 'alice', 0, { units: { port_scanner: 100 } });
const st = h.eg.status(a.userId, h.worldId);
assert.equal(st.phase, 'backbone_open');
assert.equal(st.sites.length, 7);
assert.ok(st.sites.every((s) => s.holder === null && s.level === 0 && s.id === null && s.next.toLevel === 1));
assert.deepEqual(st.sites.map((s) => [s.x, s.y]), h.sites.map((s) => [s.x, s.y]));
assert.equal(st.opensAt, h.world.start_at + 100 * DAY);
const m = h.queries.map(a.userId, { x: h.sites[0].x, y: h.sites[0].y, r: 3 });
const sp = m.specials.find((s) => s.type === 'backbone');
assert.ok(sp && sp.x === h.sites[0].x && sp.site.index === 0 && sp.site.holder === null && sp.site.level === 0);
const ti = h.mq.tileInfo(a.userId, { x: h.sites[0].x, y: h.sites[0].y });
assert.equal(ti.type, 'backbone');
assert.equal(ti.backbone.holder, null);
assert.equal(ti.backbone.canAttack, false, 'no alliance, no attack');
assert.equal(ti.settle.possible, false);
// scan (no alliance needed)
const mv = attack(h, a, 0, { port_scanner: 100 }, 'scan');
h.advanceTo(mv.arriveAt);
const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'scan');
assert.equal(rep.data.site.type, 'backbone');
assert.equal(rep.data.success, true);
assert.equal(rep.data.intel.defence, defenceNow(h, 0, 0), 'the scan shows the exact static defence');
assert.ok(rep.data.intel.defence > 10 * R.incumbentDefence(h.world.seed, h.sites[0].x, h.sites[0].y, 100));
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM landing_sites').n, 7, 'the first touch created the rows');
assert.equal(T.notes(h, a.userId, 'backbone_open').length, 1, 'and told the world once');
});
test('taking a site: alliance members only, heavy defence, the winner holds it; losing attackers change nothing; friends and pacts are refused', () => {
const h = world(100);
const a = near(h, 'alice', 0, { units: { script_crew: 1200 } });
const a2 = near(h, 'alice2', 0, { x: h.sites[0].x - 4, y: h.sites[0].y + 3 });
const b = near(h, 'bob', 0, { x: h.sites[0].x + 4, y: h.sites[0].y, units: { script_crew: 300 } });
const loner = near(h, 'loner', 0, { x: h.sites[0].x, y: h.sites[0].y - 5, units: { script_crew: 1200 } });
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
// an operator without an alliance cannot take a site
assert.equal(err(() => attack(h, loner, 0, { script_crew: 1200 })).details.reason, 'no_alliance');
T.giveUnits(h, a.townId, { ma_team: 1 });
assert.equal(err(() => attack(h, a, 0, { script_crew: 10, ma_team: 1 }, 'takeover')).details.reason, 'landing_scan_or_attack_only');
assert.equal(err(() => attack(h, a, 0, { script_crew: 10 }, 'reinforce')).code, 'invalid_target');
// too weak: bob's 300 crews (12 000) against ~40 000: lost, nothing changes
const weak = attack(h, b, 0, { script_crew: 300 });
h.advanceTo(weak.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, null);
const lost = T.reportsOf(h, b.userId).find((r) => r.type === 'landing');
assert.equal(lost.data.outcome, 'defender_won');
assert.equal(lost.data.taken, false);
assert.equal(T.units(h, b.townId).script_crew, undefined, 'all lost');
// alice takes it
const power = 1200 * 40;
assert.ok(power > defenceNow(h, 0, 0) * 1.05);
const mv = attack(h, a, 0, { script_crew: 1200 });
h.advanceTo(mv.arriveAt);
const site = siteOf(h, 0);
assert.equal(site.holder_alliance_id, A1);
assert.equal(site.holder_operator_id, a.opId);
assert.equal(site.taken_at, mv.arriveAt);
assert.equal(site.level, 0);
const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'landing');
assert.equal(rep.data.outcome, 'attacker_won');
assert.equal(rep.data.taken, true);
assert.equal(rep.data.site.holder, null, 'the report says who held it BEFORE');
assert.equal(T.notes(h, a2.userId, 'backbone_taken').length, 1, 'every member of the new holder hears it');
const surv = h.db.get("SELECT units FROM movements WHERE type = 'return' AND owner_id = ?", a.opId);
assert.ok(JSON.parse(surv.units).script_crew > 0 && JSON.parse(surv.units).script_crew < 1200, 'survivors drive home, with losses');
// status and tile now show the holder
const st = h.eg.status(a2.userId, h.worldId);
assert.equal(st.sites[0].holder.allianceId, A1);
assert.equal(st.sites[0].holder.tag, 'ALP');
assert.equal(st.sites[0].takenBy.operatorId, a.opId);
assert.equal(h.mq.tileInfo(a2.userId, { x: h.sites[0].x, y: h.sites[0].y }).backbone.mine, true);
assert.equal(h.mq.tileInfo(b.userId, { x: h.sites[0].x, y: h.sites[0].y }).backbone.canAttack, true);
// the holder's own members cannot attack it; a NAP partner cannot either
T.giveUnits(h, a2.townId, { script_crew: 10 });
assert.equal(err(() => attack(h, a2, 0, { script_crew: 10 })).details.reason, 'own_site');
A.setRelation(h.db, h.worldId, A1, B1, 'nap', h.clock.now());
T.giveUnits(h, b.townId, { script_crew: 10 });
assert.equal(err(() => attack(h, b, 0, { script_crew: 10 })).details.reason, 'pact');
A.setRelation(h.db, h.worldId, A1, B1, 'war', h.clock.now());
});
test('re-checked at arrival: a pact signed while the attack is on the road bounces it', () => {
const h = world(100);
const a = near(h, 'alice', 1, { units: { script_crew: 1200 } });
const b = near(h, 'bob', 1, { x: h.sites[1].x + 4, y: h.sites[1].y });
const A1 = alliance(h, 'Alpha', a), B1 = alliance(h, 'Bravo', b);
// bob's alliance holds the site
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 1', B1, b.opId);
const mv = attack(h, a, 1, { script_crew: 1200 });
A.setRelation(h.db, h.worldId, A1, B1, 'nap', h.clock.now());
h.advanceTo(mv.arriveAt);
assert.equal(siteOf(h, 1).holder_alliance_id, B1, 'not taken');
const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'movement_failed');
assert.equal(rep.data.reason, 'pact');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM movements WHERE type = 'return' AND owner_id = ?", a.opId).n, 1, 'the units come home');
});
test('shipping: members feed the stockpile by transport; strangers cannot; a shipment that arrives after the site changed hands rides home', () => {
const h = world(100);
const a = near(h, 'alice', 2);
const a2 = near(h, 'alice2', 2, { x: h.sites[2].x - 14, y: h.sites[2].y });
const b = near(h, 'bob', 2, { x: h.sites[2].x + 4, y: h.sites[2].y, units: { script_crew: 1300 } });
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 2', A1, a.opId);
const site = siteOf(h, 2);
const stock = (id) => { const t = T.town(h, id); return t.fiber + t.hardware + t.capital; };
assert.equal(err(() => h.run('backboneShip', { userId: b.userId, siteId: site.id, fromTownId: b.townId, cargo: { fiber: 100 } })).code, 'forbidden');
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 100 } })).code, 'not_found', "not your POP");
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 501 } })).code, 'capacity_exceeded');
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: 9999, fromTownId: a2.townId, cargo: { fiber: 5 } })).code, 'not_found');
const before = stock(a2.townId);
const s1 = h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 300, hardware: 200 } });
assert.equal(stock(a2.townId), before - 500, 'it left the POP');
assert.equal(s1.arriveAt - s1.departAt, R.transportMs(R.distance(a2.x, a2.y, site.x, site.y), 1));
h.advanceTo(s1.arriveAt);
let row = siteOf(h, 2);
assert.deepEqual([row.fiber, row.hardware, row.capital], [300, 200, 0]);
assert.deepEqual(h.db.get('SELECT fiber, hardware, capital FROM landing_contributions WHERE site_id = ? AND operator_id = ?', site.id, a2.opId), { fiber: 300, hardware: 200, capital: 0 });
assert.equal(T.notes(h, a2.userId, 'backbone_delivered').length, 1);
assert.equal(stock(a2.townId), before - 500, 'nothing came back: it was delivered');
// second shipment is still on the road when bob takes the site
const s2 = h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { capital: 400 } });
const mid = stock(a2.townId);
const atk = attack(h, b, 2, { script_crew: 1300 });
assert.ok(atk.arriveAt < s2.arriveAt, 'the attack gets there first (a2 lives further away)');
h.advanceTo(s2.arriveAt);
assert.equal(siteOf(h, 2).holder_alliance_id, B1, 'bob took it first');
row = siteOf(h, 2);
assert.deepEqual([row.fiber, row.hardware, row.capital], [300, 200, 0], 'the late shipment was not added to the new holder\'s stockpile, the old stock stayed with the site');
assert.equal(T.notes(h, a2.userId, 'backbone_ship_bounced').length, 1);
assert.equal(stock(a2.townId), mid, 'still on its way home');
h.advance(10 * H);
assert.equal(stock(a2.townId), mid + 400, 'back home: nothing lost');
});
test('building the node: from the stockpile, one level at a time, holders only; the level and the build stay with the site when it is taken', () => {
const h = world(100);
const a = near(h, 'alice', 3);
const a2 = near(h, 'alice2', 3, { x: h.sites[3].x - 4, y: h.sites[3].y + 3 });
const b = near(h, 'bob', 3, { x: h.sites[3].x + 4, y: h.sites[3].y, units: { script_crew: 1300 } });
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 3', A1, a.opId);
const site = siteOf(h, 3);
const build = (who) => h.run('backboneBuild', { userId: who.userId, siteId: site.id });
assert.equal(err(() => build(a)).code, 'not_enough_resources');
assert.equal(err(() => build(b)).code, 'forbidden', 'not a holder');
h.db.run('UPDATE landing_sites SET fiber = 5000, hardware = 4200, capital = 4000 WHERE id = ?', site.id);
const t0 = h.clock.now();
const q = build(a2);
assert.equal(q.toLevel, 1);
assert.deepEqual(q.cost, R.backboneCost(1));
assert.equal(q.dueAt, t0 + R.backboneTimeMs(1, 1));
let row = siteOf(h, 3);
assert.deepEqual([row.fiber, row.hardware, row.capital], [1000, 200, 0], 'paid from the stockpile at once');
assert.equal(row.build_to, 1);
assert.equal(err(() => build(a)).code, 'already_queued');
const view = h.eg.site(a.userId, site.id);
assert.equal(view.site.build.toLevel, 1);
assert.equal(view.you.canBuild, true);
assert.equal(h.eg.site(b.userId, site.id).contributions, undefined, 'the ledger is for holders');
// bob takes the site while level 1 is being built: the level lands on the site for its NEW holder
h.advanceTo(q.dueAt - H);
const atk = attack(h, b, 3, { script_crew: 1300 });
h.advanceTo(atk.arriveAt);
assert.equal(siteOf(h, 3).holder_alliance_id, B1);
assert.equal(siteOf(h, 3).build_to, 1, 'the build runs on');
h.advanceTo(q.dueAt);
row = siteOf(h, 3);
assert.equal(row.level, 1);
assert.equal(row.build_to, null);
assert.equal(row.holder_alliance_id, B1);
assert.equal(err(() => build(a2)).code, 'forbidden', 'alice is a stranger now');
// the node raises the site's defence (level stays with the site)
assert.ok(defenceNow(h, 3, 1) > defenceNow(h, 3, 0));
assert.equal(h.eg.status(a.userId, h.worldId).sites[3].level, 1);
// the new holder pays the next level from what is left in the stockpile
h.db.run('UPDATE landing_sites SET fiber = 9000, hardware = 9000, capital = 9000 WHERE id = ?', site.id);
const q2 = build(b);
assert.equal(q2.toLevel, 2);
assert.deepEqual(q2.cost, R.backboneCost(2));
h.advanceTo(q2.dueAt);
assert.equal(siteOf(h, 3).level, 2);
assert.equal(T.notes(h, b.userId, 'backbone_level').length, 0, 'only every 10th level is announced');
assert.equal(h.db.all("SELECT 1 FROM events WHERE status = 'failed'").length, 0);
});
test('winning: level 100 makes the holder the winner, the world ends two world days later with a ranking, then it is frozen but readable', () => {
const h = world(100, { speed: 2 });
const a = near(h, 'alice', 4, { produce: true });
const a2 = near(h, 'alice2', 4, { x: h.sites[4].x - 4, y: h.sites[4].y + 3 });
const b = near(h, 'bob', 4, { x: h.sites[4].x + 4, y: h.sites[4].y, units: { script_crew: 20 } });
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
T.giveUnits(h, a.townId, { script_crew: 40 });
h.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 12.5, 3), (?, 40, 1)', a.opId, b.opId);
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, level = 99, fiber = 1e7, hardware = 1e7, capital = 1e7 WHERE idx = 4', A1, a.opId);
const site = siteOf(h, 4);
const q = h.run('backboneBuild', { userId: a.userId, siteId: site.id });
assert.equal(q.toLevel, 100);
assert.equal(h.eg.status(a.userId, h.worldId).winner, null);
const wonAt = q.dueAt;
h.advanceTo(wonAt);
const w = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId);
assert.equal(w.winner_alliance_id, A1);
assert.equal(w.winner_name, 'Alpha');
assert.equal(w.won_at, wonAt);
assert.equal(w.status, 'running', 'the world goes on for two days');
assert.equal(w.end_at, wonAt + DAY, 'two WORLD days at speed 2 = one real day');
assert.equal(T.notes(h, b.userId, 'backbone_won').length, 1, 'everybody hears who won');
assert.equal(T.notes(h, a2.userId, 'backbone_level').length, 1);
const st = h.eg.status(b.userId, h.worldId);
assert.equal(st.winner.allianceId, A1); assert.equal(st.winner.tag, 'ALP');
assert.equal(st.endsAt, wonAt + DAY); assert.equal(st.endedAt, null);
assert.equal(st.phase, 'backbone_open');
assert.equal(h.eg.results(b.userId, h.worldId).available, false);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd' AND status = 'pending'").n, 1);
// still playable during the grace period; the winner is fixed even if the site is lost
h.run('renameTown', { userId: a.userId, townId: a.townId, name: 'Still Playing' });
assert.equal(err(() => h.run('backboneBuild', { userId: a.userId, siteId: site.id })).code, 'max_level');
h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' }); // something in the queue that the end will cancel
const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'capital', giveAmount: 100, wantRes: 'fiber', wantAmount: 100, maxDistance: 30 }).offer; // open at the end
h.advanceTo(w.end_at - 1);
assert.equal(h.db.get('SELECT status FROM worlds WHERE id = ?', h.worldId).status, 'running');
h.advanceTo(w.end_at);
const ended = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId);
assert.equal(ended.status, 'ended');
assert.equal(ended.end_at, w.end_at);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", h.worldId).n, 0, 'the world is frozen: nothing pending');
assert.equal(T.notes(h, a.userId, 'world_ended').length, 1);
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired', 'open offers end with the world: the escrow is back in its POP');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE status = 'open'").n, 0);
// the snapshot
const res = h.eg.results(b.userId, h.worldId);
assert.equal(res.available, true);
assert.equal(res.status, 'ended');
assert.equal(res.results.winner.name, 'Alpha');
assert.equal(res.results.operators.length, 3);
assert.deepEqual(res.results.operators.map((o) => o.rank), [1, 2, 3]);
assert.ok(res.results.operators[0].footprint >= res.results.operators[1].footprint);
assert.equal(res.results.alliances.length, 2);
assert.equal(res.results.alliances[0].members + res.results.alliances[1].members, 3);
assert.deepEqual(res.results.attackers.map((o) => o.name), ['bob', 'alice']);
assert.deepEqual(res.results.defenders.map((o) => o.name), ['alice', 'bob']);
assert.equal(res.results.sites.find((s) => s.index === 4).level, 100);
const stored = JSON.parse(h.db.get('SELECT data FROM world_rankings WHERE world_id = ?', h.worldId).data);
assert.deepEqual(stored, res.results);
// ended: every game command is refused with one stable code ...
const refused = (name, args) => assert.equal(err(() => h.run(name, args)).code, 'world_ended', name);
refused('build', { userId: a.userId, townId: a.townId, key: 'firewall' });
refused('renameTown', { userId: a.userId, townId: a.townId, name: 'x' });
refused('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', x: b.x, y: b.y, units: { port_scanner: 1 } });
refused('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: a2.townId, cargo: { fiber: 1 } });
refused('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 });
refused('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: 10, wantRes: 'capital', wantAmount: 10, maxDistance: 5 });
refused('tradeAccept', { userId: a.userId, offerId: 1, townId: a.townId });
refused('backboneBuild', { userId: a.userId, siteId: site.id });
refused('backboneShip', { userId: a.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 1 } });
refused('allianceCreate', { userId: a2.userId, worldId: h.worldId, name: 'New', tag: 'NW' });
refused('allianceLeave', { userId: a2.userId, allianceId: A1 });
refused('diploPropose', { userId: a.userId, allianceId: A1, targetId: B1, state: 'war' });
refused('reportShare', { userId: a.userId, reportId: 1 });
refused('recallMovement', { userId: a.userId, movementId: 1 });
refused('joinWorld', { userId: a.userId, worldId: h.worldId });
// ... except reading state and talking
h.run('markReportRead', { userId: a.userId, all: true });
assert.equal(h.run('messageSend', { userId: a.userId, toOperatorId: b.opId, text: 'gg' }).recipients, 1);
// ... and everything stays readable
assert.equal(h.queries.map(a.userId, { x: 0, y: 0, r: 40 }).world.status, 'ended');
assert.ok(h.queries.map(a.userId, { x: 0, y: 0, r: 40 }).specials.some((s) => s.type === 'backbone'));
assert.ok(h.mq.reports(a.userId, {}).items.length >= 0);
assert.ok(h.queries.town(a.userId, a.townId).town.id === a.townId);
assert.equal(h.eg.status(a.userId, h.worldId).phase, 'ended');
assert.equal(h.eg.status(a.userId, h.worldId).endedAt, w.end_at);
assert.equal(h.eg.site(a.userId, site.id).site.level, 100);
// running it again changes nothing (idempotent)
const snap = JSON.stringify(h.db.get('SELECT * FROM world_rankings'));
require('../server/events/worldEnd')(Object.assign(h.ctx(), { now: w.end_at }), { id: 0, worldId: h.worldId, dueAt: w.end_at + 5, payload: {} });
assert.equal(JSON.stringify(h.db.get('SELECT * FROM world_rankings')), snap);
});
test('winner is fixed at level 100: losing the node during the grace period does not change it; a disbanded holder leaves the site to the incumbent (level stays)', () => {
const h = world(100);
const a = near(h, 'alice', 5);
const b = near(h, 'bob', 5, { x: h.sites[5].x + 4, y: h.sites[5].y, units: { script_crew: 4700 } });
const A1 = alliance(h, 'Alpha', a), B1 = alliance(h, 'Bravo', b);
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, level = 99, fiber = 1e7, hardware = 1e7, capital = 1e7 WHERE idx = 5', A1, a.opId);
const site = siteOf(h, 5);
const q = h.run('backboneBuild', { userId: a.userId, siteId: site.id });
h.advanceTo(q.dueAt);
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1);
const atk = attack(h, b, 5, { script_crew: 4700 });
h.advanceTo(atk.arriveAt);
assert.equal(siteOf(h, 5).holder_alliance_id, B1, 'bob took the finished node');
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1, 'but alice\'s alliance already won');
// the site keeps its level when its holder disbands
A.dissolve(Object.assign(h.ctx(), { scheduler: h.scheduler }), B1, 'test');
assert.equal(siteOf(h, 5).holder_alliance_id, null);
assert.equal(siteOf(h, 5).level, 100);
assert.equal(h.eg.status(a.userId, h.worldId).sites[5].holder, null);
});
test('a finished node taken while nobody wins yet completes for the new holder; only one winner per world', () => {
const h = world(100);
const a = near(h, 'alice', 6, { units: { script_crew: 4700 } });
const A1 = alliance(h, 'Alpha', a);
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET level = 100 WHERE idx = 6'); // finished while its holder was disbanded: nobody won
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, null);
const atk = attack(h, a, 6, { script_crew: 4700 });
h.advanceTo(atk.arriveAt);
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd'").n, 1);
// a second node reaching 100 does not start a second ending
const ctx = h.ctx();
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET level = 100, holder_alliance_id = ? WHERE idx = 0', A1);
assert.equal(E.maybeWin(ctx, siteOf(h, 0), h.clock.now()), false);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd'").n, 1);
});
test('ended worlds over HTTP: reads work, writes say world_ended; status and results routes follow their schemas', async () => {
const { createTestServer } = require('./helpers');
const t = await createTestServer({ contract: true });
try {
const a = await t.signup('alice');
const w = t.srv.db.get('SELECT * FROM worlds');
let r = await t.api('/worlds/' + w.id + '/status', {}, a.token);
assert.equal(r.status, 200);
assert.equal(r.body.phase, 'running');
assert.equal((await t.api('/worlds/999/status', {}, a.token)).status, 404);
assert.equal((await t.api('/worlds/' + w.id + '/status')).status, 401);
r = await t.api('/worlds/' + w.id + '/results', {}, a.token);
assert.equal(r.body.available, false);
// jump to the end
t.srv.db.run("UPDATE worlds SET winner_alliance_id = NULL, winner_name = 'Win', winner_tag = 'WIN', won_at = ?, end_at = ?, start_at = ? WHERE id = ?", t.clock.now(), t.clock.now() + 1000, t.clock.now() - 101 * DAY, w.id);
t.srv.scheduler.enqueue({ worldId: w.id, dueAt: t.clock.now() + 1000, type: 'worldEnd', payload: {} });
t.clock.advance(1000);
r = await t.api('/worlds/' + w.id + '/status', {}, a.token);
assert.equal(r.body.phase, 'ended');
assert.equal(r.body.winner.name, 'Win');
assert.equal(r.body.sites.length, 7);
r = await t.api('/worlds/' + w.id + '/results', {}, a.token);
assert.equal(r.body.available, true);
assert.equal(r.body.results.operators[0].name, 'alice');
const build = await t.api('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'firewall' } }, a.token);
assert.equal(build.status, 409);
assert.equal(build.body.error.code, 'world_ended');
for (const p of ['/me', '/map?x=0&y=0&r=5', '/reports', '/rankings/operators', '/rankings/alliances', '/rankings/battles', '/towns/' + a.townId, '/movements', '/trade/offers', '/notifications', '/map/tile?x=0&y=0']) {
const g = await t.api(p, {}, a.token);
assert.equal(g.status, 200, p + ' -> ' + JSON.stringify(g.body).slice(0, 200));
}
const post = await t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 10, wantRes: 'capital', wantAmount: 10, maxDistance: 5 } }, a.token);
assert.equal(post.body.error.code, 'world_ended');
} finally { await t.close(); }
});
test('backbone routes over HTTP: site detail, ship, build follow their schemas and permissions', async () => {
const { createTestServer } = require('./helpers');
const t = await createTestServer({ contract: true });
try {
const lead = await t.signupPeering('lead'), mem = await t.signupPeering('mem'), out = await t.signup('outsider');
t.setBuilding(mem.townId, 'internet_exchange', 2);
const w = t.srv.db.get('SELECT * FROM worlds');
assert.equal((await t.api('/backbone/1', {}, lead.token)).status, 404, 'no such site yet');
t.srv.db.run('UPDATE worlds SET start_at = ? WHERE id = ?', t.clock.now() - 101 * DAY, w.id);
const mk = await t.api('/alliances', { method: 'POST', body: { name: 'Backers', tag: 'BKR' } }, lead.token);
const inv = await t.api('/alliances/' + mk.body.allianceId + '/invite', { method: 'POST', body: { operatorId: mem.operatorId } }, lead.token);
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, mem.token);
const world = require('../server/state').loadWorld(t.srv.db, w.id);
E.ensureSites(t.srv.db, world, t.clock.now());
t.srv.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 0', mk.body.allianceId, lead.operatorId);
const site = t.srv.db.get('SELECT * FROM landing_sites WHERE idx = 0');
let r = await t.api('/worlds/' + w.id + '/status', {}, out.token);
assert.equal(r.body.phase, 'backbone_open');
assert.equal(r.body.sites[0].holder.tag, 'BKR');
r = await t.api('/backbone/' + site.id, {}, out.token);
assert.equal(r.status, 200);
assert.equal(r.body.you.holder, false);
assert.equal(r.body.contributions, undefined);
r = await t.api('/backbone/' + site.id, {}, mem.token);
assert.equal(r.body.you.canBuild, true);
assert.deepEqual(r.body.contributions, []);
// strangers: 403 on ship and build
assert.equal((await t.api('/backbone/' + site.id + '/ship', { method: 'POST', body: { fromTownId: out.townId, cargo: { fiber: 5 } } }, out.token)).status, 403);
assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, out.token)).status, 403);
assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, mem.token)).body.error.code, 'not_enough_resources');
const ship = await t.api('/backbone/' + site.id + '/ship', { method: 'POST', body: { fromTownId: mem.townId, cargo: { fiber: 100, capital: 50 } } }, mem.token);
assert.equal(ship.status, 201);
assert.equal(ship.body.siteId, site.id);
assert.equal(ship.body.toTownId, null);
const mv = await t.api('/movements', {}, mem.token);
assert.equal(mv.body.outgoing[0].siteId, site.id, 'the movement list says it is a shipment to a site');
t.clock.advance(ship.body.arriveAt - t.clock.now());
t.srv.scheduler.runDue();
r = await t.api('/backbone/' + site.id, {}, lead.token);
assert.deepEqual(r.body.site.pool, { fiber: 100, hardware: 0, capital: 50 });
assert.deepEqual(r.body.contributions.map((c) => [c.name, c.fiber, c.capital]), [['mem', 100, 50]]);
t.srv.db.run('UPDATE landing_sites SET fiber = 4000, hardware = 4000, capital = 4000 WHERE id = ?', site.id);
const b = await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, lead.token);
assert.equal(b.status, 201);
assert.equal(b.body.toLevel, 1);
assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, lead.token)).body.error.code, 'already_queued');
t.clock.advance(b.body.dueAt - t.clock.now());
t.srv.scheduler.runDue();
r = await t.api('/worlds/' + w.id + '/status', {}, out.token);
assert.equal(r.body.sites[0].level, 1);
assert.equal(r.body.sites[0].build, null);
const map = await t.api('/map?x=' + site.x + '&y=' + site.y + '&r=2', {}, out.token);
const sp = map.body.specials.find((x) => x.type === 'backbone');
assert.equal(sp.site.level, 1);
assert.equal(sp.site.holder.tag, 'BKR');
const tile = await t.api('/map/tile?x=' + site.x + '&y=' + site.y, {}, lead.token);
assert.equal(tile.body.type, 'backbone');
assert.equal(tile.body.backbone.mine, true);
} finally { await t.close(); }
});

177
test/endgame-gaps.test.js Normal file
View file

@ -0,0 +1,177 @@
'use strict';
/* Gaps closed next to the end game: buildDone after exploit-kit damage, confederation sees incoming, shared reports. */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D, H } = T;
const level = (h, townId, key) => h.db.get('SELECT level FROM buildings WHERE town_id = ? AND key = ?', townId, key).level;
test('buildDone: an upgrade in flight lands ONE level above whatever the building is now (exploit kits cannot be undone by it)', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice', { infra: { firewall: 5, core_router: 10 } });
const q = h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' });
assert.equal(q.toLevel, 6);
// exploit kits hit the firewall while the upgrade is being built (siege writes the level directly)
h.db.run("UPDATE buildings SET level = 2 WHERE town_id = ? AND key = 'firewall'", a.townId);
h.advanceTo(q.dueAt);
assert.equal(level(h, a.townId, 'firewall'), 3, 'the finished level adds one to the damaged building, it does not restore the queued level');
const done = T.notes(h, a.userId, 'build_done');
assert.equal(done[done.length - 1].level, 3, 'the notification reports the real level');
});
test('buildDone: a building knocked down to 0 while its upgrade is queued comes back at level 1; an undamaged one still gets +1', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice', { infra: { firewall: 4, noc: 5, core_router: 10 } });
const q1 = h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' }); // 4 -> 5
const q2 = h.run('build', { userId: a.userId, townId: a.townId, key: 'noc' }); // 5 -> 6 (second slot: core router 10)
h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key = 'firewall'", a.townId);
h.advanceTo(Math.max(q1.dueAt, q2.dueAt));
assert.equal(level(h, a.townId, 'firewall'), 1);
assert.equal(level(h, a.townId, 'noc'), 6);
});
test('buildDone: a brand-new infrastructure building appears at level 1 (no row yet)', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice', { infra: { core_router: 10 } });
h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'firewall'", a.townId);
const q = h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' });
h.advanceTo(q.dueAt);
assert.equal(level(h, a.townId, 'firewall'), 1);
});
// ---- helpers: alliances without the HTTP layer
const A = require('../server/alliances');
function alliance(h, name, leader, members) {
const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid);
A.addMember(h.db, id, leader.opId, 'leader', h.clock.now());
for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now());
return id;
}
test('confederation: members see each other\'s incoming movements (origin and ETA, type hidden), strangers and neutrals do not', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice', { x: 5, y: 0 });
const a2 = T.addOperator(h, 'alice2', { x: 5, y: 6 });
const b = T.addOperator(h, 'bob', { x: 9, y: 0 });
const c = T.addOperator(h, 'cat', { x: 14, y: 0, units: { script_crew: 20 } });
const d = T.addOperator(h, 'dan', { x: 20, y: 0 });
const X = alliance(h, 'Xray', a, [a2]), Y = alliance(h, 'Yankee', b);
const sent = h.run('sendMovement', { userId: c.userId, fromTownId: c.townId, type: 'attack', toTownId: b.townId, units: { script_crew: 20 } });
// neutral: nobody but the target is told
assert.equal(h.mq.movements(a.userId, {}).alliedIncoming.length, 0);
assert.equal(h.mq.movements(b.userId, {}).incoming.length, 1);
A.setRelation(h.db, h.worldId, X, Y, 'confed', h.clock.now());
for (const who of [a, a2]) {
const l = h.mq.movements(who.userId, {});
assert.equal(l.alliedIncoming.length, 1, who.name + ' sees the attack on the confederate');
const m = l.alliedIncoming[0];
assert.equal(m.id, sent.movementId);
assert.equal(m.type, 'unknown');
assert.equal(m.units, undefined);
assert.equal(m.arriveAt, sent.arriveAt);
assert.equal(m.from.townId, c.townId);
assert.equal(m.to.townId, b.townId);
assert.equal(m.toOperator.id, b.opId);
assert.equal(l.incoming.length, 0, 'the personal incoming list is only about your own POPs');
}
const bl = h.mq.movements(b.userId, {});
assert.equal(bl.incoming.length, 1, 'bob is the target himself');
assert.equal(bl.alliedIncoming.length, 0, 'nothing is heading for his confederates');
assert.equal(h.mq.movements(d.userId, {}).alliedIncoming.length, 0, 'a stranger sees nothing');
assert.equal(h.mq.movements(c.userId, {}).alliedIncoming.length, 0);
// an attack on alice shows up for bob, but alice2's own reinforcement of alice is friendly traffic and does not
h.db.run("UPDATE movements SET status = 'done'");
T.giveUnits(h, a2.townId, { soc_analyst: 5 });
T.giveUnits(h, c.townId, { script_crew: 5 });
h.run('sendMovement', { userId: a2.userId, fromTownId: a2.townId, type: 'reinforce', toTownId: a.townId, units: { soc_analyst: 5 } });
const atk = h.run('sendMovement', { userId: c.userId, fromTownId: c.townId, type: 'raid', toTownId: a.townId, units: { script_crew: 1 } });
const bl2 = h.mq.movements(b.userId, {});
assert.deepEqual(bl2.alliedIncoming.map((m) => m.id), [atk.movementId]);
assert.equal(h.mq.movements(a.userId, {}).incoming.length, 2, 'alice herself sees both, types hidden');
// the confederation ends: the window closes
A.setRelation(h.db, h.worldId, X, Y, 'neutral', h.clock.now());
assert.equal(h.mq.movements(b.userId, {}).alliedIncoming.length, 0);
});
// ---- shared report folder (HTTP, so routes, permissions and schemas are covered)
const { createTestServer } = require('./helpers');
const { createReport } = require('../server/military/reports');
test('shared reports: share, list, read, permissions, retention, unshare', async () => {
const t = await createTestServer({ contract: true });
try {
const lead = await t.signupPeering('lead'), mem = await t.signupPeering('mem'), out = await t.signupPeering('outsider');
const mk = await t.api('/alliances', { method: 'POST', body: { name: 'Folder', tag: 'FLD' } }, lead.token);
const aid = mk.body.allianceId;
const inv = await t.api('/alliances/' + aid + '/invite', { method: 'POST', body: { operatorId: mem.operatorId } }, lead.token);
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, mem.token);
// two reports: one for lead, one for outsider
const ctx = { db: t.srv.db, enqueue: (e) => t.srv.scheduler.enqueue(e), notify: () => {} };
const now = t.clock.now();
const rid = createReport(ctx, { worldId: 1, type: 'raid', now, summary: { s: 1 }, data: { secret: 'x' }, recipients: [{ userId: lead.userId, role: 'attacker' }] });
const rid2 = createReport(ctx, { worldId: 1, type: 'scan', now, summary: {}, data: {}, recipients: [{ userId: out.userId, role: 'attacker' }] });
// sharing needs to be a recipient and an alliance member
assert.equal((await t.api('/reports/' + rid2 + '/share', { method: 'POST' }, lead.token)).status, 404, 'not your report');
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'POST' }, out.token)).status, 404, 'a stranger cannot even see it exists');
const outRep = createReport(ctx, { worldId: 1, type: 'raid', now, summary: {}, data: {}, recipients: [{ userId: out.userId, role: 'attacker' }] });
const noAll = await t.api('/reports/' + outRep + '/share', { method: 'POST' }, out.token);
assert.equal(noAll.body.error.code, 'not_in_alliance');
// the folder is empty, only members read it
assert.deepEqual((await t.api('/alliances/' + aid + '/reports', {}, mem.token)).body.items, []);
assert.equal((await t.api('/alliances/' + aid + '/reports', {}, out.token)).status, 403);
// share; retention is pushed out; repeating is a no-op
t.clock.advance(10 * 24 * 3600e3);
const sh = await t.api('/reports/' + rid + '/share', { method: 'POST' }, lead.token);
assert.equal(sh.status, 200);
assert.equal(sh.body.changed, true);
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'POST' }, lead.token)).body.changed, false);
const exp = t.srv.db.get('SELECT expires_at FROM reports WHERE id = ?', rid).expires_at;
assert.equal(exp, t.clock.now() + D.MILITARY.reportRetentionMs, 'shared report is kept 14 days from the share');
// the member reads it although they were never a participant; the stranger still cannot
const list = await t.api('/alliances/' + aid + '/reports', {}, mem.token);
assert.equal(list.body.items.length, 1);
assert.equal(list.body.items[0].id, rid);
assert.equal(list.body.items[0].sharedBy.name, 'lead');
const one = await t.api('/alliances/' + aid + '/reports/' + rid, {}, mem.token);
assert.equal(one.body.report.data.secret, 'x');
assert.equal((await t.api('/alliances/' + aid + '/reports/' + rid, {}, out.token)).status, 403);
assert.equal((await t.api('/reports/' + rid, {}, mem.token)).status, 404, 'the personal report list is unchanged: sharing is not handing out the participant role');
// the member cannot remove the leader's share; the leader can; the report row survives it
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'DELETE' }, mem.token)).status, 403);
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'DELETE' }, lead.token)).body.changed, true);
assert.equal((await t.api('/alliances/' + aid + '/reports', {}, mem.token)).body.items.length, 0);
assert.ok(t.srv.db.get('SELECT 1 AS x FROM reports WHERE id = ?', rid));
// a member shares their own; deleting the report (cleanup) takes the share with it
const mrep = createReport(ctx, { worldId: 1, type: 'raid', now: t.clock.now(), summary: {}, data: {}, recipients: [{ userId: mem.userId, role: 'defender' }] });
assert.equal((await t.api('/reports/' + mrep + '/share', { method: 'POST' }, mem.token)).status, 200);
assert.equal((await t.api('/reports/' + mrep + '/share', { method: 'DELETE' }, mem.token)).status, 200, 'the sharer may remove their own');
await t.api('/reports/' + mrep + '/share', { method: 'POST' }, mem.token);
t.srv.db.run('DELETE FROM reports WHERE id = ?', mrep);
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM report_shares WHERE report_id = ?', mrep).n, 0);
// cursor: newest first, next page holds older ones
const ids = [];
for (let i = 0; i < 3; i++) {
const r = createReport(ctx, { worldId: 1, type: 'raid', now: t.clock.now(), summary: {}, data: {}, recipients: [{ userId: lead.userId, role: 'attacker' }] });
await t.api('/reports/' + r + '/share', { method: 'POST' }, lead.token);
ids.push(r);
}
const p1 = await t.api('/alliances/' + aid + '/reports?limit=2', {}, lead.token);
assert.deepEqual(p1.body.items.map((i) => i.id), [ids[2], ids[1]]);
const p2 = await t.api('/alliances/' + aid + '/reports?limit=2&after=' + p1.body.next, {}, lead.token);
assert.deepEqual(p2.body.items.map((i) => i.id), [ids[0]]);
assert.equal(p2.body.next, null);
} finally { await t.close(); }
});

128
test/endgame-rules.test.js Normal file
View file

@ -0,0 +1,128 @@
'use strict';
/* End game and trade rules as pure functions (public/js/rules.js, data.js). */
const test = require('node:test');
const assert = require('node:assert');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
test('backbone sites: 7 fixed positions per (seed, radius), on plain land, spread out, never in the free centre, deterministic', () => {
for (const [seed, radius] of [[4242, 50], [1, 50], [99, 20], [7, 150], [123456, 30]]) {
const sites = R.backboneSites(seed, radius);
assert.equal(sites.length, D.ENDGAME.sites, 'seed ' + seed + ' radius ' + radius);
assert.deepEqual(sites.map((s) => s.index), [0, 1, 2, 3, 4, 5, 6]);
for (const s of sites) {
assert.equal(R.terrainAt(seed, radius, s.x, s.y).type, 'land');
assert.ok(Math.abs(s.x) > 2 || Math.abs(s.y) > 2, 'not in the free centre');
assert.ok(Math.abs(s.x) <= radius && Math.abs(s.y) <= radius);
for (const o of sites) if (o !== s) assert.ok(R.distance(s.x, s.y, o.x, o.y) >= D.ENDGAME.siteMinSpacing, 'spacing');
}
assert.deepEqual(R.backboneSites(seed, radius), sites, 'same input, same answer');
}
assert.notDeepEqual(R.backboneSites(1, 50), R.backboneSites(2, 50), 'the seed decides');
});
test('tileAt: a landing site is plain land until world day openDay, then reads backbone; old 4-argument callers see no change', () => {
const seed = 4242, radius = 50;
const s = R.backboneSites(seed, radius)[3];
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y), { type: 'land' });
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, 0), { type: 'land' });
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, D.ENDGAME.openDay - 0.001), { type: 'land' });
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, D.ENDGAME.openDay), { type: 'backbone', site: 3 });
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, 500), { type: 'backbone', site: 3 });
// every other tile is identical with and without age
let seen = 0;
for (let x = -radius; x <= radius; x += 1) for (let y = -radius; y <= radius; y += 3) {
const a = R.tileAt(seed, radius, x, y), b = R.tileAt(seed, radius, x, y, 1000);
if (b.type === 'backbone') { seen++; assert.ok(R.isBackboneSite(seed, radius, x, y)); } else assert.deepEqual(a, b);
}
assert.ok(seen >= 1);
assert.equal(R.tileAt(seed, radius, radius + 1, 0, 1000).type, 'void');
});
test('spawning and settling never use a landing site, not even before it shows', () => {
const seed = 4242, radius = 50;
const sites = R.backboneSites(seed, radius);
const towns = [];
for (let n = 0; n < 150; n++) {
const p = R.pickSpawn(seed, radius, n, towns);
if (!p) break;
assert.ok(!sites.some((s) => s.x === p.x && s.y === p.y), 'spawn ' + n + ' on a landing site');
towns.push(p);
}
assert.ok(towns.length > 100);
const s = sites[0];
const ok = { tileType: 'land', occupied: false, nearestOwnDist: 3, ownedCount: 1, footprint: 1e9 };
assert.equal(R.settleCheck(ok).ok, true);
const refused = R.settleCheck(Object.assign({ backbone: R.isBackboneSite(seed, radius, s.x, s.y) }, ok));
assert.equal(refused.ok, false);
assert.equal(refused.reason, 'backbone_site');
assert.equal(R.settleCheck({ tileType: 'backbone', occupied: false, nearestOwnDist: 3, ownedCount: 1, footprint: 1e9 }).ok, false);
});
test('world phase and age: running, backbone_open from day 100 / speed, ended wins over everything', () => {
const DAY = 24 * 3600e3;
assert.equal(R.worldAgeDays(1000, 1000, 1), 0);
assert.equal(R.worldAgeDays(1000, 1000 - 5, 1), 0, 'never negative');
assert.equal(R.worldAgeDays(0, 10 * DAY, 3), 30);
assert.equal(R.worldPhase('running', 99.9), 'running');
assert.equal(R.worldPhase('running', 100), 'backbone_open');
assert.equal(R.worldPhase('ended', 5), 'ended');
assert.equal(R.worldPhase('ended', 500), 'ended');
// speed 4: day 100 of world time arrives after 25 real days
assert.ok(R.worldAgeDays(0, 25 * DAY, 4) >= D.ENDGAME.openDay);
});
test('backbone defence grows with world age and node level; cost and time curves are monotonic and far above any other building', () => {
const seed = 4242;
const d0 = R.backboneDefence(seed, 10, 10, 100, 0), d50 = R.backboneDefence(seed, 10, 10, 100, 50), dOld = R.backboneDefence(seed, 10, 10, 200, 0);
assert.ok(d50 > d0 && dOld > d0);
assert.equal(R.backboneDefence(seed, 10, 10, 100, 0), Math.round(R.incumbentDefence(seed, 10, 10, 100) * D.ENDGAME.defenceMult));
assert.ok(d0 > 10 * R.incumbentDefence(seed, 10, 10, 100), 'heavy: well above an ordinary incumbent site');
let prev = 0, prevT = 0, sumFiber = 0;
for (let l = 1; l <= D.ENDGAME.maxLevel; l++) {
const c = R.backboneCost(l), t = R.backboneTimeMs(l, 1);
assert.ok(c.fiber > prev && t > prevT, 'level ' + l);
prev = c.fiber; prevT = t; sumFiber += c.fiber;
}
assert.equal(R.backboneCost(1).fiber, D.BUILDINGS.backbone_node.cost.fiber);
assert.ok(R.backboneCost(1).fiber > R.buildingCost('rollout_depot', 1).fiber * 10, 'level 1 already dwarfs the dearest ordinary building level 1');
assert.ok(R.backboneCost(D.ENDGAME.maxLevel).fiber > R.buildingCost('rack_hall', 20).fiber, 'level 100 > the best ordinary building');
assert.equal(R.backboneTimeMs(1, 4), R.backboneTimeMs(1, 1) / 4, 'world speed divides');
assert.ok(sumFiber > 1e6, 'millions in total (a first guess, not balanced)');
});
test('backbonePlan: one level at a time, paid from the pool', () => {
const pool = (n) => ({ fiber: n, hardware: n, capital: n });
assert.equal(R.backbonePlan({ level: 0, build: null, pool: pool(100) }, 1).code, 'not_enough_resources');
assert.equal(R.backbonePlan({ level: 0, build: null, pool: { fiber: 4000, hardware: 4000, capital: 3999 } }, 1).code, 'not_enough_resources');
const ok = R.backbonePlan({ level: 0, build: null, pool: pool(4000) }, 1);
assert.equal(ok.ok, true); assert.equal(ok.toLevel, 1); assert.deepEqual(ok.cost, R.backboneCost(1));
assert.equal(R.backbonePlan({ level: 3, build: { to: 4 }, pool: pool(1e9) }, 1).code, 'already_queued');
assert.equal(R.backbonePlan({ level: 100, build: null, pool: pool(1e12) }, 1).code, 'max_level');
});
test('trade terms: ratio band 1:2 both ways, one transport link per side, distinct resources, whole numbers', () => {
const t = (o) => R.tradeTermsCheck(Object.assign({ giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: 10 }, o));
assert.equal(t().ok, true);
assert.equal(t({ giveAmount: 200, wantAmount: 100 }).ok, true);
assert.equal(t({ giveAmount: 100, wantAmount: 200 }).ok, true);
assert.equal(t({ giveAmount: 201, wantAmount: 100 }).code, 'trade_ratio');
assert.equal(t({ giveAmount: 100, wantAmount: 201 }).code, 'trade_ratio');
assert.equal(t({ giveAmount: D.TRANSPORT.capacityPerLink, wantAmount: D.TRANSPORT.capacityPerLink }).ok, true);
assert.equal(t({ giveAmount: D.TRANSPORT.capacityPerLink + 1, wantAmount: D.TRANSPORT.capacityPerLink }).code, 'capacity_exceeded');
assert.equal(t({ wantRes: 'fiber' }).code, 'validation_failed');
assert.equal(t({ giveRes: 'power' }).code, 'validation_failed');
assert.equal(t({ giveAmount: 0.5 }).code, 'validation_failed');
assert.equal(t({ maxDistance: 0 }).code, 'validation_failed');
assert.equal(R.tradeReach(0), 0);
assert.equal(R.tradeReach(3), 3 * D.TRADE.reachPerLevel);
assert.equal(R.tradeInRange(10, 10, 1), true);
assert.equal(R.tradeInRange(10.01, 20, 1), false, "the taker's reach limits");
assert.equal(R.tradeInRange(5, 4, 5), false, "the offer's max distance limits");
assert.equal(R.tradeInRange(1, 50, 0), false, 'no exchange');
});
test('data: the end-game level cap matches the Backbone node building', () => {
assert.equal(D.ENDGAME.maxLevel, D.BUILDINGS.backbone_node.maxLevel);
assert.equal(D.BUILDINGS.backbone_node.special, 'backbone');
});

189
test/push-game.test.js Normal file
View file

@ -0,0 +1,189 @@
'use strict';
/* Which hint goes to whom (server/pushHooks.js), end to end: REST commands and the event queue on a fake clock, real
* WebSocket clients. Push is only a hint: every assertion on a hint is paired with the REST/DB truth it points at. */
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const { login, sleep } = require('./push-helpers');
const D = require('../public/js/data.js');
const H = D.HOUR_MS;
const post = (body) => ({ method: 'POST', body });
test('build: command hint on all devices of the owner, then town + notification when it finishes; nothing for others', async () => {
const t = await createTestServer();
try {
const alice = await t.signup('alice'), bob = await t.signup('bobby');
const login2 = await t.api('/auth/login', post({ username: 'alice', password: 'correct horse battery' }));
const a1 = await login(t.srv, alice.token), a2 = await login(t.srv, login2.body.token), b = await login(t.srv, bob.token);
const r = await t.api('/towns/' + alice.townId + '/build', post({ key: 'f1' }), alice.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
for (const c of [a1, a2]) await c.waitFor((m) => m.type === 'town' && m.townId === alice.townId);
await sleep(50);
for (const c of [a1, a2]) c.msgs.length = 0;
t.clock.advance(r.body.dueAt - t.clock.now());
t.srv.scheduler.runDue(); // the buildDone event fires
for (const c of [a1, a2]) {
const town = await c.waitFor((m) => m.type === 'town' && m.townId === alice.townId);
assert.deepEqual(town, { type: 'town', townId: alice.townId });
const n = await c.waitFor((m) => m.type === 'notification');
assert.equal(n.kind, 'build_done');
const row = t.srv.db.get('SELECT type FROM notifications WHERE id = ?', n.id);
assert.equal(row.type, 'build_done', 'the id points at a real notification row');
}
assert.deepEqual((await b.settle(100)).filter((m) => m.type !== 'ready'), [], 'another player hears nothing');
const poll = await t.api('/notifications', {}, alice.token);
assert.ok(poll.body.items.some((x) => x.id === a1.msgs.find((m) => m.type === 'notification').id), 'and REST agrees');
} finally { await t.close(); }
});
test('train done: town + notification (train_done)', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice');
t.clock.advance(73 * H);
for (const [k, lv] of [['ops_lab', 3], ['noc', 2]]) t.srv.db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, k, k, lv);
t.srv.db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId);
const c = await login(t.srv, a.token);
const r = await t.api('/towns/' + a.townId + '/train', post({ unit: 'script_crew', count: 5 }), a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
await c.waitFor((m) => m.type === 'town'); // command hint
await c.settle(50); c.msgs.length = 0;
t.clock.set(r.body.dueAt);
t.srv.scheduler.runDue();
await c.waitFor((m) => m.type === 'town' && m.townId === a.townId);
const n = await c.waitFor((m) => m.type === 'notification');
assert.equal(n.kind, 'train_done');
} finally { await t.close(); }
});
// alice raids bobby: bobby gets 'incoming' (only him), a report lands for both
async function raidSetup(t) {
const a = await t.signup('alice'), b = await t.signup('bobby');
const db = t.srv.db;
t.clock.advance(73 * H); // beginner protection over
for (const [k, lv] of [['ops_lab', 3], ['research_lab', 3], ['noc', 2]]) db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, k, k, lv);
db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId);
let r = await t.api('/towns/' + a.townId + '/train', post({ unit: 'script_crew', count: 20 }), a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
t.clock.advance(3 * H);
t.srv.scheduler.runDue();
return { a, b };
}
test('incoming attack: defender gets incoming (+ notification), attacker does not; then report hints for both', async () => {
const t = await createTestServer();
try {
const { a, b } = await raidSetup(t);
const ca = await login(t.srv, a.token), cb = await login(t.srv, b.token);
await sleep(30); ca.msgs.length = 0; cb.msgs.length = 0;
const r = await t.api('/movements', post({ fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } }), a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
const inc = await cb.waitFor((m) => m.type === 'incoming');
assert.deepEqual(inc, { type: 'incoming', townId: b.townId, arriveAt: r.body.arriveAt }, 'town and ETA only, no type, no origin');
const note = await cb.waitFor((m) => m.type === 'notification' && m.kind === 'incoming');
assert.ok(t.srv.db.get('SELECT 1 AS x FROM notifications WHERE id = ? AND user_id = ?', note.id, b.userId));
const mine = await ca.settle(100);
assert.ok(!mine.some((m) => m.type === 'incoming' || m.type === 'notification'), 'the attacker gets no warning: ' + JSON.stringify(mine));
assert.ok(mine.some((m) => m.type === 'town' && m.townId === a.townId), 'but a town hint for the POP that sent the units');
assert.ok(!cb.msgs.some((m) => m.type === 'town'), 'no plain town hint for the target at launch (the warning carries the ETA)');
ca.msgs.length = 0; cb.msgs.length = 0;
t.clock.set(r.body.arriveAt);
t.srv.scheduler.runDue(); // combat resolves
const rep = t.srv.db.get('SELECT id FROM reports ORDER BY id DESC LIMIT 1');
assert.ok(rep);
for (const c of [ca, cb]) {
const m = await c.waitFor((x) => x.type === 'report');
assert.deepEqual(m, { type: 'report', id: rep.id });
await c.waitFor((x) => x.type === 'notification' && x.kind === 'report');
}
await cb.waitFor((m) => m.type === 'town' && m.townId === b.townId); // the attacked POP changed
const view = await t.api('/reports/' + rep.id, {}, b.token);
assert.equal(view.status, 200, 'the id in the hint is fetchable over REST');
} finally { await t.close(); }
});
test('recall: the target owner learns the warning is gone (town hint), the sender gets his POP hint', async () => {
const t = await createTestServer();
try {
const { a, b } = await raidSetup(t);
const ca = await login(t.srv, a.token), cb = await login(t.srv, b.token);
const r = await t.api('/movements', post({ fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } }), a.token);
await cb.waitFor((m) => m.type === 'incoming');
await sleep(50); cb.msgs.length = 0; ca.msgs.length = 0;
const rc = await t.api('/movements/' + r.body.movementId + '/recall', post({}), a.token);
assert.equal(rc.status, 200, JSON.stringify(rc.body));
await cb.waitFor((m) => m.type === 'town' && m.townId === b.townId);
await ca.waitFor((m) => m.type === 'town' && m.townId === a.townId);
} finally { await t.close(); }
});
test('messages and alliance invites: message hint with id, notification with kind alliance_invite', async () => {
const t = await createTestServer();
try {
const lead = await t.signupPeering('leader'), bob = await t.signup('bobby');
const cl = await login(t.srv, lead.token), cb = await login(t.srv, bob.token);
let r = await t.api('/messages', post({ toOperatorId: bob.operatorId, text: 'hello there' }), lead.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
const m = await cb.waitFor((x) => x.type === 'message');
assert.deepEqual(m, { type: 'message', id: r.body.messageId });
assert.equal((await cb.waitFor((x) => x.type === 'notification' && x.kind === 'message')).kind, 'message');
assert.ok(!(await cl.settle(50)).some((x) => x.type === 'message'), 'the sender gets no message hint');
r = await t.api('/alliances', post({ name: 'Pushers', tag: 'PSH' }), lead.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
const inv = await t.api('/alliances/' + r.body.allianceId + '/invite', post({ operatorId: bob.operatorId }), lead.token);
assert.equal(inv.status, 201, JSON.stringify(inv.body));
const n = await cb.waitFor((x) => x.type === 'notification' && x.kind === 'alliance_invite');
assert.ok(t.srv.db.get("SELECT 1 AS x FROM notifications WHERE id = ? AND type = 'alliance_invite'", n.id));
} finally { await t.close(); }
});
test('hints are coalesced: identical hints produced in one tick go out once, distinct ones all arrive in order', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice');
const c = await login(t.srv, a.token);
for (let i = 0; i < 50; i++) t.srv.push.toTown(a.townId, { type: 'town', townId: a.townId }); // e.g. a long catch-up
t.srv.push.toUser(a.userId, { type: 'notification', id: 1, kind: 'x' });
t.srv.push.toUser(a.userId, { type: 'notification', id: 2, kind: 'x' });
t.srv.push.toUser(a.userId, { type: 'notification', id: 1, kind: 'x' });
await c.waitFor((m) => m.type === 'notification' && m.id === 2);
await c.settle(50);
const got = c.msgs.filter((m) => m.type !== 'ready');
assert.deepEqual(got, [{ type: 'town', townId: a.townId }, { type: 'notification', id: 1, kind: 'x' }, { type: 'notification', id: 2, kind: 'x' }]);
t.srv.push.toUser(999999, { type: 'town', townId: 1 }); // unknown user: silently nothing
t.srv.push.toTown(999999, { type: 'town', townId: 999999 }); // unknown POP: silently nothing
} finally { await t.close(); }
});
test('rollback: a notification written by an event or command that then fails is never pushed (hints follow the commit)', async () => {
const t = await createTestServer();
try {
const a = await t.signup('alice');
const c = await login(t.srv, a.token);
const sc = t.srv.scheduler;
sc.register('boom', (ctx, ev) => { ctx.notify(a.userId, ev.worldId, 'ghost', {}); throw new Error('handler failed'); });
sc.register('fine', (ctx, ev) => { ctx.notify(a.userId, ev.worldId, 'real', {}); });
t.srv.commands.handlers.boomCmd = (ctx) => { ctx.scheduler.notify(a.userId, null, 'ghost_cmd', {}); throw new Error('command failed'); };
t.srv.commands.handlers.fineCmd = (ctx) => { ctx.scheduler.notify(a.userId, null, 'real_cmd', {}); return {}; };
const worldId = t.srv.db.get('SELECT id FROM worlds').id;
const now = t.clock.now();
sc.enqueue({ worldId, dueAt: now + 10, type: 'boom', payload: {} });
sc.enqueue({ worldId, dueAt: now + 20, type: 'fine', payload: {} });
t.clock.advance(100);
sc.runDue();
assert.throws(() => t.srv.commands.run('boomCmd', {}), /command failed/);
t.srv.commands.run('fineCmd', {});
await c.waitFor((m) => m.kind === 'real_cmd');
const kinds = (await c.settle(60)).filter((m) => m.type === 'notification').map((m) => m.kind);
assert.deepEqual(kinds, ['real', 'real_cmd']);
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM notifications WHERE type IN ('ghost', 'ghost_cmd')").n, 0, 'the rows rolled back too');
assert.equal(sc.outbox.length, 0);
} finally { await t.close(); }
});

56
test/push-helpers.js Normal file
View file

@ -0,0 +1,56 @@
'use strict';
/* Shared helpers of the push tests (no tests in here): a recording WebSocket client around the real `ws` package. */
const WebSocket = require('ws');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Opens ws://127.0.0.1:port/ws. Resolves { ws, msgs, closed, open, waitFor(pred, ms), expectNone(ms), send(obj), auth(token) }.
// `closed` resolves { code, reason } when the socket closes. Rejects with { status } when the upgrade is refused.
function connect(srv, o) {
o = o || {};
return new Promise((resolve, reject) => {
const ws = new WebSocket('ws://127.0.0.1:' + srv.port + (o.path || '/ws'), Object.assign({ headers: o.headers || {} }, o.wsOptions || {}));
const msgs = [];
const waiters = [];
let closedResolve;
const closed = new Promise((r) => { closedResolve = r; });
const c = {
ws, msgs, closed,
send: (obj) => ws.send(typeof obj === 'string' ? obj : JSON.stringify(obj)),
auth: (token) => c.send({ type: 'auth', token }),
// first message (already received or still to come) matching pred, within ms
waitFor(pred, ms) {
const hit = msgs.find(pred);
if (hit) return Promise.resolve(hit);
return new Promise((res, rej) => {
const t = setTimeout(() => { const i = waiters.indexOf(w); if (i >= 0) waiters.splice(i, 1); rej(new Error('no matching message in ' + (ms || 2000) + ' ms; got ' + JSON.stringify(msgs))); }, ms || 2000);
const w = { pred, res: (m) => { clearTimeout(t); res(m); } };
waiters.push(w);
});
},
// wait ms, then return everything received so far
async settle(ms) { await sleep(ms === undefined ? 80 : ms); return msgs.slice(); },
async connectAndAuth(token) { c.auth(token); return c.waitFor((m) => m.type === 'ready'); },
};
ws.on('message', (d) => {
let m; try { m = JSON.parse(d.toString()); } catch (e) { m = { raw: d.toString() }; }
msgs.push(m);
for (let i = waiters.length - 1; i >= 0; i--) if (waiters[i].pred(m)) { const w = waiters.splice(i, 1)[0]; w.res(m); }
});
ws.on('close', (code, reason) => closedResolve({ code, reason: reason.toString() }));
ws.on('unexpected-response', (req, res) => { res.resume(); reject({ status: res.statusCode }); });
ws.on('error', (err) => { if (!/Unexpected server response/.test(err.message)) { /* closed or reset: `closed` reports it */ } });
ws.on('open', () => resolve(c));
});
}
// Connect and authenticate in one go.
async function login(srv, token, o) {
const c = await connect(srv, o);
await c.connectAndAuth(token);
return c;
}
const within = (p, ms, label) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('timeout after ' + ms + ' ms: ' + (label || ''))), ms))]);
module.exports = { connect, login, sleep, within };

193
test/push-ws.test.js Normal file
View file

@ -0,0 +1,193 @@
'use strict';
/* WebSocket transport (server/push.js): auth, limits, keepalive, revocation, shutdown. Real `ws` client against
* createServer on port 0 with the fake clock. Game hints are in push-game.test.js. */
const test = require('node:test');
const assert = require('node:assert');
const WebSocket = require('ws');
const { createTestServer } = require('./helpers');
const { connect, login, sleep, within } = require('./push-helpers');
test('auth: ready carries the server clock, ping gets pong, REST token works as ws token', async () => {
const t = await createTestServer();
try {
const u = await t.signup('alice');
t.clock.advance(12345);
const c = await connect(t.srv);
c.auth(u.token);
const ready = await c.waitFor((m) => m.type === 'ready');
assert.deepEqual(Object.keys(ready).sort(), ['serverTime', 'type']);
assert.equal(ready.serverTime, t.clock.now());
c.send({ type: 'ping' });
const pong = await c.waitFor((m) => m.type === 'pong');
assert.equal(pong.serverTime, t.clock.now());
assert.equal(t.srv.push.stats().users, 1);
c.ws.close();
await c.closed;
await sleep(20);
assert.deepEqual(t.srv.push.stats(), { connections: 0, users: 0, ips: 0 }, 'registry is empty after close');
} finally { await t.close(); }
});
test('auth: bad token, first message not auth, junk first message: close 4401, never a ready', async () => {
const t = await createTestServer();
try {
const u = await t.signup('alice');
for (const first of [{ type: 'auth', token: 'x'.repeat(43) }, { type: 'auth' }, { type: 'auth', token: 12345 }, { type: 'ping' }, 'not json', '[1,2]', { type: 'auth', token: u.token + 'x' }]) {
const c = await connect(t.srv);
c.send(first);
const r = await within(c.closed, 2000, JSON.stringify(first));
assert.equal(r.code, 4401, JSON.stringify(first));
assert.ok(!c.msgs.some((m) => m.type === 'ready'));
}
// a token in the URL is ignored: auth is the first MESSAGE only
const c = await connect(t.srv, { path: '/ws?token=' + u.token });
c.send({ type: 'ping' });
assert.equal((await c.closed).code, 4401);
await sleep(30);
assert.equal(t.srv.push.stats().connections, 0);
} finally { await t.close(); }
});
test('auth timeout: no message within wsAuthTimeoutMs closes 4408', async () => {
const t = await createTestServer({ server: { wsAuthTimeoutMs: 150 } });
try {
const c = await connect(t.srv);
const r = await within(c.closed, 2000);
assert.equal(r.code, 4408);
} finally { await t.close(); }
});
test('upgrade checks: origin, path, per-IP cap (released on close)', async () => {
const t = await createTestServer({ server: { maxConnPerIp: 2, allowedOrigins: ['https://game.example.com'] } });
try {
const u = await t.signup('alice');
await assert.rejects(connect(t.srv, { headers: { Origin: 'https://evil.example' } }), { status: 403 });
await assert.rejects(connect(t.srv, { headers: { Origin: 'null' } }), { status: 403 });
await assert.rejects(connect(t.srv, { path: '/socket' }), { status: 404 });
const ok1 = await login(t.srv, u.token, { headers: { Origin: 'https://game.example.com' } }); // allowlisted
const ok2 = await login(t.srv, u.token, { headers: { Origin: 'http://127.0.0.1:' + t.srv.port } }); // same host as Host
await assert.rejects(connect(t.srv), { status: 429 }, 'third socket from one address');
ok1.ws.close(); await ok1.closed; await sleep(20);
const ok3 = await login(t.srv, u.token); // no Origin: non-browser client
assert.equal(t.srv.push.stats().connections, 2);
ok2.ws.close(); ok3.ws.close();
await Promise.all([ok2.closed, ok3.closed]);
// refused requests never leaked a count
await sleep(20);
assert.equal(t.srv.push.stats().ips, 0);
} finally { await t.close(); }
});
test('rate limit per socket closes 4429; the bucket refills', async () => {
const t = await createTestServer({ server: { wsRate: 2, wsBurst: 4 } });
try {
const u = await t.signup('alice');
const calm = await login(t.srv, u.token);
for (let i = 0; i < 3; i++) { calm.send({ type: 'ping' }); await sleep(600); } // 1.7 msg/s: fine
assert.equal(calm.msgs.filter((m) => m.type === 'pong').length, 3);
calm.ws.close();
const c = await login(t.srv, u.token);
for (let i = 0; i < 12; i++) c.send({ type: 'ping' }); // burst of 12 > 4 + refill
assert.equal((await within(c.closed, 2000)).code, 4429);
} finally { await t.close(); }
});
test('bad-message budget closes 4400; oversize payload closes 1009', async () => {
const t = await createTestServer({ server: { wsBadBudget: 3 } });
try {
const u = await t.signup('alice');
const c = await login(t.srv, u.token);
c.send({ type: 'subscribe' });
c.send('not json');
c.send({ type: 'auth', token: u.token }); // already authenticated: counts as bad
assert.equal((await within(c.closed, 2000)).code, 4400);
const big = await login(t.srv, u.token);
big.send(JSON.stringify({ type: 'ping', pad: 'x'.repeat(2000) }));
assert.equal((await within(big.closed, 2000)).code, 1009);
const bin = await login(t.srv, u.token);
bin.ws.send(Buffer.from([1, 2, 3])); // binary frames are bad messages too
bin.ws.send(Buffer.from([1, 2, 3]));
bin.ws.send(Buffer.from([1, 2, 3]));
assert.equal((await within(bin.closed, 2000)).code, 4400);
} finally { await t.close(); }
});
test('keepalive: a socket that never answers pings is terminated', async () => {
const t = await createTestServer({ server: { wsPingMs: 60 } });
try {
const u = await t.signup('alice');
const live = await login(t.srv, u.token); // answers pings (ws default)
const dead = await login(t.srv, u.token, { wsOptions: { autoPong: false } }); // swallows them
const r = await within(dead.closed, 2000, 'dead socket should be dropped');
assert.equal(r.code, 1006);
await sleep(200);
assert.equal(live.ws.readyState, WebSocket.OPEN, 'a healthy socket stays');
assert.equal(t.srv.push.stats().connections, 1);
live.ws.close();
} finally { await t.close(); }
});
test('revoked token and banned user are disconnected at the next ping tick; other devices stay', async () => {
const t = await createTestServer({ server: { wsPingMs: 60 } });
try {
const u = await t.signup('alice');
const login2 = await t.api('/auth/login', { method: 'POST', body: { username: 'alice', password: 'correct horse battery' } });
const phone = login2.body.token;
const a = await login(t.srv, u.token), b = await login(t.srv, phone);
let r = await t.api('/auth/logout', { method: 'POST' }, u.token); // revoke device 1
assert.equal(r.status, 200);
const res = await within(a.closed, 2000, 'revoked socket');
assert.equal(res.code, 4401); assert.equal(res.reason, 'token_revoked');
await sleep(150);
assert.equal(b.ws.readyState, WebSocket.OPEN, 'the phone token is still valid');
// and a revoked token cannot open a new socket
const c = await connect(t.srv);
c.auth(u.token);
assert.equal((await within(c.closed, 2000)).code, 4401);
// ban
t.srv.db.run('UPDATE users SET banned = 1 WHERE id = ?', u.userId);
assert.equal((await within(b.closed, 2000, 'banned user')).code, 4401);
} finally { await t.close(); }
});
test('shutdown: srv.close() closes every socket with 1001 and completes promptly', async () => {
const t = await createTestServer();
const u = await t.signup('alice');
const socks = [await login(t.srv, u.token), await login(t.srv, u.token), await connect(t.srv)]; // two authed, one silent
const started = Date.now();
await within(t.close(), 4000, 'srv.close()');
assert.ok(Date.now() - started < 3000, 'close took ' + (Date.now() - started) + ' ms');
for (const s of socks) assert.equal((await within(s.closed, 1000)).code, 1001);
});
test('REST works fully with no socket, with an idle socket, and a failing command pushes nothing', async () => {
const t = await createTestServer();
try {
const u = await t.signup('alice');
// no socket at all: build, finish, notification row, all over REST
let r = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
t.clock.advance(r.body.dueAt - t.clock.now() + 1000);
r = await t.api('/notifications', {}, u.token);
assert.equal(r.status, 200);
assert.ok(r.body.items.some((n) => n.type === 'build_done'));
// a connected socket sees no hint for a refused command (rolled back, nothing happened)
const c = await login(t.srv, u.token);
r = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token);
assert.equal(r.status, 201); // sanity: this one is valid
await c.waitFor((m) => m.type === 'town'); // the valid build's own hint
await c.settle(50); c.msgs.length = 0;
const bad = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token); // queue/resources: refused
assert.ok(bad.status >= 400, 'second build of the same field is refused: ' + bad.status);
assert.deepEqual(await c.settle(100), [], 'no hint for a refused command');
// an unauthenticated socket gets no hints either
const idle = await connect(t.srv);
t.clock.advance(24 * 3600e3);
t.srv.scheduler.runDue();
assert.deepEqual(await idle.settle(100), []);
assert.equal(c.msgs.filter((m) => m.type === 'town').length >= 1, true, 'the authenticated one got its hint');
idle.ws.close(); c.ws.close();
} finally { await t.close(); }
});

75
test/trade-api.test.js Normal file
View file

@ -0,0 +1,75 @@
'use strict';
/* Trade over HTTP: routes, validation, error codes, pagination, and the declared response schemas (contract: true). */
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const D = require('../public/js/data.js');
test('trade API: post, list, take, mine, detail, cancel, errors', async () => {
const t = await createTestServer({ contract: true });
try {
const a = await t.signup('alice'), b = await t.signup('bob'), c = await t.signup('cara');
for (const u of [a, b]) t.setBuilding(u.townId, 'internet_exchange', 3);
// cara has no exchange at all
const body = (o) => Object.assign({ townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 40 }, o || {});
const bad = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 500, wantAmount: 200 }) }, a.token);
assert.equal(bad.status, 409); assert.equal(bad.body.error.code, 'trade_ratio');
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ wantRes: 'fiber' }) }, a.token)).status, 422);
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ townId: b.townId }) }, a.token)).status, 404);
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body() })).status, 401);
const made = await t.api('/trade/offers', { method: 'POST', body: body() }, a.token);
assert.equal(made.status, 201);
const id = made.body.offer.id;
assert.equal(made.body.offer.give.amount, 400);
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 100, wantAmount: 100, giveRes: 'capital' }) }, a.token)).status, 201);
const listB = await t.api('/trade/offers', {}, b.token);
assert.equal(listB.status, 200);
assert.equal(listB.body.items.length, 2);
assert.equal(listB.body.items[0].id > listB.body.items[1].id, true, 'newest first');
const p1 = await t.api('/trade/offers?limit=1', {}, b.token);
assert.equal(p1.body.items.length, 1);
const p2 = await t.api('/trade/offers?limit=1&after=' + p1.body.next, {}, b.token);
assert.equal(p2.body.items[0].id, id);
assert.equal(p2.body.next, null);
assert.equal((await t.api('/trade/offers?give=capital', {}, b.token)).body.items.length, 1, 'filter by offered resource');
assert.equal((await t.api('/trade/offers?want=capital', {}, b.token)).body.items.length, 0);
assert.equal((await t.api('/trade/offers', {}, a.token)).body.items.length, 0, 'not your own');
assert.equal((await t.api('/trade/offers', {}, c.token)).body.items.length, 0, 'no exchange: you see nothing');
assert.equal((await t.api('/trade/offers?give=gold', {}, b.token)).status, 422);
const one = await t.api('/trade/offers/' + id, {}, c.token);
assert.equal(one.body.offer.status, 'open', 'open offers are public inside the world');
const acc = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(acc.status, 201);
assert.equal(acc.body.status, 'accepted');
assert.equal((await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token)).body.error.code, 'offer_closed');
assert.equal((await t.api('/trade/offers/' + id, {}, c.token)).status, 404, 'closed offers are for the two parties');
t.clock.advance(acc.body.arriveAt - t.clock.now());
t.srv.scheduler.runDue();
const mineA = await t.api('/trade/offers/mine', {}, a.token), mineB = await t.api('/trade/offers/mine?status=completed', {}, b.token);
assert.equal(mineA.body.items.length, 2);
assert.equal(mineB.body.items[0].status, 'completed');
assert.equal(mineB.body.items[0].role, 'acceptor');
const notes = await t.api('/notifications', {}, a.token);
assert.ok(notes.body.items.some((n) => n.type === 'trade_completed'));
const other = await t.api('/trade/offers', { method: 'GET' }, b.token);
const open = other.body.items[0];
assert.equal((await t.api('/trade/offers/' + open.id, { method: 'DELETE' }, b.token)).status, 404);
const del = await t.api('/trade/offers/' + open.id, { method: 'DELETE' }, a.token);
assert.equal(del.status, 200);
assert.deepEqual(del.body.returned, { resource: 'capital', amount: 100 });
// the Idempotency-Key makes a retried POST safe: one offer, not two
const k = { 'idempotency-key': 'offer-retry-0001' };
const r1 = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 50, wantAmount: 50 }), headers: k }, a.token);
const r2 = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 50, wantAmount: 50 }), headers: k }, a.token);
assert.equal(r1.body.offer.id, r2.body.offer.id);
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE give_amount = 50").n, 1);
void D;
} finally { await t.close(); }
});

226
test/trade-flow.test.js Normal file
View file

@ -0,0 +1,226 @@
'use strict';
/* Internet exchange trade: offers, escrow, accept (two transports), cancel, expire, rules, conservation. Fake clock, in-memory db. */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D, H } = T;
// Two traders next to each other with no production at all, so every resource that moves can be counted exactly.
function traders(o) {
o = o || {};
const h = T.setup();
const a = T.addOperator(h, 'alice', { x: 5, y: 0, infra: o.aInfra });
const b = T.addOperator(h, 'bob', { x: 9, y: 0, infra: o.bInfra });
for (const t of [a, b]) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", t.townId);
return { h, a, b };
}
const stock = (h, townId) => { const t = T.town(h, townId); return { fiber: t.fiber, hardware: t.hardware, capital: t.capital }; };
// every unit of every resource in the world: in POPs, in open offers (escrow), on the road
function total(h) {
let sum = 0;
for (const t of h.db.all('SELECT fiber, hardware, capital FROM towns')) sum += t.fiber + t.hardware + t.capital;
for (const o of h.db.all("SELECT give_amount FROM trade_offers WHERE status = 'open'")) sum += o.give_amount;
for (const m of h.db.all("SELECT cargo FROM movements WHERE status = 'out'")) for (const v of Object.values(JSON.parse(m.cargo))) sum += v;
return sum;
}
const post = (h, who, townId, o) => h.run('tradeOffer', Object.assign({ userId: who.userId, townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }, o || {})).offer;
const { createTradeQueries } = require('../server/tradeQueries');
const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); };
test('trade: post, escrow, accept spawns two transports, both arrive, offer completes; nothing is created or lost', () => {
const { h, a, b } = traders();
const before = total(h);
const aStart = stock(h, a.townId), bStart = stock(h, b.townId);
const offer = post(h, a, a.townId);
assert.equal(offer.status, 'open');
assert.equal(stock(h, a.townId).fiber, aStart.fiber - 400, 'the offered amount left the POP (escrow)');
assert.equal(total(h), before, 'escrow is counted: conserved');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'tradeExpire' AND status = 'pending'").n, 1);
// bob sees it and can take it
const tq = createTradeQueries(h);
const list = tq.offers(b.userId, {});
assert.equal(list.items.length, 1);
assert.equal(list.items[0].id, offer.id);
assert.equal(list.items[0].acceptableFrom[0].townId, b.townId);
assert.equal(tq.offers(a.userId, {}).items.length, 0, 'your own offers are not in the market list');
const t0 = h.clock.now();
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId });
assert.equal(acc.status, 'accepted');
const dist = R.distance(a.x, a.y, b.x, b.y);
assert.equal(acc.arriveAt, t0 + R.transportMs(dist, 1), 'both legs use the transport speed');
assert.equal(stock(h, b.townId).hardware, bStart.hardware - 300, "the acceptor's payment left at once");
assert.equal(total(h), before, 'in flight: still conserved');
const mvs = h.db.all("SELECT * FROM movements WHERE type = 'transport' ORDER BY id");
assert.equal(mvs.length, 2);
const goods = mvs.find((m) => m.id === acc.goodsMovementId), pay = mvs.find((m) => m.id === acc.paymentMovementId);
assert.equal(goods.from_town_id, a.townId); assert.equal(goods.to_town_id, b.townId); assert.deepEqual(JSON.parse(goods.cargo), { fiber: 400 });
assert.equal(pay.from_town_id, b.townId); assert.equal(pay.to_town_id, a.townId); assert.deepEqual(JSON.parse(pay.cargo), { hardware: 300 });
assert.equal(T.notes(h, a.userId, 'trade_accepted').length, 1);
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'accepted');
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled', 'an accepted offer cannot expire');
h.advanceTo(acc.arriveAt);
assert.equal(h.db.get('SELECT status, legs_done FROM trade_offers WHERE id = ?', offer.id).status, 'completed');
assert.equal(stock(h, a.townId).hardware, aStart.hardware + 300);
assert.equal(stock(h, b.townId).fiber, bStart.fiber + 400);
assert.equal(stock(h, a.townId).fiber, aStart.fiber - 400);
assert.equal(T.notes(h, a.userId, 'trade_completed').length, 1);
assert.equal(T.notes(h, b.userId, 'trade_completed').length, 1);
assert.equal(total(h), before, 'delivered: conserved');
// the carriers drive back; the links are free again afterwards
const back = h.db.all("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
assert.equal(back.length, 2);
h.advance(10 * H);
assert.equal(require('../server/military/movements').activeLinks(h.db, a.townId), 0);
assert.equal(total(h), before);
assert.equal(h.db.all("SELECT 1 FROM events WHERE status = 'failed'").length, 0);
});
test('trade: terms - 1:2 ratio band, capacity, distinct resources, links, resources, ownership', () => {
const { h, a, b } = traders({ aInfra: { internet_exchange: 1 } });
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 249 })).code, 'trade_ratio');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 100, wantAmount: 201 })).code, 'trade_ratio');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 501 })).code, 'capacity_exceeded');
assert.equal(err(() => post(h, a, a.townId, { wantRes: 'fiber' })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { giveRes: 'power' })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 0 })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 1.5 })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { maxDistance: 0 })).code, 'validation_failed');
assert.equal(err(() => post(h, a, a.townId, { maxDistance: D.TRADE.maxDistance + 1 })).code, 'validation_failed');
assert.equal(err(() => post(h, b, a.townId)).code, 'not_found', 'not your POP');
assert.equal(post(h, a, a.townId, { giveAmount: 500, wantAmount: 250 }).status, 'open', 'exactly 2:1 is allowed');
// level 1 exchange = one link, held by the open offer: no second offer and no direct transport meanwhile
assert.equal(err(() => post(h, a, a.townId)).code, 'no_transport_link');
assert.equal(err(() => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: 10 } })).code, 'no_transport_link');
// a POP without an exchange cannot post
h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'internet_exchange'", b.townId);
assert.equal(err(() => post(h, b, b.townId)).code, 'no_transport_link');
// not enough of the offered resource
const c = T.addOperator(h, 'cat', { x: 14, y: 0, res: 100 });
assert.equal(err(() => post(h, c, c.townId)).code, 'not_enough_resources');
});
test('trade: accept rules - own offer, closed, range, exchange, cannot afford (atomic), links', () => {
const { h, a, b } = traders();
const c = T.addOperator(h, 'cat', { x: 40, y: 0 }); // 35 tiles from alice
const d = T.addOperator(h, 'dan', { x: 12, y: 0, infra: { internet_exchange: 0 } });
h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'internet_exchange'", d.townId);
const offer = post(h, a, a.townId, { maxDistance: 12 });
assert.equal(err(() => h.run('tradeAccept', { userId: a.userId, offerId: offer.id, townId: a.townId })).code, 'own_offer');
assert.equal(err(() => h.run('tradeAccept', { userId: c.userId, offerId: offer.id, townId: c.townId })).code, 'trade_out_of_range', 'beyond the offer\'s max distance');
assert.equal(err(() => h.run('tradeAccept', { userId: d.userId, offerId: offer.id, townId: d.townId })).code, 'no_transport_link', 'no Internet exchange');
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: 999, townId: b.townId })).code, 'not_found');
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: a.townId })).code, 'not_found', 'not your POP');
// reach: a level-1 exchange sees 10 tiles
const far = T.addOperator(h, 'far', { x: 20, y: 0, infra: { internet_exchange: 1 } }); // 15 tiles from alice, within the offer's 30 below
const wide = post(h, a, a.townId, { maxDistance: 30, giveAmount: 100, wantAmount: 100 });
assert.equal(err(() => h.run('tradeAccept', { userId: far.userId, offerId: wide.id, townId: far.townId })).code, 'trade_out_of_range');
const seen = createTradeQueries(h).offers(far.userId, {});
assert.equal(seen.items.length, 0, 'out of reach: not even listed');
assert.equal(seen.exchangeLevels[0].reach, 10);
// bob cannot pay: nothing changes (all or nothing)
h.db.run('UPDATE towns SET hardware = 100 WHERE id = ?', b.townId);
const snap = JSON.stringify([stock(h, a.townId), stock(h, b.townId), h.db.all('SELECT * FROM movements'), h.db.all('SELECT status FROM trade_offers ORDER BY id')]);
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'not_enough_resources');
assert.equal(JSON.stringify([stock(h, a.townId), stock(h, b.townId), h.db.all('SELECT * FROM movements'), h.db.all('SELECT status FROM trade_offers ORDER BY id')]), snap, 'a failed accept leaves no trace');
// no free link for bob (level 3, three running transports)
h.db.run('UPDATE towns SET hardware = 1000 WHERE id = ?', b.townId);
for (let i = 0; i < 3; i++) h.run('sendTransport', { userId: b.userId, fromTownId: b.townId, toTownId: c.townId, cargo: { capital: 10 } });
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'no_transport_link');
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open');
});
test('trade: cancel returns the escrow, closed offers cannot be taken, strangers cannot cancel', () => {
const { h, a, b } = traders();
const start = stock(h, a.townId), before = total(h);
const offer = post(h, a, a.townId);
assert.equal(err(() => h.run('tradeCancel', { userId: b.userId, offerId: offer.id })).code, 'not_found');
const r = h.run('tradeCancel', { userId: a.userId, offerId: offer.id });
assert.deepEqual(r.returned, { resource: 'fiber', amount: 400 });
assert.deepEqual(stock(h, a.townId), start);
assert.equal(total(h), before);
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled');
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'offer_closed');
assert.equal(err(() => h.run('tradeCancel', { userId: a.userId, offerId: offer.id })).code, 'offer_closed');
assert.equal(require('../server/military/movements').activeLinks(h.db, a.townId), 0, 'the reserved link is free again');
});
test('trade: an offer expires after its ttl (divided by world speed) and returns the escrow exactly once', () => {
for (const speed of [1, 4]) {
const h = T.setup({ speed });
const a = T.addOperator(h, 'alice', { x: 5, y: 0 });
h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", a.townId);
const start = stock(h, a.townId);
const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'capital', giveAmount: 250, wantRes: 'fiber', wantAmount: 400, maxDistance: 20 }).offer;
assert.equal(offer.expiresAt - h.clock.now(), D.TRADE.ttlHours * H / speed);
h.advanceTo(offer.expiresAt - 1);
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open');
h.advanceTo(offer.expiresAt);
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired');
assert.deepEqual(stock(h, a.townId), start);
assert.equal(T.notes(h, a.userId, 'trade_expired').length, 1);
// running the handler again (idempotence) does not pay twice
require('../server/events/tradeExpire')(Object.assign(h.ctx(), { now: offer.expiresAt }), { id: 0, worldId: h.worldId, dueAt: offer.expiresAt, payload: { offerId: offer.id } });
assert.deepEqual(stock(h, a.townId), start);
}
});
test('trade: a delivery above the receiver\'s storage cap loses exactly the overflow (and says so); the rest is conserved', () => {
const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000
h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId);
const before = total(h);
const offer = post(h, a, a.townId);
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId });
h.advanceTo(acc.arriveAt);
assert.equal(stock(h, b.townId).fiber, 1000);
const arrived = T.notes(h, b.userId, 'transport_arrived')[0];
assert.deepEqual(arrived.cargoLost, { fiber: 300 });
assert.equal(total(h) + 300, before, 'every unit is somewhere, except the 300 that did not fit and were reported lost');
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'completed');
});
test('trade: a POP that changes hands voids its open offers; the escrow stays in the POP', () => {
const { h, a, b } = traders();
const offer = post(h, a, a.townId);
const before = total(h);
const combat = require('../server/military/combat');
const town = require('../server/state').loadTown(h.db, a.townId);
h.db.tx(() => combat.transferTown(h.ctx(), town, { id: b.opId, name: 'bob' }, { id: a.opId, name: 'alice' }, h.clock.now()));
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'void');
assert.equal(T.town(h, a.townId).owner_id, b.opId);
assert.equal(T.town(h, a.townId).fiber, 4000, "the escrow is back in the POP, now bob's");
assert.equal(total(h), before, 'nothing created or lost');
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'offer_closed');
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled');
assert.equal(T.notes(h, a.userId, 'trade_void').length, 1);
});
test('trade list: pages through offers that are out of reach (chunked read), cursor and filters stay right', () => {
const saved = D.TRADE.scanChunk;
D.TRADE.scanChunk = 2;
try {
const h = T.setup();
const p = T.addOperator(h, 'poster', { x: 5, y: 0, infra: { internet_exchange: 10 } });
const v = T.addOperator(h, 'viewer', { x: 9, y: 0 }); // 4 tiles away, exchange 3 (reach 30)
for (const q of [p, v]) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", q.townId);
const ids = [];
for (const [md, amt] of [[2, 10], [10, 20], [2, 30], [2, 40], [10, 50], [3, 60], [10, 70]]) ids.push(post(h, p, p.townId, { maxDistance: md, giveAmount: amt, wantAmount: amt }).id);
const tq = createTradeQueries(h);
const visible = [ids[1], ids[4], ids[6]]; // maxDistance >= 4
const p1 = tq.offers(v.userId, { limit: 2 });
assert.deepEqual(p1.items.map((o) => o.id), [visible[2], visible[1]]);
assert.equal(p1.next, visible[1]);
const p2 = tq.offers(v.userId, { limit: 2, after: p1.next });
assert.deepEqual(p2.items.map((o) => o.id), [visible[0]]);
assert.equal(p2.next, null);
assert.equal(tq.offers(v.userId, { limit: 10 }).items.length, 3);
assert.deepEqual(tq.offers(v.userId, { limit: 10, give: 'capital' }).items, []);
} finally { D.TRADE.scanChunk = saved; }
});