Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy

Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

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 18:32:36 +02:00
parent b56b13880e
commit 249818a7aa
111 changed files with 17472 additions and 13 deletions

284
test/admin-cli.test.js Normal file
View file

@ -0,0 +1,284 @@
'use strict';
// tools/admin.js against temp databases. The ban test runs the real HTTP server and the CLI on the same DB file
// at the same time, which is exactly how the CLI is used in production.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const admin = require('../tools/admin.js');
const { createServer } = require('../server');
const { openDb, migrate } = require('../server/db');
function tmp() { return fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-admin-test-')); }
// run the CLI in-process; returns { code, out, err, json }
function cli(dbPath, args, now) {
const out = [], err = [];
const code = admin.main(args.concat(['--db', dbPath]), { out: (s) => out.push(s), err: (s) => err.push(s), env: {}, now: now ? () => now : undefined });
const text = out.join('\n');
let json = null;
if (args.includes('--json')) { try { json = JSON.parse(text); } catch (e) { /* not json */ } }
return { code, out: text, err: err.join('\n'), json };
}
function freshDb(dir) {
const file = path.join(dir, 'game.db');
const db = openDb(file); migrate(db); db.close();
return file;
}
async function api(srv, method, url, body, token) {
const res = await fetch('http://127.0.0.1:' + srv.port + '/api/v1' + url, {
method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}),
body: body ? JSON.stringify(body) : undefined,
});
return { status: res.status, body: await res.json() };
}
test('parseArgs, parseTime, parseDuration', () => {
const a = admin.parseArgs(['backup', '/x', '--keep', '5', '--yes', '--type=buildDone']);
assert.deepEqual(a._, ['backup', '/x']);
assert.deepEqual(a.flags, { keep: '5', yes: true, type: 'buildDone' });
assert.throws(() => admin.parseArgs(['events', '--limit']), /needs a value/);
const now = Date.UTC(2026, 0, 1);
assert.equal(admin.parseTime('now', now), now);
assert.equal(admin.parseTime('+2h', now), now + 7200e3);
assert.equal(admin.parseTime('-30m', now), now - 1800e3);
assert.equal(admin.parseTime('2026-01-02T00:00:00Z', now), now + 86400e3);
assert.equal(admin.parseDuration('14d'), 14 * 86400e3);
assert.throws(() => admin.parseTime('soon', now), /bad time/);
});
test('help and unknown command', () => {
const dir = tmp();
const h = cli(path.join(dir, 'none.db'), ['help']);
assert.equal(h.code, 0);
assert.match(h.out, /reset-world/);
const u = cli(path.join(dir, 'none.db'), ['frobnicate']);
assert.equal(u.code, 2);
assert.match(u.err, /unknown command/);
});
test('missing database is an error, not a silently created empty file', () => {
const dir = tmp();
const file = path.join(dir, 'nope.db');
const r = cli(file, ['worlds']);
assert.equal(r.code, 1);
assert.match(r.err, /database not found/);
assert.equal(fs.existsSync(file), false);
});
test('create-world, worlds, end-world needs --yes', () => {
const file = freshDb(tmp());
const c = cli(file, ['create-world', '--name', 'Lab', '--speed', '3', '--radius', '12', '--seed', '42', '--json']);
assert.equal(c.code, 0);
assert.equal(c.json.world.name, 'Lab');
assert.equal(c.json.world.seed, 42);
assert.equal(c.json.world.map_radius, 12);
assert.equal(cli(file, ['create-world', '--speed', 'fast']).code, 2);
const w = cli(file, ['worlds', '--json']);
assert.equal(w.json.worlds.length, 1);
const id = w.json.worlds[0].id;
assert.equal(cli(file, ['end-world', String(id)]).code, 2);
assert.equal(cli(file, ['worlds', '--json']).json.worlds[0].status, 'running');
assert.equal(cli(file, ['end-world', String(id), '--yes']).code, 0);
assert.equal(cli(file, ['worlds', '--json']).json.worlds[0].status, 'ended');
assert.equal(cli(file, ['end-world', '99', '--yes']).code, 3);
});
test('backup: readable verified snapshot, never overwrites, retention prunes only its own files', () => {
const dir = tmp();
const file = freshDb(dir);
cli(file, ['create-world', '--name', 'Backed up']);
const dest = path.join(dir, 'bk');
fs.mkdirSync(dest);
fs.writeFileSync(path.join(dest, 'notes.txt'), 'keep me');
const t0 = Date.UTC(2026, 5, 1, 4, 0, 0);
const b1 = cli(file, ['backup', dest, '--json'], t0);
assert.equal(b1.code, 0, b1.err);
assert.match(path.basename(b1.json.file), /^upstream-20260601T040000Z\.db$/);
const v = admin.verifySnapshot(b1.json.file);
assert.equal(v.integrity, 'ok');
assert.equal(v.worlds, 1);
assert.equal(cli(file, ['verify-backup', b1.json.file]).code, 0);
// the snapshot opens as an ordinary database and holds the data
const snap = openDb(b1.json.file);
assert.equal(snap.get('SELECT name FROM worlds').name, 'Backed up');
snap.close();
// same second: a second file, the first one untouched
const before = fs.readFileSync(b1.json.file);
const b2 = cli(file, ['backup', dest, '--json'], t0);
assert.equal(b2.code, 0);
assert.notEqual(b2.json.file, b1.json.file);
assert.deepEqual(fs.readFileSync(b1.json.file), before);
// retention by count: three more days of snapshots, keep 2
for (let d = 1; d <= 3; d++) assert.equal(cli(file, ['backup', dest], t0 + d * 86400e3).code, 0);
const r = cli(file, ['backup', dest, '--keep', '2', '--json'], t0 + 4 * 86400e3);
assert.equal(r.code, 0);
const left = admin.listBackups(dest).map((b) => b.name);
assert.equal(left.length, 2);
assert.ok(left[0].includes('20260605'));
assert.ok(fs.existsSync(path.join(dest, 'notes.txt')), 'foreign files are never touched');
assert.equal(fs.readdirSync(dest).filter((n) => n.startsWith('.partial')).length, 0);
// a corrupt target is not a backup
fs.writeFileSync(path.join(dir, 'junk.db'), 'not a database');
assert.notEqual(cli(file, ['verify-backup', path.join(dir, 'junk.db')]).code, 0);
});
test('pruneSet: count, age, both, never the newest', () => {
const now = Date.UTC(2026, 5, 10);
const mk = (daysAgo) => ({ name: 'd' + daysAgo, at: now - daysAgo * 86400e3, seq: 0 });
const list = [mk(0), mk(1), mk(2), mk(5), mk(9)];
assert.deepEqual(admin.pruneSet(list, now, {}), []);
assert.deepEqual(admin.pruneSet(list, now, { keep: 2 }).map((b) => b.name), ['d2', 'd5', 'd9']);
assert.deepEqual(admin.pruneSet(list, now, { keepDays: 3 }).map((b) => b.name), ['d5', 'd9']);
assert.deepEqual(admin.pruneSet(list, now, { keep: 1, keepDays: 3 }).map((b) => b.name), ['d5', 'd9']);
assert.deepEqual(admin.pruneSet(list, now, { keep: 1, keepDays: 0.1 }).map((b) => b.name), ['d1', 'd2', 'd5', 'd9']);
});
test('ban stops login and revokes tokens on a RUNNING server; unban restores; output never leaks secrets', async () => {
const dir = tmp();
const file = path.join(dir, 'game.db');
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, world: { mapRadius: 20 } });
try {
const s = await api(srv, 'POST', '/auth/signup', { username: 'mallory', password: 'correct horse battery' });
assert.equal(s.status, 201);
const token = s.body.token;
assert.equal((await api(srv, 'GET', '/me', null, token)).status, 200);
const u = cli(file, ['users']);
assert.match(u.out, /mallory/);
assert.ok(!u.out.includes(token));
assert.ok(!/scrypt/.test(u.out + cli(file, ['inspect-operator', 'mallory']).out), 'no password hashes in output');
const b = cli(file, ['ban', 'mallory', '--json']);
assert.equal(b.code, 0, b.err);
assert.equal(b.json.tokensRevoked, 1);
assert.equal((await api(srv, 'GET', '/me', null, token)).status, 401, 'old token is dead');
const login = await api(srv, 'POST', '/auth/login', { username: 'mallory', password: 'correct horse battery' });
assert.equal(login.status, 403);
assert.equal(login.body.error.code, 'forbidden');
assert.match(cli(file, ['users', '--banned']).out, /BANNED/);
assert.equal(cli(file, ['unban', 'mallory']).code, 0);
const again = await api(srv, 'POST', '/auth/login', { username: 'mallory', password: 'correct horse battery' });
assert.equal(again.status, 200);
assert.equal(cli(file, ['revoke-tokens', 'mallory', '--json']).json.revoked, 1);
assert.equal((await api(srv, 'GET', '/me', null, again.body.token)).status, 401);
assert.equal(cli(file, ['ban', 'nobody']).code, 3);
} finally { await srv.close(); }
});
test('inspect-town, grant (needs --yes), events and replay-events leave the database untouched', async () => {
const dir = tmp();
const file = path.join(dir, 'game.db');
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false, world: { mapRadius: 20 } });
let townId;
try {
const s = await api(srv, 'POST', '/auth/signup', { username: 'ada', password: 'analytical engine' });
townId = s.body.operators[0].towns ? s.body.operators[0].towns[0].id : (await api(srv, 'GET', '/me', null, s.body.token)).body.operators[0].towns[0].id;
const built = await api(srv, 'POST', '/towns/' + townId + '/build', { key: 'f1' }, s.body.token);
assert.equal(built.status, 201, JSON.stringify(built.body));
} finally { await srv.close(); }
const it = cli(file, ['inspect-town', String(townId), '--json']);
assert.equal(it.code, 0, it.err);
assert.equal(it.json.town.id, townId);
assert.ok(it.json.buildings.length >= 1);
assert.equal(it.json.queue.length, 1);
assert.ok(it.json.town.resources.fiber > 0);
assert.equal(cli(file, ['inspect-town', '99999']).code, 3);
assert.equal(cli(file, ['inspect-operator', 'ada', '--json']).json.operators[0].towns[0].id, townId);
// grant: refused without --yes, nothing changes
const before = it.json.town.resources.fiber;
assert.equal(cli(file, ['grant', String(townId), '--fiber', '500']).code, 2);
assert.equal(cli(file, ['inspect-town', String(townId), '--json']).json.town.resources.fiber, before);
const g = cli(file, ['grant', String(townId), '--fiber', '10', '--yes', '--json']);
assert.equal(g.code, 0, g.err);
assert.ok(g.json.after.fiber >= g.json.before.fiber + 9.9);
assert.equal(cli(file, ['grant', String(townId), '--yes']).code, 2);
// events
const ev = cli(file, ['events', '--pending', '--json']);
assert.equal(ev.json.events.length, 1);
assert.equal(ev.json.events[0].type, 'buildDone');
assert.equal(cli(file, ['events', '--type', 'nothing', '--json']).json.events.length, 0);
// replay: dry run and simulation never change the real queue
const dbSnapshot = () => { const db = openDb(file); const r = db.all('SELECT id, status, due_at FROM events ORDER BY id'); const n = db.get('SELECT COUNT(*) AS n FROM notifications').n; const b = db.all('SELECT * FROM buildings ORDER BY town_id, key'); db.close(); return JSON.stringify([r, n, b]); };
const snap = dbSnapshot();
const far = cli(file, ['replay-events', '--until', '+30d', '--simulate', '--json']);
assert.equal(far.code, 0, far.err);
assert.equal(far.json.dueCount, 1);
assert.equal(far.json.simulated.outcome[0].status, 'done');
assert.ok(far.json.simulated.notifications >= 1);
assert.equal(dbSnapshot(), snap, 'the real database is unchanged');
const near = cli(file, ['replay-events', '--json']);
assert.equal(near.json.dueCount, 0);
assert.ok(near.json.next && near.json.next.type === 'buildDone');
assert.equal(dbSnapshot(), snap);
assert.deepEqual(fs.readdirSync(os.tmpdir()).filter((n) => n.startsWith('upstream-replay-')).length, 0, 'scratch copy removed');
});
test('reset-world refuses without --yes-destroy, then wipes the world and keeps accounts', async () => {
const dir = tmp();
const file = path.join(dir, 'game.db');
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false, world: { mapRadius: 20 } });
try {
const s = await api(srv, 'POST', '/auth/signup', { username: 'grace', password: 'compiler compiler' });
assert.equal(s.status, 201);
} finally { await srv.close(); }
const counts = () => { const db = openDb(file); const r = { users: db.get('SELECT COUNT(*) AS n FROM users').n, tokens: db.get('SELECT COUNT(*) AS n FROM tokens').n, towns: db.get('SELECT COUNT(*) AS n FROM towns').n, operators: db.get('SELECT COUNT(*) AS n FROM operators').n, buildings: db.get('SELECT COUNT(*) AS n FROM buildings').n }; db.close(); return r; };
const before = counts();
assert.equal(before.towns, 1);
const refused = cli(file, ['reset-world', '1']);
assert.equal(refused.code, 2);
assert.match(refused.err, /--yes-destroy/);
assert.deepEqual(counts(), before, 'refusal changes nothing');
assert.equal(cli(file, ['reset-world', '1', '--yes']).code, 2, '--yes is not enough for reset-world');
const bk = path.join(dir, 'bk');
const done = cli(file, ['reset-world', '1', '--yes-destroy', '--backup', bk, '--new-seed', '--json']);
assert.equal(done.code, 0, done.err);
const after = counts();
assert.equal(after.towns, 0);
assert.equal(after.operators, 0);
assert.equal(after.buildings, 0);
assert.equal(after.users, 1, 'accounts are kept');
assert.equal(after.tokens, 1, 'tokens are kept');
assert.equal(admin.listBackups(bk).length, 1, 'a backup was taken first');
assert.equal(admin.verifySnapshot(path.join(bk, admin.listBackups(bk)[0].name)).towns, 1, 'the backup still has the town');
assert.equal(cli(file, ['reset-world', '77', '--yes-destroy']).code, 3);
// the world is playable again: the account can join it
const srv2 = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false });
try {
const login = await api(srv2, 'POST', '/auth/login', { username: 'grace', password: 'compiler compiler' });
assert.equal(login.status, 200);
assert.equal(login.body.operators.length, 0);
assert.equal(srv2.db.get('SELECT COUNT(*) AS n FROM worlds').n, 1);
} finally { await srv2.close(); }
});
test('resetPlan finds tables of later stages by world_id and foreign keys', () => {
const db = openDb(':memory:');
migrate(db);
db.exec('CREATE TABLE zz_movements (id INTEGER PRIMARY KEY, world_id INTEGER NOT NULL, town_id INTEGER); CREATE TABLE zz_units (town_id INTEGER, unit TEXT, count INTEGER); CREATE TABLE zz_global (id INTEGER PRIMARY KEY, note TEXT)');
const plan = admin.resetPlan(db, 1);
const names = plan.steps.map((s) => s.table);
for (const t of ['zz_movements', 'zz_units', 'towns', 'buildings', 'events', 'operators']) assert.ok(names.includes(t), t);
assert.ok(names.indexOf('buildings') < names.indexOf('towns'), 'children before parents');
assert.ok(names.indexOf('towns') < names.indexOf('operators'));
assert.ok(plan.skipped.includes('zz_global'));
for (const t of ['users', 'tokens', 'worlds', 'schema_migrations']) assert.ok(!names.includes(t), t);
db.close();
});

186
test/client-api.test.js Normal file
View file

@ -0,0 +1,186 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createApi, ApiError } = require('../public/js/api.js');
// A scripted fetch: each call takes the next response (or throws when given an Error).
function harness(script, extra) {
const calls = [];
const sleeps = [];
let t = 1000;
const store = new Map();
const api = createApi(Object.assign({
fetch: async (url, init) => {
calls.push({ url, init });
const step = script.shift();
if (step instanceof Error) throw step;
t += step.rtt || 0;
return {
ok: step.status >= 200 && step.status < 300, status: step.status,
headers: { get: (k) => (step.headers || {})[k] || null },
json: async () => step.body,
};
},
now: () => t, sleep: async (ms) => { sleeps.push(ms); t += ms; }, jitter: () => 0.5,
storage: { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => store.set(k, v), removeItem: (k) => store.delete(k) },
randomHex: (() => { let n = 0; return () => 'abcdef' + String(++n).padStart(6, '0'); })(),
}, extra));
return { api, calls, sleeps, store, tick: (ms) => { t += ms; } };
}
const ok = (body, more) => Object.assign({ status: 200, body: Object.assign({ serverTime: 5000 }, body) }, more);
const err = (status, code, more) => Object.assign({ status, body: { serverTime: 5000, error: { code, message: code, details: {} } } }, more);
test('bearer token, JSON body and Idempotency-Key on authenticated POST', async () => {
const h = harness([ok({ a: 1 })]);
h.api.setToken('tok');
assert.strictEqual(h.store.get('upstream.token'), 'tok');
await h.api.post('/towns/1/build', { key: 'f1' });
const { url, init } = h.calls[0];
assert.strictEqual(url, 'api/v1/towns/1/build');
assert.strictEqual(init.headers.Authorization, 'Bearer tok');
assert.strictEqual(init.headers['Content-Type'], 'application/json');
assert.ok(h.api.isValidKey(init.headers['Idempotency-Key']));
assert.strictEqual(init.body, '{"key":"f1"}');
});
test('login POST carries no token and no idempotency key; GET carries no key', async () => {
const h = harness([ok({}), ok({})]);
await h.api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false });
assert.strictEqual(h.calls[0].init.headers['Idempotency-Key'], undefined);
assert.strictEqual(h.calls[0].init.headers.Authorization, undefined);
h.api.setToken('t');
await h.api.get('/me');
assert.strictEqual(h.calls[1].init.headers['Idempotency-Key'], undefined);
});
test('query string is encoded and skips undefined values', async () => {
const h = harness([ok({})]);
await h.api.get('/map', { x: -3, y: 4, r: 20, worldId: undefined });
assert.strictEqual(h.calls[0].url, 'api/v1/map?x=-3&y=4&r=20');
});
test('error envelope becomes ApiError with code, status and details', async () => {
const h = harness([{ status: 409, body: { serverTime: 1, error: { code: 'not_enough_resources', message: 'no', details: { key: 'f1' } } } }]);
h.api.setToken('t');
await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }), (e) => e instanceof ApiError && e.code === 'not_enough_resources' && e.status === 409 && e.details.key === 'f1');
});
test('401 clears the token and emits unauthorized', async () => {
const h = harness([err(401, 'unauthorized')]);
h.api.setToken('t');
let fired = 0;
h.api.on('unauthorized', () => fired++);
await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'unauthorized');
assert.strictEqual(fired, 1);
assert.strictEqual(h.api.hasToken(), false);
assert.strictEqual(h.store.has('upstream.token'), false);
});
test('network errors on GET retry with growing backoff, then succeed', async () => {
const h = harness([new TypeError('fail'), new TypeError('fail'), ok({ fine: true })]);
const events = [];
h.api.on('offline', () => events.push('offline')); h.api.on('online', () => events.push('online'));
const r = await h.api.get('/me');
assert.strictEqual(r.fine, true);
assert.deepStrictEqual(h.sleeps, [400, 800]);
assert.deepStrictEqual(events, ['offline', 'online']);
});
test('network errors give up as network_error after the retry budget', async () => {
const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x')], { maxRetries: 2 });
await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'network_error' && e.status === 0);
assert.strictEqual(h.calls.length, 3);
});
test('unkeyed POST (login) is NOT retried on a network error', async () => {
const h = harness([new TypeError('x'), ok({})]);
await assert.rejects(() => h.api.post('/auth/signup', { username: 'a' }, { auth: false }), (e) => e.code === 'network_error');
assert.strictEqual(h.calls.length, 1);
});
test('429 honours Retry-After (seconds) and is retried even for unkeyed POSTs', async () => {
const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '3' } }), ok({ done: 1 })]);
const r = await h.api.post('/auth/login', {}, { auth: false });
assert.strictEqual(r.done, 1);
assert.deepStrictEqual(h.sleeps, [3000]);
});
test('a Retry-After beyond the cap is handed to the caller instead of blocking', async () => {
const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '120' } })]);
await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'rate_limited' && e.retryAfter === 120);
assert.deepStrictEqual(h.sleeps, []);
});
test('retries of one call reuse its Idempotency-Key; the next call gets a new one', async () => {
const h = harness([new TypeError('x'), ok({}), ok({})]);
h.api.setToken('t');
await h.api.post('/towns/1/build', { key: 'f1' });
await h.api.post('/towns/1/build', { key: 'f1' });
const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']);
assert.strictEqual(keys[0], keys[1]);
assert.notStrictEqual(keys[1], keys[2]);
});
test('an intent keeps its key across failed attempts until the server answers', async () => {
const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x'), err(409, 'not_enough_resources'), ok({})], { maxRetries: 0 });
h.api.setToken('t');
for (let i = 0; i < 3; i++) await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'network_error');
assert.deepStrictEqual(h.api.pendingIntents(), ['build:1:f1']);
await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'not_enough_resources');
assert.deepStrictEqual(h.api.pendingIntents(), []); // definite answer: the intent is over
await h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' });
const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']);
assert.strictEqual(new Set(keys.slice(0, 4)).size, 1);
assert.notStrictEqual(keys[4], keys[3]);
});
test('request_in_progress is retried after a short delay', async () => {
const h = harness([err(409, 'request_in_progress'), ok({ x: 1 })]);
h.api.setToken('t');
const r = await h.api.post('/towns/1/build', { key: 'f1' });
assert.strictEqual(r.x, 1);
assert.strictEqual(h.sleeps.length, 1);
});
test('503 on GET is retried, on unkeyed POST is not', async () => {
const a = harness([err(503, 'internal_error'), ok({ y: 1 })]);
assert.strictEqual((await a.api.get('/me')).y, 1);
const b = harness([err(503, 'internal_error'), ok({})]);
await assert.rejects(() => b.api.post('/auth/login', {}, { auth: false }), (e) => e.status === 503);
assert.strictEqual(b.calls.length, 1);
});
test('server clock offset comes from the lowest-latency sample; replayed responses are ignored', async () => {
// t0=1000, rtt 400, serverTime 5000 -> offset 5000 - 1200 = 3800
const h = harness([ok({}, { rtt: 400 }), ok({ serverTime: 99999 }, { rtt: 100 }), ok({ serverTime: 1 }, { rtt: 900 }), ok({ serverTime: 99999 }, { rtt: 1, headers: { 'Idempotent-Replay': 'true' } })]);
await h.api.get('/me');
assert.strictEqual(h.api.serverOffset(), 3800);
await h.api.get('/me'); // better rtt (100): adopted. t0 was 1400 -> mid 1450 -> offset 99999-1450
assert.strictEqual(h.api.serverOffset(), 99999 - 1450);
const before = h.api.serverOffset();
await h.api.get('/me'); // worse rtt: kept
assert.strictEqual(h.api.serverOffset(), before);
await h.api.get('/me'); // replay: ignored
assert.strictEqual(h.api.serverOffset(), before);
});
test('push events can be emitted and unsubscribed; a throwing listener does not break others', () => {
const h = harness([]);
const got = [];
const off = h.api.on('push', (m) => got.push(m));
h.api.on('push', () => { throw new Error('boom'); });
h.api.on('push', (m) => got.push('2:' + m.type));
h.api.emit('push', { type: 'town', id: 1 });
off();
h.api.emit('push', { type: 'x' });
assert.deepStrictEqual(got, [{ type: 'town', id: 1 }, '2:town', '2:x']);
});
test('storage failures fall back to memory', () => {
const api = createApi({ fetch: async () => { throw new Error('unused'); }, storage: { getItem() { throw new Error('denied'); }, setItem() { throw new Error('denied'); }, removeItem() { throw new Error('denied'); } } });
api.setToken('abc');
assert.strictEqual(api.getToken(), 'abc');
api.clearToken();
assert.strictEqual(api.getToken(), null);
});

71
test/client-i18n.test.js Normal file
View file

@ -0,0 +1,71 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const I = require('../public/js/i18n.js');
const D = require('../public/js/data.js');
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(',');
test('en and nb have identical key sets and placeholders', () => {
const en = Object.keys(I.strings.en).sort(), nb = Object.keys(I.strings.nb).sort();
assert.deepStrictEqual(nb.filter((k) => !en.includes(k)), [], 'keys only in nb');
assert.deepStrictEqual(en.filter((k) => !nb.includes(k)), [], 'keys only in en');
for (const k of en) assert.strictEqual(placeholders(I.strings.nb[k]), placeholders(I.strings.en[k]), 'placeholders differ for ' + k);
});
test('every building, resource and tile type has a player-facing name in both languages', () => {
for (const l of I.LANGS) {
for (const b of Object.keys(D.BUILDINGS)) {
assert.ok(I.strings[l]['building.' + b + '.name'], l + ' name for ' + b);
assert.ok(I.strings[l]['building.' + b + '.desc'], l + ' desc for ' + b);
}
for (const r of D.RESOURCES.concat(['power', 'battery'])) assert.ok(I.strings[l]['res.' + r], l + ' res.' + r);
for (const t of ['land', 'rural', 'incumbent', 'pop', 'void']) assert.ok(I.strings[l]['tile.' + t], l + ' tile.' + t);
}
});
test('every error code the client can meet is translated', () => {
// codes the current screens can see (auth, build, cancel, rename, map, notifications, tokens) + client-side ones
const codes = ['bad_request', 'validation_failed', 'unauthorized', 'invalid_credentials', 'forbidden', 'not_found', 'conflict', 'request_in_progress',
'idempotency_key_reuse', 'payload_too_large', 'rate_limited', 'internal_error', 'signup_closed', 'username_taken', 'world_full', 'unknown_building',
'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources', 'network_error', 'unknown', 'method_not_allowed'];
for (const l of I.LANGS) for (const c of codes) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c);
});
test('t() fills placeholders, falls back to en then to the key', () => {
assert.strictEqual(I.t('en', 'sheet.build', { n: 3 }), 'Build level 3');
assert.strictEqual(I.t('nb', 'sheet.build', { n: 3 }), 'Bygg nivå 3');
assert.strictEqual(I.t('xx', 'common.close'), 'Close');
assert.strictEqual(I.t('en', 'no.such.key'), 'no.such.key');
assert.strictEqual(I.t('en', 'sheet.build'), 'Build level {n}');
});
test('duration and clock formatting', () => {
assert.strictEqual(I.fmtDuration('en', 0), '0s');
assert.strictEqual(I.fmtDuration('en', 45000), '45s');
assert.strictEqual(I.fmtDuration('en', 133000), '2m 13s');
assert.strictEqual(I.fmtDuration('en', 3600000), '1h');
assert.strictEqual(I.fmtDuration('en', 3600000 * 26 + 60000 * 5), '1d 2h');
assert.strictEqual(I.fmtDuration('nb', 3600000 * 2 + 60000 * 5), '2t 5m');
assert.strictEqual(I.fmtClock(1), '0:01');
assert.strictEqual(I.fmtClock(65000), '1:05');
assert.strictEqual(I.fmtClock(3661000), '1:01:01');
assert.strictEqual(I.fmtClock(-5), '0:00');
});
test('number formatting', () => {
assert.strictEqual(I.fmtNum('en', 749.9), '749');
assert.strictEqual(I.fmtNum('en', 123456), '123k');
assert.strictEqual(I.fmtNum('en', 2500000), '2.5M');
assert.strictEqual(I.fmtDec('en', 12.34, true), '+12.3');
assert.strictEqual(I.fmtDec('en', -3, true), '−3.0');
assert.strictEqual(I.fmtDec('en', 420.4), '420');
});
test('language detection', () => {
assert.strictEqual(I.detectLang('nb-NO'), 'nb');
assert.strictEqual(I.detectLang('nn'), 'nb');
assert.strictEqual(I.detectLang('no'), 'nb');
assert.strictEqual(I.detectLang('en-GB'), 'en');
assert.strictEqual(I.detectLang(undefined), 'en');
});

111
test/helpers.js Normal file
View file

@ -0,0 +1,111 @@
'use strict';
/*
* Shared test helpers (no tests in here). An in-memory server on port 0 with a fake clock and no background timer:
* events only run when a request, a command or the test calls scheduler.runDue().
*
* const { createTestServer } = require('./helpers');
* const t = await createTestServer();
* const alice = await t.signup('alice'); // { token, userId, operatorId, townId, name }
* const r = await t.api('/alliances', { method: 'POST', body: { name: 'X', tag: 'X1' } }, alice.token);
* t.clock.advance(3600e3); t.srv.scheduler.runDue();
* await t.close();
*/
const assert = require('node:assert');
const { createServer } = require('../server');
const { FakeClock } = require('../server/clock');
// ---- optional response contract check: every 2xx JSON body must satisfy its route's declared `response` schema
// (server/routes/schemas.js), error bodies the Error schema. Opt-in: createTestServer({ contract: true }).
let contractRouter = null;
function contract() {
if (contractRouter) return contractRouter;
const { Router } = require('../server/http');
const routes = require('../server/routes');
const router = new Router();
routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null, apply: () => null }) }));
contractRouter = { router, schemas: require('../server/routes/schemas').schemas };
return contractRouter;
}
function conforms(schemas, schema, v, path, errs) {
if (schema.$ref) return conforms(schemas, schemas[schema.$ref], v, path, errs);
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
if (v === null) { if (!types.includes('null')) errs.push(path + ' is null'); return; }
const t = types.find((x) => x !== 'null');
if (t === 'integer') { if (!Number.isInteger(v)) errs.push(path + ' not an integer: ' + JSON.stringify(v)); }
else if (t === 'number') { if (typeof v !== 'number') errs.push(path + ' not a number'); }
else if (t === 'string') { if (typeof v !== 'string') errs.push(path + ' not a string'); }
else if (t === 'boolean') { if (typeof v !== 'boolean') errs.push(path + ' not a boolean'); }
else if (t === 'array') {
if (!Array.isArray(v)) errs.push(path + ' not an array');
else if (schema.items) v.forEach((x, i) => conforms(schemas, schema.items, x, path + '[' + i + ']', errs));
} else if (t === 'object') {
if (typeof v !== 'object' || Array.isArray(v)) { errs.push(path + ' not an object'); return; }
for (const k of schema.required || []) if (!(k in v)) errs.push(path + '.' + k + ' missing');
for (const k of Object.keys(schema.properties || {})) if (k in v) conforms(schemas, schema.properties[k], v[k], path + '.' + k, errs);
}
}
function checkContract(method, path, status, body) {
const { router, schemas } = contract();
const found = router.find(method, path.split('?')[0].replace(/^\/api\/v1/, ''));
if (!found || !found.route) return;
const errs = [];
conforms(schemas, status < 300 ? (found.route.meta.response || { $ref: 'Ok' }) : { $ref: 'Error' }, body, '', errs);
if (errs.length) throw new assert.AssertionError({ message: method + ' ' + path + ' -> ' + status + ' breaks its response schema: ' + errs.join('; ') + ' in ' + JSON.stringify(body).slice(0, 400) });
}
async function createTestServer(o) {
o = o || {};
const clock = o.clock || new FakeClock();
const srv = await createServer(Object.assign({
port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {},
// many signups and calls from one IP: lift the per-IP/token/auth rate limits
ipRate: 1e6, ipBurst: 1e6, tokenRate: 1e6, tokenBurst: 1e6, authRate: 1e6, authBurst: 1e6,
}, o.server || {}));
const base = 'http://127.0.0.1:' + srv.port + '/api/v1';
// api(path, { method, body, headers }, token) -> { status, body, headers }
async function api(path, opts, token) {
opts = opts || {};
const headers = Object.assign({ 'content-type': 'application/json' }, opts.headers || {});
if (token) headers.authorization = 'Bearer ' + token;
const r = await fetch(base + path, { method: opts.method || 'GET', headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body) });
const out = { status: r.status, body: await r.json(), headers: r.headers };
if (o.contract) checkContract(opts.method || 'GET', path, out.status, out.body);
return out;
}
const names = new Map();
async function signup(name) {
const r = await api('/auth/signup', { method: 'POST', body: { username: name, password: 'correct horse battery' } });
assert.equal(r.status, 201, 'signup ' + name + ': ' + JSON.stringify(r.body));
const op = r.body.operators[0];
const u = { token: r.body.token, userId: r.body.user.id, operatorId: op.id, townId: op.towns[0].id, name };
names.set(name, u);
return u;
}
// Set a building level directly (tests that need a Peering office without playing through the build chain).
function setBuilding(townId, type, level) {
srv.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?) ON CONFLICT (town_id, key) DO UPDATE SET level = excluded.level', townId, type, type, level);
}
// signup + Peering office level (default 1), ready to found or join an alliance.
async function signupPeering(name, level) {
const u = await signup(name);
setBuilding(u.townId, 'peering_office', level === undefined ? 1 : level);
return u;
}
// Bulk operators without the scrypt cost and without a usable token (drive them through srv.commands.run).
function quickSignup(name) {
const r = srv.commands.run('signup', { username: name, passHash: 'x', tokenHash: require('crypto').randomBytes(16).toString('hex'), device: 'test' });
return { userId: r.userId, operatorId: r.operatorId, townId: r.townId, name };
}
const close = () => srv.close();
return { srv, clock, api, signup, signupPeering, quickSignup, setBuilding, close, base };
}
module.exports = { createTestServer, checkContract };

121
test/military-api.test.js Normal file
View file

@ -0,0 +1,121 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createServer } = require('../server');
const { FakeClock } = require('../server/clock');
const T = require('./military-helpers');
const { D, H } = T;
// A real server on port 0 with a fake clock: signup two players over HTTP, then drive the military routes.
async function boot() {
const clock = new FakeClock();
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {} });
const base = 'http://127.0.0.1:' + srv.port + '/api/v1';
const call = async (p, o, token) => {
o = o || {};
const headers = Object.assign({ 'content-type': 'application/json' }, o.headers || {});
if (token) headers.authorization = 'Bearer ' + token;
const r = await fetch(base + p, Object.assign({}, o, { headers, body: o.body && JSON.stringify(o.body) }));
return { status: r.status, body: await r.json() };
};
const signup = async (username) => {
const r = await call('/auth/signup', { method: 'POST', body: { username, password: 'correct horse battery' } });
assert.equal(r.status, 201, JSON.stringify(r.body));
const t = r.body.operators[0].towns[0];
return { token: r.body.token, townId: t.id, x: t.x, y: t.y, opId: r.body.operators[0].id, userId: r.body.user.id };
};
return { srv, clock, call, signup };
}
test('API: train, send a raid, warning for the target, reports, recall, error codes', async () => {
const { srv, clock, call, signup } = await boot();
try {
const a = await signup('alice'), b = await signup('bobby');
const db = srv.db;
// both start protected (72 h): move the clock past it, give alice infrastructure to train
clock.advance(73 * H);
for (const [t, 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, t, t, lv);
db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId);
let r = await call('/towns/' + a.townId + '/train', { method: 'POST', body: { unit: 'script_crew', count: 20 } }, a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
assert.equal(typeof r.body.serverTime, 'number');
r = await call('/towns/' + a.townId, {}, a.token);
assert.equal(r.body.town.military.training.length, 1);
assert.equal(r.body.town.military.trainable.find((u) => u.unit === 'script_crew').locked, false);
assert.equal(r.body.town.military.trainable.find((u) => u.unit === 'botnet').locked, true);
clock.advance(3 * H);
r = await call('/towns/' + a.townId, {}, a.token);
assert.deepEqual(r.body.town.military.units.home, { script_crew: 20 });
// errors are enveloped with stable codes
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 99 } } }, a.token);
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'not_enough_units');
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 5 } } }, b.token);
assert.equal(r.status, 404, 'cannot send from somebody else\'s POP');
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 5 }, extra: 1 } }, a.token);
assert.equal(r.status, 422);
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'teleport', toTownId: b.townId, units: {} } }, a.token);
assert.equal(r.status, 422);
// alice is protected no more (73 h passed) and bob neither: the raid goes out
r = await call('/movements', { method: 'POST', headers: { 'idempotency-key': 'raid-key-0001' }, body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } } }, a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
const mid = r.body.movementId;
const replay = await call('/movements', { method: 'POST', headers: { 'idempotency-key': 'raid-key-0001' }, body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } } }, a.token);
assert.equal(replay.body.movementId, mid, 'idempotent replay: no second movement');
assert.equal(db.get('SELECT COUNT(*) AS n FROM movements').n, 1);
r = await call('/movements', {}, b.token);
assert.equal(r.body.incoming.length, 1); assert.equal(r.body.incoming[0].type, 'unknown');
r = await call('/movements', {}, a.token);
assert.equal(r.body.outgoing[0].type, 'raid');
// recall inside 90 s, then send again and let it land
r = await call('/movements/' + mid + '/recall', { method: 'POST' }, a.token);
assert.equal(r.status, 200, JSON.stringify(r.body));
clock.advance(H);
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 } } }, a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
clock.advance(100 * 1000);
r = await call('/movements/' + r.body.movementId + '/recall', { method: 'POST' }, a.token);
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'recall_expired');
clock.advance(5 * H);
r = await call('/reports', {}, a.token);
assert.equal(r.status, 200); assert.equal(r.body.items.length, 1); assert.equal(r.body.unread, 1);
const id = r.body.items[0].id;
const rb = await call('/reports', {}, b.token);
assert.equal(rb.body.items[0].id, id, 'defender sees the same report');
r = await call('/reports/' + id, {}, a.token);
assert.equal(r.body.report.type, 'raid'); assert.equal(r.body.report.data.outcome, 'attacker_won');
r = await call('/reports/' + id + '/read', { method: 'POST' }, a.token);
assert.equal(r.status, 200);
r = await call('/reports?unread=true', {}, a.token);
assert.equal(r.body.items.length, 0);
r = await call('/reports/999999', {}, a.token);
assert.equal(r.status, 404);
// tile info and research over the API
r = await call('/map/tile?x=' + b.x + '&y=' + b.y, {}, a.token);
assert.equal(r.body.type, 'pop'); assert.equal(r.body.town.owner.name, 'bobby');
r = await call('/towns/' + a.townId + '/research', { method: 'POST', body: { unit: 'script_crew', stat: 'attack' } }, a.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
r = await call('/towns/' + a.townId + '/research', { method: 'POST', body: { unit: 'script_crew', stat: 'attack' } }, a.token);
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'queue_full');
r = await call('/notifications', {}, b.token);
assert.ok(r.body.items.some((n) => n.type === 'incoming'));
assert.ok(r.body.items.some((n) => n.type === 'report'));
} finally { await srv.close(); }
});
test('API: openapi describes every military route', () => {
const { build } = require('../tools/gen-openapi');
const spec = build();
for (const [p, m] of [['/towns/{id}/train', 'post'], ['/towns/{id}/research', 'post'], ['/movements', 'post'], ['/movements', 'get'], ['/movements/{id}/recall', 'post'],
['/towns/{id}/withdraw', 'post'], ['/reports', 'get'], ['/reports/{id}', 'get'], ['/reports/{id}/read', 'post'], ['/reports/read-all', 'post'], ['/map/tile', 'get']]) {
assert.ok(spec.paths[p] && spec.paths[p][m], m + ' ' + p + ' is in openapi.json');
}
for (const c of ['not_enough_units', 'units_offline', 'target_protected', 'protection_active', 'footprint_too_low', 'cannot_takeover', 'recall_expired']) assert.ok(spec['x-error-codes'][c], c);
assert.ok(D.UNIT_ORDER.length === 10);
});

View file

@ -0,0 +1,203 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D, H } = T;
const { loadTown } = require('../server/state');
function sendTakeover(h, att, targetTownId, units) {
return h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: targetTownId, units: units || { script_crew: 80, ma_team: 2 } });
}
test('takeover: loyalty drops by the seeded roll, the POP changes owner at zero, pending work stops', () => {
const h = T.setup();
const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 80, ma_team: 2 } });
const def = T.addOperator(h, 'seller', { x: 10, y: 0 });
const extra = T.addTown(h, def, { x: 12, y: 2, infra: { noc: 2 } });
h.db.run('UPDATE towns SET loyalty = 40, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId);
h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, 4)', extra.townId, 'soc_analyst');
h.run('train', { userId: def.userId, townId: extra.townId, unit: 'soc_analyst', count: 5 }); // pending work that must be cancelled
let s = sendTakeover(h, att, extra.townId);
h.advanceTo(s.arriveAt);
let rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.outcome, 'attacker_won');
assert.equal(rep.takeover.attempted, true);
assert.ok(rep.takeover.drop >= 15 && rep.takeover.drop <= 30, 'drop in range');
assert.equal(rep.takeover.captured, false, '40 loyalty needs two hits');
assert.ok(Math.abs(T.town(h, extra.townId).loyalty - (rep.takeover.loyaltyBefore - rep.takeover.drop)) < 0.01);
assert.equal(T.town(h, extra.townId).owner_id, def.opId);
const retMv = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
assert.equal(JSON.parse(retMv.units).ma_team, 1, 'one M&A team was used up, the other comes home');
// second hit
h.advanceTo(retMv.arrive_at);
h.db.run('UPDATE towns SET loyalty = 10, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId);
s = sendTakeover(h, att, extra.townId, { script_crew: 70, ma_team: 1 });
h.advanceTo(s.arriveAt);
rep = T.reportsOf(h, att.userId)[1].data;
assert.equal(rep.takeover.captured, true);
const taken = T.town(h, extra.townId);
assert.equal(taken.owner_id, att.opId);
assert.equal(taken.is_capital, 0);
assert.equal(taken.loyalty, D.EXPANSION.conqueredLoyalty);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending'", extra.townId).n, 0, 'old owner training cancelled');
assert.deepEqual(T.units(h, extra.townId), {}, 'the defenders died with the loss');
assert.equal(T.notes(h, def.userId, 'town_lost').length, 1);
assert.equal(T.notes(h, att.userId, 'town_gained').length, 1);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', def.opId).n, 1);
// loyalty then regenerates for the new owner (+1/h)
const t = loadTown(h.db, extra.townId);
assert.equal(R.loyaltyAt(t.loyalty, t.loyaltyAt, t.loyaltyAt + 10 * H, 1), D.EXPANSION.conqueredLoyalty + 10);
});
test('takeover protections: capital is only drained, last POP and low footprint are refused', () => {
const h = T.setup();
const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 160, ma_team: 4 } });
const def = T.addOperator(h, 'seller', { x: 10, y: 0 });
const second = T.addTown(h, def, { x: 12, y: 2 });
const lone = T.addOperator(h, 'lone', { x: 20, y: 0 });
// last POP: refused at send
assert.throws(() => sendTakeover(h, att, lone.townId), (e) => e.code === 'cannot_takeover');
// capital: loyalty is dragged to zero, the owner stays
h.db.run('UPDATE towns SET loyalty = 5, loyalty_at = ? WHERE id = ?', h.clock.now(), def.townId);
const s = sendTakeover(h, att, def.townId, { script_crew: 80, ma_team: 2 });
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.takeover.capital, true);
assert.equal(rep.takeover.captured, false);
assert.equal(T.town(h, def.townId).loyalty, 0);
assert.equal(T.town(h, def.townId).owner_id, def.opId);
// footprint gate
const poor = T.addOperator(h, 'poor', { x: 30, y: 0, footprint: 10, units: { script_crew: 80, ma_team: 1 } });
assert.throws(() => sendTakeover(h, poor, second.townId, { script_crew: 80, ma_team: 1 }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(1));
// a takeover needs an M&A team, which only goes on takeovers
assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: second.townId, units: { script_crew: 5 } }), (e) => e.code === 'validation_failed');
assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: second.townId, units: { script_crew: 5, ma_team: 1 } }), (e) => e.code === 'validation_failed');
});
test('exploit kits damage the chosen building on a win; DDoS rigs lower the firewall in the battle', () => {
const h = T.setup();
const att = T.addOperator(h, 'siege', { x: 5, y: 0, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 } });
const def = T.addOperator(h, 'wall', { x: 9, y: 0, units: { soc_analyst: 40 }, infra: { firewall: 10, noc: 7 } });
const s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 }, target: 'noc' });
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.outcome, 'attacker_won');
assert.equal(rep.power.effectiveFirewall, 8, '20 rigs lower a level-10 firewall by 2');
assert.equal(rep.siege.key, 'noc');
const kits = rep.attacker.units.survivors.exploit_kit;
assert.equal(rep.siege.to, 7 - R.siegeLevels(kits));
assert.equal(h.db.get('SELECT level FROM buildings WHERE town_id = ? AND key = ?', def.townId, 'noc').level, rep.siege.to);
// the lost units are gone for good
assert.deepEqual(T.units(h, def.townId), {});
});
test('protection: protected targets cannot be attacked, attacking ends your own protection, arrival re-checks', () => {
const h = T.setup();
const now = h.clock.now();
const newbie = T.addOperator(h, 'newbie', { x: 5, y: 0, protectedUntil: now + 72 * H, units: { script_crew: 20, port_scanner: 3 } });
const vet = T.addOperator(h, 'vet', { x: 9, y: 0, units: { script_crew: 40, port_scanner: 3 } });
// nobody may attack a protected operator ...
assert.throws(() => h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'raid', toTownId: newbie.townId, units: { script_crew: 10 } }), (e) => e.code === 'target_protected');
// ... but scouting is allowed
h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'scan', toTownId: newbie.townId, units: { port_scanner: 3 } });
// a protected operator must confirm to attack, which ends the protection at once
assert.throws(() => h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 } }), (e) => e.code === 'protection_active');
assert.ok(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p > now, 'the refused send changed nothing');
const r = h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 }, confirmEndProtection: true });
assert.equal(r.protectionEnded, true);
assert.equal(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p, now);
// protection that lasts past the arrival blocks the attack at arrival time (units turn around, report to the sender)
const h2 = T.setup();
const a2 = T.addOperator(h2, 'a', { x: 5, y: 0, units: { script_crew: 30 } });
const d2 = T.addOperator(h2, 'd', { x: 9, y: 0, units: { soc_analyst: 2 } });
const s2 = h2.run('sendMovement', { userId: a2.userId, fromTownId: a2.townId, type: 'raid', toTownId: d2.townId, units: { script_crew: 30 } });
h2.db.run('UPDATE operators SET protection_until = ? WHERE id = ?', s2.arriveAt + H, d2.opId); // e.g. an admin grants protection
h2.advanceTo(s2.arriveAt);
const rep = T.reportsOf(h2, a2.userId)[0];
assert.equal(rep.type, 'movement_failed');
assert.equal(rep.data.reason, 'protected');
assert.equal(T.reportsOf(h2, d2.userId).length, 0, 'the protected side is not bothered');
assert.deepEqual(T.units(h2, d2.townId), { soc_analyst: 2 });
h2.advance(10 * H);
assert.equal(T.units(h2, a2.townId).script_crew, 30, 'the units came back untouched');
});
test('expansion: three Rollout crews found a POP; wild slots, empty start, range, footprint, occupied tile', () => {
const h = T.setup();
const a = T.addOperator(h, 'founder', { x: 5, y: 0, footprint: 3000, units: { rollout_crew: 9 } });
const spot = T.landNear(h, 12, 3);
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 }, wild: ['substation', 'sales_office'] });
assert.equal(T.units(h, a.townId).rollout_crew, 6);
h.advanceTo(s.arriveAt);
const t = h.db.get('SELECT * FROM towns WHERE x = ? AND y = ?', spot.x, spot.y);
assert.ok(t, 'a new POP exists');
assert.equal(t.owner_id, a.opId); assert.equal(t.is_capital, 0);
const b = h.db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', t.id);
assert.ok(b.every((x) => x.level === 0), 'everything at level 0');
assert.equal(b.length, D.FIELD_SLOTS, 'fields only, no infrastructure');
assert.equal(b.find((x) => x.key === 'f17').type, 'substation');
assert.equal(b.find((x) => x.key === 'f18').type, 'sales_office');
assert.equal(t.fiber, D.EXPANSION.startResources.fiber);
assert.equal(T.reportsOf(h, a.userId)[0].type, 'settle');
assert.equal(T.units(h, a.townId).rollout_crew, 6, 'the crews were consumed');
// the second extra POP needs more footprint (500 * 2^1.8 = 1741 for the 2nd extra; the operator has 3000 + ...)
h.db.run('UPDATE towns SET footprint = 700 WHERE id = ?', a.townId);
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x + 2, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(2));
// too far from every own POP
const far = T.landNear(h, 30, 0);
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: far.x, y: far.y, units: { rollout_crew: 3 } }), (e) => e.code === 'out_of_range');
// not exactly three crews
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y + 3, units: { rollout_crew: 2 } }), (e) => e.code === 'validation_failed');
// an occupied tile
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'invalid_target');
// somebody else takes the tile while the crews are on the way: the crews come home with a report
h.db.run('UPDATE towns SET footprint = 99999 WHERE id = ?', a.townId);
const free = T.landNear(h, 10, -4);
const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: free.x, y: free.y, units: { rollout_crew: 3 } });
const squatter = T.addOperator(h, 'squatter', { x: free.x, y: free.y }); // lands exactly on `free`
assert.equal(squatter.x, free.x);
h.advanceTo(s2.arriveAt);
const failed = T.reportsOf(h, a.userId).filter((r) => r.type === 'movement_failed');
assert.equal(failed.length, 1);
assert.equal(failed[0].data.reason, 'invalid_target');
h.advance(48 * H);
assert.equal(T.units(h, a.townId).rollout_crew, 6, 'crews returned');
});
test('incumbent site: static defence, one-time Hardware bonus per operator, research speed bonus', () => {
const h = T.setup({ seed: 99 });
let site = null;
for (let x = -20; x <= 20 && !site; x++) for (let y = -20; y <= 20 && !site; y++) if (R.tileAt(h.world.seed, 50, x, y).type === 'incumbent' && Math.abs(x) + Math.abs(y) > 6) site = { x, y };
assert.ok(site, 'the test world has an incumbent site');
const need = R.incumbentDefence(h.world.seed, site.x, site.y, 0);
const crews = Math.ceil(need / 40 * 1.6);
const a = T.addOperator(h, 'raider', { x: site.x - 3, y: site.y, res: 3000, units: { script_crew: crews } });
const hwBefore = T.town(h, a.townId).hardware;
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: { script_crew: crews } });
assert.equal(s.toTownId, null);
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, a.userId)[0];
assert.equal(rep.type, 'incumbent');
assert.equal(rep.data.outcome, 'attacker_won');
assert.equal(rep.data.bonus.hardware, D.INCUMBENT.hardwareBonus);
assert.ok(rep.data.bonus.researchSpeedBonus > 0);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', a.opId).n, 1);
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
h.advanceTo(ret.arrive_at);
assert.ok(T.town(h, a.townId).hardware > hwBefore + 1000, 'the bonus arrived with the survivors');
// a second take gives no second bonus
const back = JSON.parse(ret.units);
const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: back });
h.advanceTo(s2.arriveAt);
assert.equal(T.reportsOf(h, a.userId)[1].data.bonus, null);
// research gets faster
const plain = R.researchTimeMs('script_crew', 1, 8, 1, 0), fast = R.researchTimeMs('script_crew', 1, 8, 1, R.researchSpeedBonus(1));
assert.ok(fast < plain);
// incumbent sites accept only scans and attacks, and defence scales with world age
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', x: site.x, y: site.y, units: { script_crew: 1 } }), (e) => e.code === 'invalid_target' || e.code === 'not_enough_units');
assert.ok(R.incumbentDefence(h.world.seed, site.x, site.y, 50) > need);
});

148
test/military-flow.test.js Normal file
View file

@ -0,0 +1,148 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D, H } = T;
test('training: batches of one building run in order, other buildings in parallel, requirements and queue limit', () => {
const h = T.setup();
const a = T.addOperator(h, 'alice');
const t0 = h.clock.now();
const r1 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 10 });
const r2 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'port_scanner', count: 4 }); // same building (noc): after r1
const r3 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'script_crew', count: 5 }); // ops_lab: in parallel
assert.equal(r1.startAt, t0);
assert.equal(r2.startAt, r1.dueAt, 'second noc batch starts when the first is done');
assert.equal(r3.startAt, t0, 'other buildings train in parallel');
assert.equal(r1.dueAt - r1.startAt, R.trainTimeMs('soc_analyst', 10, 5, 1));
assert.deepEqual(T.units(h, a.townId), {});
h.advanceTo(r3.dueAt);
assert.deepEqual(T.units(h, a.townId), { script_crew: 5 }, 'only the parallel batch is done so far');
h.advanceTo(r1.dueAt);
assert.deepEqual(T.units(h, a.townId), { script_crew: 5, soc_analyst: 10 });
h.advanceTo(r2.dueAt);
assert.deepEqual(T.units(h, a.townId), { script_crew: 5, soc_analyst: 10, port_scanner: 4 });
assert.equal(T.notes(h, a.userId, 'train_done').length, 3);
// unit power draw is part of the town's rates once the units exist
const t = require('../server/state').loadTown(h.db, a.townId);
assert.equal(t.unitDraw, 10 * 1 + 4 * 1 + 5 * 1);
// costs were paid; requirements are enforced; the queue is limited
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'exploit_kit', count: 1 }), (e) => e.code === 'requirements_not_met');
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'nonsense', count: 1 }), (e) => e.code === 'unknown_unit');
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 100000 }), (e) => e.code === 'validation_failed');
const b = T.addOperator(h, 'bob', { res: 100 });
assert.throws(() => h.run('train', { userId: b.userId, townId: b.townId, unit: 'botnet', count: 50 }), (e) => e.code === 'not_enough_resources' || e.code === 'requirements_not_met');
for (let i = 0; i < D.MILITARY.maxTrainQueue; i++) h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 });
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 }), (e) => e.code === 'queue_full');
});
test('raid end to end: send, incoming warning, arrive, loot, reports for both sides, return', () => {
const h = T.setup();
const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 40 } });
const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 20 }, infra: { rack_hall: 2 } });
h.db.run('UPDATE towns SET fiber = 600, hardware = 600, capital = 600 WHERE id = ?', def.townId);
const before = T.town(h, def.townId);
const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } });
assert.equal(T.units(h, att.townId).script_crew, undefined, 'units left home');
assert.equal(sent.arriveAt - sent.departAt, R.latencyMs(4, 8, 1));
// the target sees origin and ETA but not the type
const mv = h.mq.movements(def.userId, {});
assert.equal(mv.incoming.length, 1);
assert.equal(mv.incoming[0].type, 'unknown');
assert.equal(mv.incoming[0].units, undefined);
assert.equal(mv.incoming[0].arriveAt, sent.arriveAt);
assert.equal(h.mq.movements(att.userId, {}).outgoing[0].type, 'raid');
assert.equal(T.notes(h, def.userId, 'incoming').length, 1);
assert.equal(T.notes(h, def.userId, 'incoming')[0].type, undefined);
h.advanceTo(sent.arriveAt);
const ra = T.reportsOf(h, att.userId), rd = T.reportsOf(h, def.userId);
assert.equal(ra.length, 1); assert.equal(rd.length, 1);
assert.equal(ra[0].id, rd[0].id, 'one report shared by both sides');
assert.equal(ra[0].role, 'attacker'); assert.equal(rd[0].role, 'defender');
const rep = ra[0].data;
assert.equal(rep.outcome, 'attacker_won');
assert.ok(rep.loot.fiber > 0 && rep.loot.fiber === rep.loot.hardware, 'loot is split evenly');
// 10% per rack hall level hides stock from a raid: level 2 hides 20%
assert.equal(rep.cacheHidden, 0.2);
const d1 = T.town(h, def.townId);
assert.ok(d1.fiber < before.fiber, 'target lost fiber');
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
assert.ok(ret, 'a return movement carries the loot');
assert.deepEqual(JSON.parse(ret.cargo), rep.loot);
const attBefore = T.town(h, att.townId).fiber;
h.advanceTo(ret.arrive_at);
assert.equal(T.units(h, att.townId).script_crew, 40 - (rep.attacker.units.lost.script_crew || 0));
assert.ok(T.town(h, att.townId).fiber > attBefore, 'loot arrived home');
assert.equal(T.notes(h, att.userId, 'movement_returned').length, 1);
const stats = h.db.get('SELECT * FROM operator_stats WHERE operator_id = ?', att.opId);
assert.ok(stats.attack_points > 0, 'killed units give battle points');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
});
test('a failed raid loses units and loots nothing; both sides still get the report', () => {
const h = T.setup();
const att = T.addOperator(h, 'weak', { x: 5, y: 0, units: { script_crew: 2 } });
const def = T.addOperator(h, 'strong', { x: 8, y: 0, units: { blue_team: 20 }, infra: { firewall: 10 } });
const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 2 } });
h.advanceTo(sent.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.outcome, 'defender_won');
assert.deepEqual(rep.loot, { fiber: 0, hardware: 0, capital: 0 });
assert.equal(T.units(h, def.townId).blue_team, 20 - (rep.defender.groups[0].lost.blue_team || 0));
assert.equal(T.reportsOf(h, def.userId).length, 1);
});
test('scan: success shows units, resources, buildings at 2:1; failed scan loses scanners and reveals the scanner', () => {
const h = T.setup();
const att = T.addOperator(h, 'spy', { x: 5, y: 0, units: { port_scanner: 10 } });
const def = T.addOperator(h, 'watched', { x: 8, y: 0, units: { port_scanner: 3, soc_analyst: 4 } });
let s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'scan', toTownId: def.townId, units: { port_scanner: 10 } });
h.advanceTo(s.arriveAt);
const ok = T.reportsOf(h, att.userId).find((r) => r.type === 'scan').data;
assert.equal(ok.success, true);
assert.equal(ok.detail, 'full'); // 10 >= 2 * 3
assert.deepEqual(ok.intel.units.home, { port_scanner: 3, soc_analyst: 4 });
assert.ok(ok.intel.buildings.length > 0 && ok.intel.resources.fiber > 0);
const det = T.reportsOf(h, def.userId).find((r) => r.type === 'scan_detected').data;
assert.equal(det.identityRevealed, false, 'the defender only learns who scanned when their scanners win');
assert.equal(det.by, null);
// now a scan that fails: 2 scanners against 3
h.advance(3 * H);
h.db.run("UPDATE town_units SET count = 2 WHERE town_id = ? AND unit = 'port_scanner'", att.townId); // 10 came home (minus losses); keep 2 for the test
s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'scan', toTownId: def.townId, units: { port_scanner: 2 } });
h.advanceTo(s.arriveAt);
const bad = T.reportsOf(h, att.userId).filter((r) => r.type === 'scan')[1].data;
assert.equal(bad.success, false);
assert.deepEqual(bad.scanners.survivors, {});
const det2 = T.reportsOf(h, def.userId).filter((r) => r.type === 'scan_detected')[1].data;
assert.equal(det2.identityRevealed, true);
assert.equal(det2.by.operator.name, 'spy');
});
test('event order: combat resolves in (arrive time, id) order and the whole run is deterministic', () => {
function run() {
const h = T.setup({ seed: 777 });
const slow = T.addOperator(h, 'slow', { x: 40, y: 0, units: { script_crew: 60 } });
const fast = T.addOperator(h, 'fast', { x: 20, y: 0, units: { botnet: 25 } });
const def = T.addOperator(h, 'victim', { x: 8, y: 0, units: { soc_analyst: 30 } });
h.db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', def.townId);
const a = h.run('sendMovement', { userId: slow.userId, fromTownId: slow.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 60 } });
const b = h.run('sendMovement', { userId: fast.userId, fromTownId: fast.townId, type: 'raid', toTownId: def.townId, units: { botnet: 25 } });
assert.ok(a.movementId < b.movementId);
h.advance(200 * H);
return { h, a, b, slow, fast, def };
}
const x = run(), y = run();
assert.ok(x.b.arriveAt < x.a.arriveAt, 'the botnet raid is faster although it was sent second');
const reps = x.h.db.all("SELECT id, type, created_at FROM reports WHERE type IN ('raid','attack') ORDER BY id");
assert.deepEqual(reps.map((r) => r.type), ['raid', 'attack'], 'reports are created in arrival order');
assert.ok(T.snapshot(x.h) === T.snapshot(y.h), 'same inputs, same world seed: identical state');
assert.equal(x.h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
});

108
test/military-helpers.js Normal file
View file

@ -0,0 +1,108 @@
'use strict';
/* Shared fixtures of the military tests: an in-memory (or file) game with a fake clock and hand-placed operators.
* Not a test file itself (node:test finds no tests in it). */
const crypto = require('crypto');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { openDb, migrate } = require('../server/db');
const { FakeClock } = require('../server/clock');
const { Scheduler } = require('../server/scheduler');
const { createCommands } = require('../server/commands');
const { createQueries } = require('../server/queries');
const { createWorld } = require('../server/world');
const { createTown } = require('../server/commands/joinWorld');
const handlers = require('../server/events');
const { createMilitaryQueries } = require('../server/military/views');
const H = D.HOUR_MS;
function setup(o) {
o = o || {};
const clock = o.clock || new FakeClock();
const db = openDb(o.file || ':memory:');
migrate(db);
const row = db.get('SELECT id FROM worlds LIMIT 1');
const worldId = row ? row.id : createWorld(db, clock.now(), { seed: o.seed || 4242, speed: o.speed || 1, mapRadius: o.radius || 50 });
const scheduler = new Scheduler({ db, clock, handlers, autoArm: false, log: o.log || (() => {}) });
const commands = createCommands({ db, clock, scheduler });
const queries = createQueries({ db, clock, scheduler });
const mq = createMilitaryQueries({ db, clock, scheduler });
const world = db.get('SELECT * FROM worlds WHERE id = ?', worldId);
const h = { db, clock, scheduler, commands, queries, mq, worldId, world };
h.run = (name, args) => commands.run(name, args);
h.advance = (ms) => { clock.advance(ms); return scheduler.runDue(); };
h.advanceTo = (t) => { clock.set(t); return scheduler.runDue(); };
h.ctx = () => ({ db, clock, now: clock.now(), scheduler, enqueue: (e) => scheduler.enqueue(e), notify: (u, w, t, p) => scheduler.notify(u, w, t, p) });
return h;
}
// First free land tile at or near (x, y), scanning rightwards.
function landNear(h, x, y) {
for (let i = 0; i < 400; i++) {
const xx = x + i;
if (R.tileAt(h.world.seed, h.world.map_radius, xx, y).type === 'land' && !h.db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', h.worldId, xx, y)) return { x: xx, y };
}
throw new Error('no land near ' + x + ',' + y);
}
// An operator with one capital POP at the first land tile from (x, y). Buildings: the starting POP plus `infra` levels,
// strong power, lots of resources. Beginner protection off unless `protectedUntil`.
function addOperator(h, name, o) {
o = o || {};
const { x, y } = landNear(h, o.x === undefined ? 5 : o.x, o.y === undefined ? 0 : o.y);
const now = h.clock.now();
const u = h.db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', name, 'x', now);
const userId = Number(u.lastInsertRowid);
const op = h.db.run('INSERT INTO operators (world_id, user_id, name, as_number, protection_until, created_at) VALUES (?, ?, ?, ?, ?, ?)', h.worldId, userId, name, D.AS_RANGE.min + (h.asn = (h.asn || 0) + 1), o.protectedUntil || 0, now);
const opId = Number(op.lastInsertRowid);
const townId = createTown(h.db, { worldId: h.worldId, ownerId: opId, name: name + ' POP 1', x, y, isCapital: true, now });
setBuildings(h, townId, Object.assign({ core_router: 10, rack_hall: 10, battery_bank: 10, noc: 5, ops_lab: 5, research_lab: 8, rollout_depot: 5, internet_exchange: 3, firewall: 0 }, o.infra || {}));
for (const k of ['f13', 'f14', 'f15', 'f16']) h.db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', o.power === undefined ? 10 : o.power, townId, k);
const big = o.res || 4000;
h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ? WHERE id = ?', big, big, big, o.battery === undefined ? 1000 : o.battery, o.footprint || 0, townId);
if (o.units) giveUnits(h, townId, o.units);
return { name, userId, opId, townId, x, y };
}
// Another POP for an existing operator.
function addTown(h, op, o) {
o = o || {};
const { x, y } = landNear(h, o.x === undefined ? op.x + 2 : o.x, o.y === undefined ? op.y + 1 : o.y);
const id = createTown(h.db, { worldId: h.worldId, ownerId: op.opId, name: op.name + ' POP ' + (o.n || 2), x, y, isCapital: false, now: h.clock.now() });
setBuildings(h, id, Object.assign({ core_router: 3, rack_hall: 3, battery_bank: 3 }, o.infra || {}));
h.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000, battery = 100 WHERE id = ?', id);
return { townId: id, x, y };
}
function setBuildings(h, townId, levels) {
for (const type of Object.keys(levels)) {
if (h.db.get('SELECT 1 AS x FROM buildings WHERE town_id = ? AND key = ?', townId, type)) h.db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', levels[type], townId, type);
else h.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', townId, type, type, levels[type]);
}
}
function giveUnits(h, townId, units) {
for (const k of Object.keys(units)) {
const cur = h.db.get('SELECT count FROM town_units WHERE town_id = ? AND unit = ?', townId, k);
h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, k, (cur ? cur.count : 0) + units[k]);
}
}
const units = (h, townId) => { const o = {}; for (const r of h.db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) o[r.unit] = r.count; return o; };
const town = (h, id) => h.db.get('SELECT * FROM towns WHERE id = ?', id);
const reportsOf = (h, userId) => h.db.all('SELECT r.id, r.type, r.created_at, r.data, r.summary, rr.role FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? ORDER BY r.id', userId)
.map((r) => Object.assign({}, r, { data: JSON.parse(r.data), summary: JSON.parse(r.summary) }));
const notes = (h, userId, type) => h.db.all('SELECT type, payload FROM notifications WHERE user_id = ? AND type = ? ORDER BY id', userId, type).map((r) => JSON.parse(r.payload));
// All state a battle could touch, as one comparable value (determinism tests).
function snapshot(h) {
const q = (sql) => h.db.all(sql).map((r) => JSON.stringify(r));
return JSON.stringify([
q('SELECT id, owner_id, loyalty, round(fiber, 4) AS fiber, round(hardware, 4) AS hardware, round(capital, 4) AS capital FROM towns ORDER BY id'),
q('SELECT * FROM town_units ORDER BY town_id, unit'), q('SELECT * FROM stationed ORDER BY host_town_id, owner_town_id, unit'),
q('SELECT id, type, status, units, cargo, arrive_at FROM movements ORDER BY id'),
q('SELECT id, type, data FROM reports ORDER BY id'), q('SELECT * FROM operator_stats ORDER BY operator_id'),
q('SELECT id, due_at, type, status FROM events ORDER BY id'),
]);
}
module.exports = { setup, addOperator, addTown, setBuildings, giveUnits, units, town, reportsOf, notes, landNear, snapshot, H, R, D, crypto };

182
test/military-moves.test.js Normal file
View file

@ -0,0 +1,182 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D, H } = T;
test('transport: capacity and links come from the Internet exchange; cargo arrives, carriers drive back, hooks fire', () => {
const h = T.setup();
const a = T.addOperator(h, 'sender', { x: 5, y: 0, infra: { internet_exchange: 2 } });
const b = T.addOperator(h, 'receiver', { x: 9, y: 0 });
h.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000 WHERE id = ?', b.townId);
const M = require('../server/military/movements');
const seen = [];
M.hooks.transportArrived.push((ctx, mv, r) => seen.push({ id: mv.id, added: r.added, extra: mv.extra }));
const send = (cargo) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo });
assert.throws(() => send({ fiber: 600 }), (e) => e.code === 'capacity_exceeded');
assert.throws(() => send({ fiber: 0 }), (e) => e.code === 'validation_failed');
assert.throws(() => send({ fiber: 5000 }), (e) => e.code === 'capacity_exceeded');
const noIx = T.addOperator(h, 'no-ix', { x: 12, y: 0, infra: { internet_exchange: 0 } });
assert.throws(() => h.run('sendTransport', { userId: noIx.userId, fromTownId: noIx.townId, toTownId: b.townId, cargo: { fiber: 10 } }), (e) => e.code === 'no_transport_link');
const before = T.town(h, a.townId).fiber;
const t1 = send({ fiber: 300, capital: 200 });
const t2 = send({ hardware: 100 });
assert.throws(() => send({ hardware: 10 }), (e) => e.code === 'no_transport_link', 'two links, both busy');
assert.ok(Math.abs(T.town(h, a.townId).fiber - (before - 300)) < 1, 'cargo left the POP at once');
assert.equal(t1.arriveAt - t1.departAt, R.transportMs(4, 1));
const rb = T.town(h, b.townId).fiber;
h.advanceTo(t1.arriveAt);
assert.ok(T.town(h, b.townId).fiber >= rb + 300 - 1, 'delivered');
assert.equal(seen.length, 2, 'the arrival hook fired for both transports (same distance, same time)');
assert.deepEqual(seen[0].added, { fiber: 300, capital: 200 });
assert.equal(T.notes(h, b.userId, 'transport_arrived').length, 2);
// the link is busy until the carriers are home, then free again
assert.throws(() => send({ hardware: 10 }), (e) => e.code === 'no_transport_link');
h.advance(10 * H);
assert.doesNotThrow(() => send({ hardware: 10 }));
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
});
test('transport above the Rack hall cap is lost; transports are recallable only in the first 90 s', () => {
const h = T.setup();
const a = T.addOperator(h, 'a', { x: 5, y: 0, infra: { internet_exchange: 3 } });
const b = T.addOperator(h, 'b', { x: 30, y: 0 });
const cap = R.storageCap(require('../server/state').loadTown(h.db, b.townId));
h.db.run('UPDATE towns SET fiber = ?, hardware = 0, capital = 0 WHERE id = ?', cap - 100, b.townId);
const t = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: 400 } });
h.advanceTo(t.arriveAt);
assert.ok(Math.abs(T.town(h, b.townId).fiber - cap) < 1e-6 + 60, 'capped at the Rack hall');
assert.equal(T.notes(h, b.userId, 'transport_arrived')[0].cargoLost.fiber > 0, true);
const c = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { capital: 250 } });
const capBefore = T.town(h, a.townId).capital;
h.advance(60 * 1000);
const rc = h.run('recallMovement', { userId: a.userId, movementId: c.movementId });
assert.ok(rc.arriveAt <= h.clock.now() + 61 * 1000 + 1000);
assert.equal(h.db.get('SELECT status FROM movements WHERE id = ?', c.movementId).status, 'recalled');
h.advanceTo(rc.arriveAt);
assert.ok(T.town(h, a.townId).capital > capBefore + 200, 'the cargo is back home');
// too late
const d = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { capital: 50 } });
h.advance(91 * 1000);
assert.throws(() => h.run('recallMovement', { userId: a.userId, movementId: d.movementId }), (e) => e.code === 'recall_expired');
// others cannot recall your movements
const e2 = h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { capital: 10 } });
assert.throws(() => h.run('recallMovement', { userId: b.userId, movementId: e2.movementId }), (e) => e.code === 'not_found');
});
test('recall: a recalled raid never fights and its units come home after as long as they were out', () => {
const h = T.setup();
const a = T.addOperator(h, 'a', { x: 5, y: 0, units: { script_crew: 20 } });
const d = T.addOperator(h, 'd', { x: 12, y: 0, units: { soc_analyst: 2 } });
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { script_crew: 20 } });
h.advance(30 * 1000);
const r = h.run('recallMovement', { userId: a.userId, movementId: s.movementId });
assert.equal(r.arriveAt, h.clock.now() + 30 * 1000);
assert.equal(h.mq.movements(d.userId, {}).incoming.length, 0, 'the warning disappears');
h.advance(2 * H);
assert.equal(T.units(h, a.townId).script_crew, 20);
assert.equal(T.reportsOf(h, d.userId).length, 0);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
});
test('research: levels need a Research lab, take time, cost resources, and raise unit strength by 5% per level', () => {
const h = T.setup();
const a = T.addOperator(h, 'scholar', { infra: { research_lab: 3, ops_lab: 3 } });
const r1 = h.run('research', { userId: a.userId, townId: a.townId, unit: 'script_crew', stat: 'attack' });
assert.equal(r1.toLevel, 1);
assert.throws(() => h.run('research', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', stat: 'defence' }), (e) => e.code === 'queue_full', 'one research at a time per POP');
h.advanceTo(r1.dueAt);
assert.equal(h.db.get('SELECT level FROM town_research WHERE town_id = ?', a.townId).level, 1);
assert.equal(T.notes(h, a.userId, 'research_done').length, 1);
// level 2 needs lab 4
assert.throws(() => h.run('research', { userId: a.userId, townId: a.townId, unit: 'script_crew', stat: 'attack' }), (e) => e.code === 'requirements_not_met');
T.setBuildings(h, a.townId, { research_lab: 8 });
const r2 = h.run('research', { userId: a.userId, townId: a.townId, unit: 'script_crew', stat: 'attack' });
h.advanceTo(r2.dueAt);
assert.equal(h.db.get('SELECT level FROM town_research WHERE town_id = ?', a.townId).level, 2);
assert.throws(() => h.run('research', { userId: a.userId, townId: a.townId, unit: 'port_scanner', stat: 'attack' }), (e) => e.code === 'not_researchable');
assert.equal(R.unitStat('script_crew', 'attack', { 'script_crew:attack': 2 }), 40 * 1.1);
// research is applied in combat: the snapshot taken at departure is what the attack uses
T.giveUnits(h, a.townId, { script_crew: 10 });
const d = T.addOperator(h, 'd', { x: 12, y: 0 });
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { script_crew: 10 } });
h.advanceTo(s.arriveAt);
assert.ok(Math.abs(T.reportsOf(h, a.userId).find((r) => r.type === 'raid').data.power.attack - 10 * 40 * 1.1) < 1e-9);
});
test('movement list: own outgoing movements are detailed, foreign incoming ones hide type, units and cargo', () => {
const h = T.setup();
const a = T.addOperator(h, 'a', { x: 5, y: 0, units: { script_crew: 10, port_scanner: 2 }, infra: { internet_exchange: 1 } });
const d = T.addOperator(h, 'd', { x: 9, y: 0 });
h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', toTownId: d.townId, units: { script_crew: 10 } });
h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', toTownId: d.townId, units: { port_scanner: 2 } });
h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: d.townId, cargo: { fiber: 10 } });
const mine = h.mq.movements(a.userId, {});
assert.deepEqual(mine.outgoing.map((m) => m.type).sort(), ['attack', 'scan', 'transport']);
assert.ok(mine.outgoing.every((m) => m.recallableUntil !== null));
const theirs = h.mq.movements(d.userId, {});
assert.equal(theirs.incoming.length, 3);
for (const m of theirs.incoming) {
assert.equal(m.type, 'unknown'); assert.equal(m.units, undefined); assert.equal(m.cargo, undefined);
assert.equal(m.from.townId, a.townId); assert.equal(m.from.owner.name, 'a');
}
// and the town view carries the same warnings
assert.equal(h.queries.town(d.userId, d.townId).town.military.movements.incoming.length, 3);
// someone else cannot look at your POP
assert.throws(() => h.queries.town(d.userId, a.townId), (e) => e.code === 'not_found');
});
test('tile info: public facts, distances, settle verdict', () => {
const h = T.setup();
const a = T.addOperator(h, 'a', { x: 5, y: 0 });
const d = T.addOperator(h, 'd', { x: 9, y: 0, protectedUntil: h.clock.now() + H });
const info = h.mq.tileInfo(a.userId, { x: d.x, y: d.y });
assert.equal(info.type, 'pop'); assert.equal(info.town.owner.protected, true); assert.equal(info.town.mine, false);
assert.ok(Math.abs(info.distances[0].distance - 4) < 1e-9);
const land = T.landNear(h, 8, 3);
const li = h.mq.tileInfo(a.userId, { x: land.x, y: land.y });
assert.equal(li.type, 'land'); assert.equal(li.settle.possible, false); assert.equal(li.settle.code, 'footprint_too_low');
assert.equal(li.settle.footprintNeeded, R.footprintNeeded(1));
assert.throws(() => h.mq.tileInfo(a.userId, { x: 999, y: 0 }), (e) => e.code === 'not_found');
});
test('reports: cursor pages newest first, read flags, 14 day retention cleanup', () => {
const h = T.setup();
const a = T.addOperator(h, 'a', { x: 5, y: 0, units: { port_scanner: 30 } });
const d = T.addOperator(h, 'd', { x: 9, y: 0 });
for (let i = 0; i < 3; i++) {
h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', toTownId: d.townId, units: { port_scanner: 5 } });
h.advance(2 * H);
}
const p1 = h.mq.reports(a.userId, { limit: 2 });
assert.equal(p1.items.length, 2); assert.ok(p1.items[0].id > p1.items[1].id);
assert.equal(p1.unread, 3);
const p2 = h.mq.reports(a.userId, { limit: 2, after: p1.next });
assert.equal(p2.items.length, 1); assert.equal(p2.next, null);
h.run('markReportRead', { userId: a.userId, reportId: p1.items[0].id });
assert.equal(h.mq.reports(a.userId, {}).unread, 2);
assert.equal(h.mq.report(a.userId, p1.items[0].id).report.read, true);
assert.throws(() => h.mq.report(d.userId, p1.items[0].id), (e) => e.code === 'not_found', 'the scanner owner only: the defender has his own scan_detected report');
h.run('markReportRead', { userId: a.userId, all: true });
assert.equal(h.mq.reports(a.userId, { unread: true }).items.length, 0);
// retention
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM reports').n, 6);
h.advance(15 * 24 * H);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM reports').n, 0, 'expired reports are gone');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'reportCleanup' AND status = 'pending'").n, 0, 'no cleanup pending without reports');
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM report_recipients').n, 0);
});
test('moving units between your own POPs makes them live there (no "stationed" bookkeeping)', () => {
const h = T.setup();
const a = T.addOperator(h, 'mover', { x: 5, y: 0, units: { soc_analyst: 10 } });
const second = T.addTown(h, a, { x: 8, y: 1 });
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: second.townId, units: { soc_analyst: 6 } });
h.advanceTo(s.arriveAt);
assert.deepEqual(T.units(h, second.townId), { soc_analyst: 6 });
assert.deepEqual(T.units(h, a.townId), { soc_analyst: 4 });
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM stationed').n, 0);
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: a.townId, units: { soc_analyst: 1 } }), (e) => e.code === 'invalid_target');
});

151
test/military-power.test.js Normal file
View file

@ -0,0 +1,151 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const T = require('./military-helpers');
const P = require('../server/military/power');
const { loadTown } = require('../server/state');
const { R, D, H } = T;
// A POP whose units draw more than it produces, with a small battery: units must go offline when the battery is empty.
function strainedTown(h, name, o) {
const op = T.addOperator(h, name, Object.assign({ power: 5, battery: 40, infra: { battery_bank: 1 } }, o));
T.giveUnits(h, op.townId, { script_crew: 40, soc_analyst: 10 });
P.reschedule(h.ctx(), op.townId, h.clock.now());
return op;
}
test('power: the battery empties, units go offline (cannot move, do not defend), then the expensive ones are decommissioned', () => {
const h = T.setup();
const a = strainedTown(h, 'strained', { x: 5, y: 0 });
const t0 = loadTown(h.db, a.townId);
const net = R.ratesPerHour(t0).powerNet;
assert.ok(net < 0, 'net power is negative with 50 units');
const emptyAt = R.batteryEmptyAt(t0, h.clock.now());
assert.ok(emptyAt > h.clock.now());
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'powerCheck' AND status = 'pending'").n, 1, 'exactly one pending check');
// before the battery is empty: units online and can move
h.advanceTo(emptyAt - 60000);
assert.ok(P.online(loadTown(h.db, a.townId), h.clock.now()));
assert.equal(h.queries.town(a.userId, a.townId).town.power.online, true);
// after: offline
h.advanceTo(emptyAt + 5000);
const offline = h.db.get('SELECT offline_since FROM town_power WHERE town_id = ?', a.townId);
assert.ok(offline && offline.offline_since >= emptyAt, 'offline since the battery ran dry');
assert.equal(T.notes(h, a.userId, 'units_offline').length, 1);
assert.equal(h.queries.town(a.userId, a.townId).town.power.online, false);
const target = T.addOperator(h, 'target', { x: 9, y: 0 });
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: target.townId, units: { script_crew: 10 } }), (e) => e.code === 'units_offline');
// offline units do not defend: a small raid against the strained POP loots it although it "has" 50 units
const raider = T.addOperator(h, 'raider', { x: 3, y: 2, units: { script_crew: 15 } });
const s = h.run('sendMovement', { userId: raider.userId, fromTownId: raider.townId, type: 'raid', toTownId: a.townId, units: { script_crew: 15 } });
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, raider.userId).find((r) => r.type === 'raid').data;
assert.equal(rep.defender.online, false);
assert.equal(rep.outcome, 'attacker_won');
assert.equal(rep.power.defenceRaw, 0);
assert.deepEqual(T.units(h, a.townId), { script_crew: 40, soc_analyst: 10 }, 'offline units are not hurt by a raid');
// 24 h offline: decommission, most expensive first, until the draw fits again
const since = h.db.get('SELECT offline_since FROM town_power WHERE town_id = ?', a.townId).offline_since;
h.advanceTo(since + R.decommissionMs(1) - 1000);
assert.deepEqual(T.units(h, a.townId), { script_crew: 40, soc_analyst: 10 }, 'nothing before the 24 hours are up');
h.advanceTo(since + R.decommissionMs(1) + 1000);
const left = T.units(h, a.townId);
assert.ok(left.script_crew < 40 || left.soc_analyst < 10, 'units were decommissioned');
const t1 = loadTown(h.db, a.townId);
assert.ok(R.ratesPerHour(t1).powerNet >= 0, 'the draw fits the output now');
assert.ok(P.online(t1, h.clock.now()), 'online again');
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM town_power WHERE town_id = ?', a.townId).n, 0);
assert.equal(T.notes(h, a.userId, 'units_decommissioned').length, 1);
const unit = (id) => D.UNITS[id];
// script_crew (cost 150) is more expensive than soc_analyst (90): the crews go first
assert.ok(unit('script_crew').cost.fiber + unit('script_crew').cost.hardware + unit('script_crew').cost.capital > unit('soc_analyst').cost.fiber + unit('soc_analyst').cost.hardware + unit('soc_analyst').cost.capital);
assert.equal(left.soc_analyst, 10, 'the cheaper defenders survive');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
});
test('power: building more substations before the battery is empty re-arms the check (no offline)', () => {
const h = T.setup();
const a = strainedTown(h, 'saver', { x: 5, y: 0 });
const emptyAt = R.batteryEmptyAt(loadTown(h.db, a.townId), h.clock.now());
// more output: the reschedule moves the check, units never go offline
h.db.run("UPDATE buildings SET level = 12 WHERE town_id = ? AND key IN ('f13','f14','f15','f16')", a.townId);
P.reschedule(h.ctx(), a.townId, h.clock.now());
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'powerCheck' AND status = 'pending'").n, 0, 'net power is positive: no check needed');
h.advanceTo(emptyAt + 10 * H);
assert.equal(T.notes(h, a.userId, 'units_offline').length, 0);
assert.ok(P.online(loadTown(h.db, a.townId), h.clock.now()));
});
test('power: reinforcements draw from the host, and leaving units stops the draw at the origin', () => {
const h = T.setup();
const a = T.addOperator(h, 'ally-a', { x: 5, y: 0, units: { soc_analyst: 20 } });
const b = T.addOperator(h, 'ally-b', { x: 8, y: 0 });
const t = (id) => loadTown(h.db, id).unitDraw;
assert.equal(t(a.townId), 20);
// not allied: refused
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: b.townId, units: { soc_analyst: 5 } }), (e) => e.code === 'invalid_target');
// allies via the social tables
h.db.run("INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, 'N', 'NN', 10, ?, ?)", h.worldId, a.opId, h.clock.now());
const aid = h.db.get('SELECT id FROM alliances').id;
for (const op of [a, b]) h.db.run('UPDATE operators SET alliance_id = ? WHERE id = ?', aid, op.opId);
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', toTownId: b.townId, units: { soc_analyst: 12 } });
assert.equal(t(a.townId), 8, 'units in transit draw nothing');
h.advanceTo(s.arriveAt);
assert.equal(t(b.townId), 12, 'the host pays for the reinforcements');
assert.equal(t(a.townId), 8);
const view = h.queries.town(b.userId, b.townId).town.military.units;
assert.equal(view.stationedHere.length, 1);
assert.deepEqual(view.stationedHere[0].units, { soc_analyst: 12 });
assert.equal(h.queries.town(a.userId, a.townId).town.military.units.stationedAway[0].hostTownId, b.townId);
// the reinforcement defends the host
const raider = T.addOperator(h, 'raider', { x: 12, y: 0, units: { script_crew: 20 } });
const rs = h.run('sendMovement', { userId: raider.userId, fromTownId: raider.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 } });
h.advanceTo(rs.arriveAt);
const rep = T.reportsOf(h, raider.userId).find((r) => r.type === 'raid');
assert.equal(rep.data.defender.groups[0].sent.soc_analyst, 12);
assert.ok(T.reportsOf(h, a.userId).some((r) => r.role === 'reinforcer'), 'the reinforcing owner gets the report');
// the host sends them home: draw moves back after they arrive
const w = h.run('withdrawStationed', { userId: b.userId, hostTownId: b.townId, ownerTownId: a.townId });
assert.equal(t(b.townId), 0);
h.advanceTo(w.arriveAt);
assert.equal(T.units(h, a.townId).soc_analyst > 8, true);
});
test('restart: overdue events are caught up in order after reopening the same database file', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-mil-'));
const file = path.join(dir, 'game.db');
const h1 = T.setup({ file });
const clock = h1.clock;
const a = T.addOperator(h1, 'raider', { x: 5, y: 0, units: { script_crew: 60, botnet: 10 } });
const d = T.addOperator(h1, 'victim', { x: 20, y: 0, units: { soc_analyst: 5 } });
const slow = h1.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { script_crew: 60 } });
const fast = h1.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', toTownId: d.townId, units: { botnet: 10 } });
h1.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 3 });
assert.ok(fast.arriveAt < slow.arriveAt);
h1.db.close(); // "the server is down"
clock.advance(100 * H); // ... for a long time
const h2 = T.setup({ file, clock });
const n = h2.scheduler.catchUp();
assert.ok(n >= 5, 'arrivals, returns and the training batch were all overdue: ' + n);
const reps = h2.db.all("SELECT id, type, data FROM reports WHERE type = 'raid' ORDER BY id").map((r) => JSON.parse(r.data));
assert.equal(reps.length, 2);
assert.ok(reps[0].arrivedAt === fast.arriveAt && reps[1].arrivedAt === slow.arriveAt, 'reports follow event order, not creation order');
assert.equal(h2.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending' AND due_at <= ?", clock.now()).n, 0);
assert.equal(h2.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
const home = T.units(h2, a.townId);
assert.ok(home.script_crew > 0 && home.botnet > 0, 'everyone came home');
assert.equal(home.soc_analyst, 3, 'the training batch finished during the downtime');
// resources: the first (fast) raid saw the victim's stock at ITS time, not at catch-up time
assert.equal(reps[0].defender.groups[0].sent.soc_analyst, 5);
h2.db.close();
fs.rmSync(dir, { recursive: true, force: true });
});

159
test/military-rules.test.js Normal file
View file

@ -0,0 +1,159 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const H = D.HOUR_MS;
const close = (a, b, eps) => Math.abs(a - b) <= (eps || 1e-9);
test('units: data is complete and consistent', () => {
assert.equal(D.UNIT_ORDER.length, Object.keys(D.UNITS).length);
for (const [id, u] of Object.entries(D.UNITS)) {
assert.ok(D.BUILDINGS[u.building], id + ' has a training building');
for (const r of u.requires) assert.ok(D.BUILDINGS[r.type], id + ' requires a real building');
assert.ok(u.draw >= 0 && u.speed >= 0 && u.time > 0, id);
for (const res of D.RESOURCES) assert.ok(u.cost[res] > 0, id + ' costs ' + res);
}
assert.equal(D.UNITS.honeypot.fixed, true);
assert.equal(D.UNITS.honeypot.speed, 0);
});
test('training and research: costs, times, requirements', () => {
assert.deepEqual(R.unitCost('script_crew', 10), { fiber: 800, hardware: 400, capital: 300 });
// building level and world speed shorten training
assert.equal(R.trainTimeMs('script_crew', 1, 0, 1), 180000);
assert.equal(R.trainTimeMs('script_crew', 1, 10, 1), Math.round(180000 / 1.3));
assert.equal(R.trainTimeMs('script_crew', 10, 0, 2), 900000);
const town = { speed: 1, updatedAt: 0, res: { fiber: 1000, hardware: 1000, capital: 1000, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { ops_lab: { type: 'ops_lab', level: 1 } } };
assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 0).ok, true);
assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 0).dueAt, R.trainTimeMs('script_crew', 5, 1, 1));
assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 99999).startAt, 99999, 'queued behind the tail');
assert.equal(R.trainPlan(town, 'botnet', 1, 0, 0).code, 'requirements_not_met');
assert.deepEqual(R.unitMissing(town, 'botnet').map((m) => m.type).sort(), ['ops_lab', 'research_lab']);
assert.equal(R.trainPlan(town, 'script_crew', 500, 0, 0).code, 'not_enough_resources');
assert.equal(R.trainPlan(town, 'script_crew', 0, 0, 0).code, 'validation_failed');
assert.equal(R.trainPlan(town, 'nope', 1, 0, 0).code, 'unknown_unit');
// research
const t2 = Object.assign({}, town, { buildings: { ops_lab: { type: 'ops_lab', level: 1 }, research_lab: { type: 'research_lab', level: 3 } } });
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 0, false, 0, 0).ok, true);
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 1, false, 0, 0).code, 'requirements_not_met', 'level 2 needs lab 4');
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 0, true, 0, 0).code, 'queue_full');
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 10, false, 0, 0).code, 'max_level');
assert.equal(R.researchPlan(t2, 'honeypot', 'attack', 0, false, 0, 0).code, 'not_researchable');
assert.equal(R.researchPlan(t2, 'script_crew', 'speed', 0, false, 0, 0).code, 'not_researchable');
assert.ok(R.researchCost('script_crew', 2).fiber > R.researchCost('script_crew', 1).fiber);
assert.ok(R.researchTimeMs('script_crew', 1, 3, 1, 0.1) < R.researchTimeMs('script_crew', 1, 3, 1, 0));
assert.equal(R.researchSpeedBonus(2), 0.2); assert.equal(R.researchSpeedBonus(99), D.INCUMBENT.researchSpeedMax);
});
test('movement rules: slowest unit, latency, unit/role checks', () => {
assert.equal(R.slowestSpeed({ script_crew: 5, botnet: 5 }), 8);
assert.equal(R.slowestSpeed({ script_crew: 0, botnet: 5 }), 14);
assert.equal(R.movementMs(20, { script_crew: 1, ddos_rig: 1 }, 1), Math.round(20 / 5 * H), 'the slowest unit sets the pace');
assert.equal(R.movementMs(20, { script_crew: 1 }, 2), Math.round(20 / 16 * H), 'world speed');
assert.equal(R.movementMs(0.1, { port_scanner: 1 }, 1), 10 * 60 * 1000, 'minimum 10 minutes');
assert.equal(R.checkUnitsForType('raid', { script_crew: 5 }), null);
assert.equal(R.checkUnitsForType('raid', { ddos_rig: 5 }).code, 'validation_failed', 'no siege on raids');
assert.equal(R.checkUnitsForType('attack', { script_crew: 5, ddos_rig: 1, exploit_kit: 1 }), null);
assert.equal(R.checkUnitsForType('scan', { script_crew: 1 }).code, 'validation_failed');
assert.equal(R.checkUnitsForType('attack', { honeypot: 1 }).code, 'validation_failed', 'honeypots never move');
assert.equal(R.checkUnitsForType('attack', {}).code, 'validation_failed');
assert.equal(R.checkUnitsForType('attack', { nope: 1 }).code, 'unknown_unit');
assert.equal(R.checkUnitsForType('settle', { rollout_crew: 3 }), null);
assert.equal(R.checkUnitsForType('settle', { rollout_crew: 4 }).code, 'validation_failed');
assert.equal(R.checkUnitsForType('takeover', { script_crew: 3 }).code, 'validation_failed');
assert.equal(R.checkUnitsForType('takeover', { script_crew: 3, ma_team: 1 }), null);
assert.equal(R.checkUnitsForType('reinforce', { honeypot: 1 }).code, 'validation_failed');
assert.equal(R.isProtected(100, 99), true); assert.equal(R.isProtected(100, 100), false);
});
test('combat: full attack, raid, firewall, rigs, research, ties, empty target', () => {
const att = (units, research) => ({ units, research: research || {} });
// attacker wins a full attack: defender is wiped, attacker loses (D/A)^1.5
let b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 100 }), defenders: [{ id: 'h', units: { soc_analyst: 80 } }], firewall: 0 });
assert.equal(b.A, 4000); assert.equal(b.D, 2010);
assert.equal(b.attackerWins, true);
assert.deepEqual(b.defenders[0].survivors, {});
assert.ok(close(b.attackerLossFraction, Math.pow(2010 / 4000, 1.5)));
assert.equal(b.attacker.lost.script_crew, Math.round(100 * Math.pow(2010 / 4000, 1.5)));
// defender wins: attacker wiped, defender loses (A/D)^1.5
b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 10 }), defenders: [{ id: 'h', units: { blue_team: 10 } }], firewall: 0 });
assert.equal(b.attackerWins, false);
assert.deepEqual(b.attacker.survivors, {});
assert.ok(close(b.defenderLossFraction, Math.pow(400 / 810, 1.5)));
// ties go to the defender
b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 1 }), defenders: [], firewall: 0, staticDefence: 40 });
assert.equal(b.attackerWins, false);
// raid: both lose 0.5 * ratio^1.5
b = R.resolveBattle({ kind: 'raid', attackers: att({ script_crew: 100 }), defenders: [{ id: 'h', units: { soc_analyst: 80 } }], firewall: 0 });
const f = 0.5 * Math.pow(2010 / 4000, 1.5);
assert.ok(close(b.attackerLossFraction, f) && close(b.defenderLossFraction, f));
assert.equal(b.defenders[0].survivors.soc_analyst, 80 - Math.round(80 * f));
// firewall multiplies defence; rigs lower it by one level per 10
const fw = (rigs) => R.resolveBattle({ kind: 'attack', attackers: att(Object.assign({ script_crew: 10 }, rigs ? { ddos_rig: rigs } : {})), defenders: [{ id: 'h', units: { soc_analyst: 10 } }], firewall: 10 });
assert.ok(close(fw(0).D, (250 + 10) * 1.3));
assert.ok(close(fw(20).D, (250 + 10) * 1.24), 'level 10 - 20 rigs / 10 = 8');
assert.equal(fw(20).effectiveFirewall, 8);
assert.equal(R.effectiveFirewall(3, 100), 0, 'never below zero');
// research: +5% per level, per unit type and stat
b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 10 }, { 'script_crew:attack': 4 }), defenders: [{ id: 'h', units: { soc_analyst: 10 }, research: { 'soc_analyst:defence': 2 } }], firewall: 0 });
assert.ok(close(b.A, 400 * 1.2)); assert.ok(close(b.D, 250 * 1.1 + 10));
// empty POP: only the base defence stands
b = R.resolveBattle({ kind: 'raid', attackers: att({ script_crew: 1 }), defenders: [], firewall: 0 });
assert.equal(b.D, 10); assert.equal(b.attackerWins, true); assert.deepEqual(b.attacker.lost, {});
// reinforcements count together with home crews, and the share goes by defence power
b = R.resolveBattle({ kind: 'attack', attackers: att({ botnet: 50 }), defenders: [{ id: 'home', units: { soc_analyst: 10 } }, { id: 'ally', units: { blue_team: 10 } }], firewall: 0 });
assert.ok(close(b.defenceRaw, 250 + 800)); assert.ok(close(b.defenders[1].share, 800 / 1050));
// determinism: the same call gives the same result
assert.deepEqual(R.resolveBattle({ kind: 'raid', attackers: att({ botnet: 7 }), defenders: [{ id: 'h', units: { soc_analyst: 9 } }], firewall: 2 }),
R.resolveBattle({ kind: 'raid', attackers: att({ botnet: 7 }), defenders: [{ id: 'h', units: { soc_analyst: 9 } }], firewall: 2 }));
assert.ok(R.battlePoints({ script_crew: 10 }) > 0);
});
test('loot, cache, siege, loyalty, scan, incumbent, decommission, transport plan', () => {
assert.deepEqual(R.lootSplit(300, { fiber: 1000, hardware: 1000, capital: 1000 }), { fiber: 100, hardware: 100, capital: 100 });
assert.deepEqual(R.lootSplit(300, { fiber: 10, hardware: 1000, capital: 1000 }), { fiber: 10, hardware: 145, capital: 145 }, 'what fiber cannot give is shared');
assert.deepEqual(R.lootSplit(9999, { fiber: 5, hardware: 6, capital: 7 }), { fiber: 5, hardware: 6, capital: 7 }, 'never more than there is');
assert.deepEqual(R.lootSplit(0, { fiber: 5, hardware: 6, capital: 7 }), { fiber: 0, hardware: 0, capital: 0 });
assert.equal(R.carryOf({ script_crew: 10, botnet: 2, soc_analyst: 5 }), 10 * 50 + 2 * 150);
assert.equal(R.cacheFraction(0), 0); assert.ok(close(R.cacheFraction(3), 0.3)); assert.equal(R.cacheFraction(20), 0.5);
assert.equal(R.siegeLevels(4), 0); assert.equal(R.siegeLevels(5), 1); assert.equal(R.siegeLevels(19), 1); assert.equal(R.siegeLevels(45), 2);
assert.equal(R.loyaltyDrop(0), 15); assert.equal(R.loyaltyDrop(0.999999), 30);
for (let i = 0; i < 200; i++) { const d = R.loyaltyDrop(R.rng(i)()); assert.ok(d >= 15 && d <= 30); }
assert.equal(R.takeoverBlock(true, 3), 'capital'); assert.equal(R.takeoverBlock(false, 1), 'last_pop'); assert.equal(R.takeoverBlock(true, 1), 'last_pop'); assert.equal(R.takeoverBlock(false, 2), null);
assert.deepEqual(R.footprintGate(1, 499), { ok: false, need: 500, have: 499 }); assert.equal(R.footprintGate(2, 1741).ok, true); assert.equal(R.footprintGate(2, 1740).ok, false);
// scan: success needs more scanners than the defender; buildings at 2:1; failure loses everything
assert.deepEqual(R.resolveScan(5, 5), { success: false, detail: 'none', identityRevealed: true, lossFraction: 1 });
assert.equal(R.resolveScan(6, 5).detail, 'basic');
assert.equal(R.resolveScan(10, 5).detail, 'full');
assert.equal(R.resolveScan(3, 0).detail, 'full'); assert.equal(R.resolveScan(3, 0).lossFraction, 0);
assert.equal(R.resolveScan(6, 5).identityRevealed, false);
// incumbent: static, grows with age, varies per site, deterministic
assert.equal(R.incumbentDefence(1, 5, 5, 0), R.incumbentDefence(1, 5, 5, 0));
assert.ok(R.incumbentDefence(1, 5, 5, 100) > R.incumbentDefence(1, 5, 5, 0));
assert.notEqual(R.incumbentDefence(1, 5, 5, 0), R.incumbentDefence(1, 6, 5, 0));
// decommission: most expensive first, only as many as needed
assert.deepEqual(R.decommissionPlan({ botnet: 5, script_crew: 10 }, 8), { botnet: 5, script_crew: 2 });
assert.deepEqual(R.decommissionPlan({ botnet: 5, script_crew: 10 }, 100), {});
assert.deepEqual(R.decommissionPlan({ botnet: 5, soc_analyst: 3 }, -5), { botnet: 5, soc_analyst: 3 });
assert.equal(R.decommissionMs(1), 24 * H); assert.equal(R.decommissionMs(4), 6 * H);
// transport plan
const town = { speed: 1, updatedAt: 0, res: { fiber: 400, hardware: 400, capital: 400, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 }, rack_hall: { type: 'rack_hall', level: 5 } } };
assert.equal(R.transportPlan(town, { fiber: 100 }, 0, 0).ok, true);
assert.equal(R.transportPlan(town, { fiber: 100 }, 2, 0).code, 'no_transport_link');
assert.equal(R.transportPlan(town, { fiber: 501 }, 0, 0).code, 'capacity_exceeded');
assert.equal(R.transportPlan(town, { fiber: 450 }, 0, 0).code, 'not_enough_resources');
assert.equal(R.transportPlan(town, { gold: 5 }, 0, 0).code, 'validation_failed');
assert.equal(R.transportPlan(town, {}, 0, 0).code, 'validation_failed');
// settle checks and new-POP helpers
assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).ok, true);
assert.equal(R.settleCheck({ tileType: 'rural', occupied: false, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).code, 'invalid_target');
assert.equal(R.settleCheck({ tileType: 'land', occupied: true, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).code, 'invalid_target');
assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 15.01, ownedCount: 1, footprint: 600 }).code, 'out_of_range');
assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 15, ownedCount: 1, footprint: 400 }).code, 'footprint_too_low');
assert.deepEqual(R.cleanWild(['substation', 'bogus']), ['substation', D.START.wild[1]]);
const nb = R.newTownBuildings(['substation', 'sales_office']);
assert.equal(Object.keys(nb).length, 18); assert.ok(Object.values(nb).every((b) => b.level === 0));
assert.equal(nb.f17.type, 'substation');
});

View file

@ -0,0 +1,310 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const A = require('../server/alliances');
const post = (body) => ({ method: 'POST', body });
async function found(t, u, name, tag) {
const r = await t.api('/alliances', post({ name, tag }), u.token);
assert.equal(r.status, 201, JSON.stringify(r.body));
return r.body.allianceId;
}
// invite + accept
async function join(t, leader, allianceId, u) {
const inv = await t.api('/alliances/' + allianceId + '/invite', post({ operatorId: u.operatorId }), leader.token);
assert.equal(inv.status, 201, JSON.stringify(inv.body));
const r = await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, u.token);
assert.equal(r.status, 200, JSON.stringify(r.body));
}
test('alliances: founding needs a Peering office, names and tags are unique per world', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const noOffice = await t.signup('nooffice');
let r = await t.api('/alliances', post({ name: 'Nope', tag: 'NO' }), noOffice.token);
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'peering_office_required');
const a = await t.signupPeering('ada', 3);
r = await t.api('/alliances', post({ name: 'Fibre Friends', tag: 'FF' }), a.token);
assert.equal(r.status, 201);
assert.equal(r.body.sizeCap, 16, '10 + 2 * 3');
assert.equal(r.body.role, 'leader');
r = await t.api('/alliances', post({ name: 'Other', tag: 'OT' }), a.token);
assert.equal(r.body.error.code, 'already_in_alliance');
const b = await t.signupPeering('bob');
r = await t.api('/alliances', post({ name: 'fibre friends', tag: 'XX' }), b.token);
assert.equal(r.body.error.code, 'alliance_name_taken', 'case-insensitive');
r = await t.api('/alliances', post({ name: 'Different', tag: 'ff' }), b.token);
assert.equal(r.body.error.code, 'alliance_tag_taken');
r = await t.api('/alliances', post({ name: 'Bad<>Name', tag: 'BN' }), b.token);
assert.equal(r.status, 422);
r = await t.api('/alliances', post({ name: 'Fine Name', tag: 'a b' }), b.token);
assert.equal(r.status, 422);
r = await t.api('/alliances', post({ name: 'Zero​width', tag: 'ZW' }), b.token);
assert.equal(r.status, 201, 'invisible characters are stripped, not rejected');
assert.equal(r.body.name, 'Zerowidth');
});
test('alliances: invite, accept, decline, cancel, idempotency and room checks', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const lead = await t.signupPeering('lead', 1);
const m1 = await t.signupPeering('mem1');
const m2 = await t.signupPeering('mem2');
const bare = await t.signup('bare'); // no Peering office
const id = await found(t, lead, 'Core Club', 'CC');
// invite twice: same invite, second call is a no-op (200)
let r = await t.api('/alliances/' + id + '/invite', post({ name: 'MEM1' }), lead.token);
assert.equal(r.status, 201); const inv1 = r.body.inviteId;
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m1.operatorId }), lead.token);
assert.equal(r.status, 200); assert.equal(r.body.inviteId, inv1); assert.equal(r.body.changed, false);
r = await t.api('/alliances/' + id + '/invite', post({}), lead.token);
assert.equal(r.status, 422, 'needs a target');
// the invitee sees it and got a notification
r = await t.api('/alliance-invites', {}, m1.token);
assert.equal(r.body.items.length, 1); assert.equal(r.body.items[0].alliance.tag, 'CC');
r = await t.api('/notifications', {}, m1.token);
assert.ok(r.body.items.some((n) => n.type === 'alliance_invite' && n.payload.inviteId === inv1));
// someone else cannot answer it
r = await t.api('/alliance-invites/' + inv1 + '/accept', { method: 'POST' }, m2.token);
assert.equal(r.status, 404);
r = await t.api('/alliance-invites/' + inv1 + '/accept', { method: 'POST' }, m1.token);
assert.equal(r.status, 200); assert.equal(r.body.changed, true);
r = await t.api('/alliance-invites/' + inv1 + '/accept', { method: 'POST' }, m1.token);
assert.equal(r.status, 200); assert.equal(r.body.changed, false, 'accepting twice is a no-op');
r = await t.api('/alliance-invites/' + inv1 + '/decline', { method: 'POST' }, m1.token);
assert.equal(r.status, 409, 'cannot decline what was accepted');
// a plain member may not invite
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), m1.token);
assert.equal(r.status, 403); assert.equal(r.body.error.details.need, 'invite');
// already in an alliance
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m1.operatorId }), lead.token);
assert.equal(r.body.error.code, 'already_in_alliance');
// decline, then re-invite, then cancel
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), lead.token);
const inv2 = r.body.inviteId;
r = await t.api('/alliance-invites/' + inv2 + '/decline', { method: 'POST' }, m2.token);
assert.equal(r.body.changed, true);
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), lead.token);
const inv3 = r.body.inviteId; assert.notEqual(inv3, inv2);
r = await t.api('/alliances/' + id + '/invites', {}, lead.token);
assert.equal(r.body.items.length, 1);
r = await t.api('/alliances/' + id + '/invites/' + inv3, { method: 'DELETE' }, lead.token);
assert.equal(r.body.changed, true);
r = await t.api('/alliances/' + id + '/invites/' + inv3, { method: 'DELETE' }, lead.token);
assert.equal(r.body.changed, false);
r = await t.api('/alliance-invites/' + inv3 + '/accept', { method: 'POST' }, m2.token);
assert.equal(r.status, 409);
// joining needs a Peering office
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: bare.operatorId }), lead.token);
r = await t.api('/alliance-invites/' + r.body.inviteId + '/accept', { method: 'POST' }, bare.token);
assert.equal(r.body.error.code, 'peering_office_required');
t.setBuilding(bare.townId, 'peering_office', 1);
r = await t.api('/alliances/' + id + '/invites', {}, lead.token);
r = await t.api('/alliance-invites/' + r.body.items[0].id + '/accept', { method: 'POST' }, bare.token);
assert.equal(r.status, 200, JSON.stringify(r.body));
// room: the cap is 10 + 2 * 1 = 12 members; fill it with quick operators
const filler = [];
for (let i = 0; filler.length < 12 - 3; i++) {
const f = t.quickSignup('fill' + i);
t.setBuilding(f.townId, 'peering_office', 1);
filler.push(f);
}
for (const f of filler) t.srv.commands.run('allianceInvite', { userId: lead.userId, allianceId: id, operatorId: f.operatorId });
for (const f of filler) {
const inv = t.srv.db.get("SELECT id FROM alliance_invites WHERE operator_id = ? AND status = 'pending'", f.operatorId);
t.srv.commands.run('allianceInviteAnswer', { userId: f.userId, inviteId: inv.id, accept: true });
}
assert.equal(A.memberCount(t.srv.db, id), 12);
r = await t.api('/alliances/' + id + '/invite', post({ operatorId: m2.operatorId }), lead.token);
assert.equal(r.body.error.code, 'alliance_full');
assert.equal(r.body.error.details.cap, 12);
});
test('alliances: the size cap is stored, only raised, and refreshed from the leader\'s best Peering office', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const lead = await t.signupPeering('lead', 1);
const m = await t.signupPeering('mmm');
const id = await found(t, lead, 'Growers', 'GR');
let r = await t.api('/alliances/' + id, {}, lead.token);
assert.equal(r.body.alliance.sizeCap, 12);
t.setBuilding(lead.townId, 'peering_office', 6);
r = await t.api('/alliances/' + id, {}, lead.token);
assert.equal(r.body.alliance.sizeCap, 22, 'reads show the effective cap');
assert.equal(t.srv.db.get('SELECT size_cap FROM alliances WHERE id = ?', id).size_cap, 12, 'reads do not write');
await t.api('/alliances/' + id + '/invite', post({ operatorId: m.operatorId }), lead.token);
assert.equal(t.srv.db.get('SELECT size_cap FROM alliances WHERE id = ?', id).size_cap, 22, 'a command stores the raise');
t.srv.db.run("UPDATE buildings SET level = 1 WHERE town_id = ? AND type = 'peering_office'", lead.townId);
r = await t.api('/alliances/' + id, {}, lead.token);
assert.equal(r.body.alliance.sizeCap, 22, 'never lowered');
});
test('alliances: roles, kick rules, leader transfer, leaving, notes, members list', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const lead = await t.signupPeering('lead');
const off = await t.signupPeering('off');
const dip = await t.signupPeering('dip');
const mem = await t.signupPeering('mem');
const id = await found(t, lead, 'Roles', 'RL');
for (const u of [off, dip, mem]) await join(t, lead, id, u);
const url = (p) => '/alliances/' + id + p;
// role changes: leader only, never to leader via /role
let r = await t.api(url('/role'), post({ operatorId: off.operatorId, role: 'officer' }), lead.token);
assert.equal(r.body.changed, true);
r = await t.api(url('/role'), post({ operatorId: off.operatorId, role: 'officer' }), lead.token);
assert.equal(r.body.changed, false);
await t.api(url('/role'), post({ operatorId: dip.operatorId, role: 'diplomat' }), lead.token);
r = await t.api(url('/role'), post({ operatorId: mem.operatorId, role: 'leader' }), lead.token);
assert.equal(r.status, 422);
r = await t.api(url('/role'), post({ operatorId: mem.operatorId, role: 'officer' }), off.token);
assert.equal(r.status, 403, 'officers cannot promote');
r = await t.api(url('/role'), post({ operatorId: lead.operatorId, role: 'member' }), lead.token);
assert.equal(r.status, 422, 'the leader cannot demote themselves');
// kick: officer may kick members but not diplomats or the leader
r = await t.api(url('/kick'), post({ operatorId: dip.operatorId }), off.token);
assert.equal(r.status, 403); assert.equal(r.body.error.details.need, 'outrank');
r = await t.api(url('/kick'), post({ operatorId: lead.operatorId }), off.token);
assert.equal(r.status, 403);
r = await t.api(url('/kick'), post({ operatorId: mem.operatorId }), dip.token);
assert.equal(r.status, 403, 'a diplomat has no kick permission');
r = await t.api(url('/kick'), post({ operatorId: mem.operatorId }), off.token);
assert.equal(r.body.changed, true);
r = await t.api(url('/kick'), post({ operatorId: mem.operatorId }), off.token);
assert.equal(r.body.changed, false, 'kicking twice is a no-op');
r = await t.api('/notifications', {}, mem.token);
assert.ok(r.body.items.some((n) => n.type === 'alliance_kicked'));
assert.equal(t.srv.db.get('SELECT alliance_id FROM operators WHERE id = ?', mem.operatorId).alliance_id, null);
// members list, with last online from the token use
t.clock.advance(10 * 60 * 1000);
await t.api('/me', {}, dip.token); // touches dip's token at the new time
r = await t.api(url('/members'), {}, lead.token);
assert.deepEqual(r.body.items.map((m) => m.role), ['leader', 'diplomat', 'officer']);
const d = r.body.items.find((m) => m.name === 'dip');
assert.equal(d.towns, 1); assert.equal(d.lastOnline, t.clock.now());
const o = r.body.items.find((m) => m.name === 'off');
assert.ok(o.lastOnline < t.clock.now(), 'off was not online since');
r = await t.api(url('/members'), {}, mem.token);
assert.equal(r.status, 403, 'non-members cannot list members');
// notes
r = await t.api(url('/notes'), post({ text: 'Rally at 20:00‮' }), mem.token);
assert.equal(r.status, 403);
r = await t.api(url('/notes'), post({ text: 'Rally at 20:00‮' }), off.token);
assert.equal(r.status, 201); assert.equal(r.body.note.text, 'Rally at 20:00');
const nid = r.body.note.id;
r = await t.api(url('/notes/' + nid), post({ text: 'Rally at 21:00' }), dip.token);
assert.equal(r.body.note.text, 'Rally at 21:00');
r = await t.api(url('/notes'), {}, dip.token);
assert.equal(r.body.items.length, 1);
r = await t.api(url('/notes/' + nid), { method: 'DELETE' }, off.token);
assert.equal(r.body.changed, true);
for (let i = 0; i < 10; i++) await t.api(url('/notes'), post({ text: 'n' + i }), lead.token);
r = await t.api(url('/notes'), post({ text: 'one too many' }), lead.token);
assert.equal(r.body.error.code, 'notes_full');
// leader cannot leave while others remain; transfer then leave
r = await t.api(url('/leave'), { method: 'POST' }, lead.token);
assert.equal(r.body.error.code, 'leader_must_transfer');
r = await t.api(url('/transfer'), post({ operatorId: lead.operatorId }), lead.token);
assert.equal(r.status, 422);
r = await t.api(url('/transfer'), post({ operatorId: mem.operatorId }), lead.token);
assert.equal(r.status, 404, 'target must be a member');
r = await t.api(url('/transfer'), post({ operatorId: dip.operatorId }), off.token);
assert.equal(r.status, 403);
r = await t.api(url('/transfer'), post({ operatorId: dip.operatorId }), lead.token);
assert.equal(r.body.changed, true);
assert.equal(A.membership(t.srv.db, dip.operatorId).role, 'leader');
assert.equal(A.membership(t.srv.db, lead.operatorId).role, 'officer');
r = await t.api(url('/leave'), { method: 'POST' }, lead.token);
assert.equal(r.body.changed, true);
r = await t.api(url('/leave'), { method: 'POST' }, lead.token);
assert.equal(r.body.changed, false, 'leaving twice is a no-op');
// disband: leader only; everything goes, names are free again
r = await t.api(url('/disband'), { method: 'POST' }, off.token);
assert.equal(r.status, 403);
r = await t.api(url('/disband'), { method: 'POST' }, dip.token);
assert.equal(r.status, 200);
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliances').n, 0);
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_members').n, 0);
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_notes').n, 0);
assert.equal((await t.api(url(''), {}, dip.token)).status, 404);
r = await t.api('/alliances', post({ name: 'Roles', tag: 'RL' }), off.token);
assert.equal(r.status, 201, 'name and tag are reusable after a disband');
});
test('alliances: a lone leader leaving disbands; alliance shows in /me and /map; directory and profile', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signupPeering('aa1');
const b = await t.signupPeering('bb1');
const idA = await found(t, a, 'Alpha Net', 'ALP');
const idB = await found(t, b, 'Beta Net', 'BET');
let r = await t.api('/me', {}, a.token);
assert.deepEqual(r.body.operators[0].alliance, { id: idA, tag: 'ALP', name: 'Alpha Net' });
const out = await t.api('/map?x=0&y=0&r=40', {}, b.token);
const mine = out.body.towns.find((x) => x.owner.id === a.operatorId);
assert.deepEqual(mine.owner.alliance, { id: idA, tag: 'ALP', name: 'Alpha Net' });
assert.equal(mine.owner.allianceId, idA);
r = await t.api('/alliances', {}, a.token);
assert.deepEqual(r.body.items.map((x) => x.tag), ['ALP', 'BET']);
r = await t.api('/alliances?q=beta', {}, a.token);
assert.deepEqual(r.body.items.map((x) => x.tag), ['BET']);
r = await t.api('/alliances?limit=1', {}, a.token);
assert.equal(r.body.items.length, 1); assert.equal(r.body.next, idA);
r = await t.api('/alliances?limit=1&after=' + r.body.next, {}, a.token);
assert.equal(r.body.items[0].tag, 'BET'); assert.equal(r.body.next, null);
r = await t.api('/alliances/' + idB, {}, a.token);
assert.equal(r.body.alliance.memberCount, 1); assert.equal(r.body.alliance.myRole, null); assert.equal(r.body.alliance.relation, 'neutral');
assert.equal(r.body.alliance.leader.name, 'bb1'); assert.ok(r.body.alliance.footprint >= 0);
r = await t.api('/alliances/mine', {}, a.token);
assert.equal(r.body.role, 'leader'); assert.ok(r.body.permissions.includes('disband')); assert.equal(r.body.peeringLevel, 1);
assert.equal((await t.api('/alliances/abc', {}, a.token)).status, 404);
r = await t.api('/alliances/' + idA + '/leave', { method: 'POST' }, a.token);
assert.equal(r.body.disbanded, true);
r = await t.api('/alliances/mine', {}, a.token);
assert.equal(r.body.alliance, null); assert.equal(r.body.role, null);
r = await t.api('/me', {}, a.token);
assert.equal(r.body.operators[0].alliance, null);
});
test('alliances: lookup helpers for other modules', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signupPeering('hh1'), b = await t.signupPeering('hh2'), c = await t.signupPeering('hh3'), d = await t.signup('hh4');
const idA = await found(t, a, 'Hel A', 'HA');
const idB = await found(t, b, 'Hel B', 'HB');
await join(t, a, idA, c);
const db = t.srv.db;
assert.equal(A.operatorRelation(db, a.operatorId, a.operatorId), 'self');
assert.equal(A.operatorRelation(db, a.operatorId, c.operatorId), 'same_alliance');
assert.equal(A.operatorRelation(db, a.operatorId, b.operatorId), 'neutral');
assert.equal(A.operatorRelation(db, a.operatorId, d.operatorId), 'neutral');
await t.api('/alliances/' + idA + '/diplomacy', post({ targetId: idB, state: 'war' }), a.token);
assert.equal(A.operatorRelation(db, c.operatorId, b.operatorId), 'war');
assert.ok(A.atWar(db, b.operatorId, c.operatorId));
assert.ok(!A.pactPartners(db, a.operatorId, b.operatorId));
assert.ok(A.pactPartners(db, a.operatorId, c.operatorId) && A.confederated(db, a.operatorId, c.operatorId));
assert.equal(A.relationBetween(db, idA, idB), 'war');
assert.equal(A.relationBetween(db, idA, idA), 'neutral');
});

View file

@ -0,0 +1,186 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const A = require('../server/alliances');
const post = (body) => ({ method: 'POST', body });
const H = 3600 * 1000;
// Two alliances (leaders lA, lB), each with a diplomat (dA, dB) and a plain member (mA).
async function setup() {
const t = await createTestServer({ contract: true });
const lA = await t.signupPeering('lead_a'), lB = await t.signupPeering('lead_b');
const dA = await t.signupPeering('dip_a'), dB = await t.signupPeering('dip_b'), mA = await t.signupPeering('mem_a');
const mk = async (lead, name, tag) => (await t.api('/alliances', post({ name, tag }), lead.token)).body.allianceId;
const A1 = await mk(lA, 'Alpha', 'AAA'), B1 = await mk(lB, 'Bravo', 'BBB');
const join = async (lead, id, u, role) => {
const inv = await t.api('/alliances/' + id + '/invite', post({ operatorId: u.operatorId }), lead.token);
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, u.token);
if (role) await t.api('/alliances/' + id + '/role', post({ operatorId: u.operatorId, role }), lead.token);
};
await join(lA, A1, dA, 'diplomat'); await join(lB, B1, dB, 'diplomat'); await join(lA, A1, mA);
return { t, lA, lB, dA, dB, mA, A1, B1 };
}
const rel = (t, id, tok) => t.api('/alliances/' + id + '/diplomacy', {}, tok);
const types = async (t, u) => (await t.api('/notifications', {}, u.token)).body.items.map((n) => n.type);
test('diplomacy: war is declared at once, peace and pacts need the other side to accept', async (t0) => {
const { t, lA, lB, dA, dB, mA, A1, B1 } = await setup();
t0.after(() => t.close());
// permission: members cannot, diplomats can
let r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'war' }), mA.token);
assert.equal(r.status, 403);
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dA.token);
assert.equal(r.status, 422);
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'neutral' }), dA.token);
assert.equal(r.body.error.code, 'diplomacy_invalid', 'already neutral');
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'bogus' }), dA.token);
assert.equal(r.status, 422);
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'war' }), dA.token);
assert.equal(r.status, 200); assert.equal(r.body.result, 'applied');
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'war');
r = await rel(t, B1, lB.token);
assert.equal(r.body.relations[0].state, 'war'); assert.equal(r.body.relations[0].other.tag, 'AAA');
assert.ok((await types(t, dB)).includes('diplomacy_changed'), 'the other side is told');
assert.ok((await types(t, mA)).includes('diplomacy_changed'), 'so are plain members of the declaring side');
// war -> confed is not allowed; war -> neutral is a proposal
r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'confed' }), dB.token);
assert.equal(r.body.error.code, 'diplomacy_invalid');
r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'neutral' }), dB.token);
assert.equal(r.body.result, 'proposed'); const pid = r.body.proposalId;
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'war', 'nothing changes before acceptance');
assert.ok((await types(t, dA)).includes('diplomacy_proposal'));
assert.ok(!(await types(t, mA)).includes('diplomacy_proposal'), 'only leader/diplomats are pinged');
r = await rel(t, A1, dA.token);
assert.equal(r.body.proposalsIn.length, 1); assert.equal(r.body.proposalsIn[0].state, 'neutral');
r = await rel(t, B1, dB.token);
assert.equal(r.body.proposalsOut.length, 1);
// wrong alliance / wrong role cannot answer
r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dB.token);
assert.equal(r.status, 403, 'the proposer cannot accept their own proposal');
r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, mA.token);
assert.equal(r.status, 403);
r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dA.token);
assert.equal(r.body.changed, true);
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'neutral');
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_relations').n, 0, 'neutral keeps no row');
r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dA.token);
assert.equal(r.body.changed, false, 'idempotent');
r = await t.api('/diplomacy/proposals/' + pid + '/decline', { method: 'POST' }, dA.token);
assert.equal(r.status, 409);
// a pact: propose, replace, withdraw, decline, accept
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token);
const p1 = r.body.proposalId;
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'confed' }), dA.token);
const p2 = r.body.proposalId; assert.notEqual(p1, p2);
assert.equal(t.srv.db.get('SELECT status FROM alliance_proposals WHERE id = ?', p1).status, 'withdrawn', 'a new proposal replaces the old one');
r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'confed' }), dB.token);
assert.equal(r.body.error.code, 'proposal_exists');
r = await t.api('/diplomacy/proposals/' + p2, { method: 'DELETE' }, dB.token);
assert.equal(r.status, 403, 'only the proposer may withdraw');
r = await t.api('/diplomacy/proposals/' + p2, { method: 'DELETE' }, dA.token);
assert.equal(r.body.changed, true);
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token);
r = await t.api('/diplomacy/proposals/' + r.body.proposalId + '/decline', { method: 'POST' }, dB.token);
assert.equal(r.body.changed, true);
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token);
r = await t.api('/diplomacy/proposals/' + r.body.proposalId + '/accept', { method: 'POST' }, dB.token);
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'nap');
assert.ok(A.pactPartners(t.srv.db, lA.operatorId, lB.operatorId));
assert.ok(!A.confederated(t.srv.db, lA.operatorId, lB.operatorId));
});
test('diplomacy: cancelling a pact takes 24 h / world speed, can be revoked, and runs through the event queue', async (t0) => {
const { t, lA, lB, dA, dB, A1, B1 } = await setup();
t0.after(() => t.close());
const accept = async (from, fromTok, to, toTok, state) => {
const r = await t.api('/alliances/' + from + '/diplomacy', post({ targetId: to, state }), fromTok);
return t.api('/diplomacy/proposals/' + r.body.proposalId + '/accept', { method: 'POST' }, toTok);
};
await accept(A1, dA.token, B1, dB.token, 'confed');
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed');
assert.ok(A.confederated(t.srv.db, lA.operatorId, lB.operatorId));
const t0ms = t.clock.now();
let r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'neutral' }), dA.token);
assert.equal(r.body.result, 'scheduled'); assert.equal(r.body.effectiveAt, t0ms + 24 * H);
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed', 'the pact still holds while the cancel is pending');
r = await rel(t, B1, dB.token);
assert.equal(r.body.relations[0].pending.to, 'neutral'); assert.equal(r.body.relations[0].pending.byUs, false);
assert.ok((await types(t, lB)).includes('diplomacy_cancel_pending'));
// no further changes while one is pending
r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dB.token);
assert.equal(r.body.error.code, 'diplomacy_pending');
// revoke: only the side that started it
r = await t.api('/alliances/' + B1 + '/diplomacy/' + A1 + '/pending', { method: 'DELETE' }, dB.token);
assert.equal(r.status, 403);
r = await t.api('/alliances/' + A1 + '/diplomacy/' + B1 + '/pending', { method: 'DELETE' }, dA.token);
assert.equal(r.body.changed, true);
r = await t.api('/alliances/' + A1 + '/diplomacy/' + B1 + '/pending', { method: 'DELETE' }, dA.token);
assert.equal(r.body.changed, false);
t.clock.advance(25 * H); t.srv.scheduler.runDue();
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed', 'a revoked cancel never fires');
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'diploChange' AND status = 'cancelled'").n, 1);
// cancel again and let it run: just before the deadline nothing, after it the change applies
r = await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dB.token);
assert.equal(r.body.result, 'scheduled', 'confed -> war is also a delayed move');
t.clock.advance(24 * H - 1000); t.srv.scheduler.runDue();
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'confed');
t.clock.advance(2000); t.srv.scheduler.runDue();
assert.equal(A.relationBetween(t.srv.db, A1, B1), 'war');
r = await rel(t, A1, dA.token);
assert.equal(r.body.relations[0].pending, null);
assert.ok((await types(t, lA)).filter((x) => x === 'diplomacy_changed').length >= 2);
assert.equal(t.srv.db.get("SELECT status FROM events WHERE type = 'diploChange' ORDER BY id DESC LIMIT 1").status, 'done');
});
test('diplomacy: faster worlds shorten the cancel, disbanding clears relations and pending events', async (t0) => {
const t = await createTestServer({ contract: true, server: { world: { speed: 3 } } });
t0.after(() => t.close());
const l1 = await t.signupPeering('lead_one'), l2 = await t.signupPeering('lead_two');
const a = (await t.api('/alliances', post({ name: 'One', tag: 'ONE' }), l1.token)).body.allianceId;
const b = (await t.api('/alliances', post({ name: 'Two', tag: 'TWO' }), l2.token)).body.allianceId;
let r = await t.api('/alliances/' + a + '/diplomacy', post({ targetId: b, state: 'nap' }), l1.token);
await t.api('/diplomacy/proposals/' + r.body.proposalId + '/accept', { method: 'POST' }, l2.token);
const now = t.clock.now();
r = await t.api('/alliances/' + a + '/diplomacy', post({ targetId: b, state: 'neutral' }), l1.token);
assert.equal(r.body.effectiveAt, now + 8 * H, '24 h at 3x');
// disband the other side while the cancel is pending
await t.api('/alliances/' + b + '/disband', { method: 'POST' }, l2.token);
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM alliance_relations').n, 0);
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'diploChange' AND status = 'pending'").n, 0);
t.clock.advance(9 * H); t.srv.scheduler.runDue();
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
r = await t.api('/notifications', {}, l1.token);
assert.ok(r.body.items.some((n) => n.type === 'diplomacy_changed' && n.payload.reason === 'disbanded' && n.payload.to === 'neutral'));
});
test('diplomacy: proposals expire, and a stale proposal is re-validated on accept', async (t0) => {
const { t, dA, dB, A1, B1 } = await setup();
t0.after(() => t.close());
let r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token);
const pid = r.body.proposalId;
t.clock.advance(73 * H);
r = await rel(t, B1, dB.token);
assert.equal(r.body.proposalsIn.length, 0, 'expired proposals are not listed');
r = await t.api('/diplomacy/proposals/' + pid + '/accept', { method: 'POST' }, dB.token);
assert.equal(r.body.error.code, 'proposal_expired');
// pending proposal, then war is declared: the proposal is withdrawn by the state change
r = await t.api('/alliances/' + A1 + '/diplomacy', post({ targetId: B1, state: 'nap' }), dA.token);
const p2 = r.body.proposalId;
await t.api('/alliances/' + B1 + '/diplomacy', post({ targetId: A1, state: 'war' }), dB.token);
assert.equal(t.srv.db.get('SELECT status FROM alliance_proposals WHERE id = ?', p2).status, 'withdrawn');
r = await t.api('/diplomacy/proposals/' + p2 + '/accept', { method: 'POST' }, dB.token);
assert.equal(r.status, 409);
});

View file

@ -0,0 +1,171 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const post = (body) => ({ method: 'POST', body });
const MIN = 60 * 1000;
test('messages: send, inbox/outbox/thread, read, delete own copy', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signup('alice'), b = await t.signup('bobby'), c = await t.signup('carol');
let r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'hi‮ bob​!\u0007' }), a.token);
assert.equal(r.status, 201); assert.equal(r.body.recipients, 1);
const m1 = r.body.messageId;
t.clock.advance(1000);
r = await t.api('/messages', post({ toName: 'ALICE', text: 'hello back' }), b.token);
assert.equal(r.status, 201); const m2 = r.body.messageId;
t.clock.advance(1000);
r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'third' }), c.token);
const m3 = r.body.messageId;
r = await t.api('/messages/inbox', {}, b.token);
assert.deepEqual(r.body.items.map((m) => m.id), [m3, m1], 'newest first');
assert.equal(r.body.unread, 2);
assert.equal(r.body.items[1].text, 'hi bob!', 'control and bidi characters are stripped');
assert.equal(r.body.items[1].from.name, 'alice'); assert.equal(r.body.items[1].direction, 'in');
assert.equal(r.body.items[1].readAt, null);
// cursor: page of one
r = await t.api('/messages/inbox?limit=1', {}, b.token);
assert.equal(r.body.items.length, 1); assert.equal(r.body.next, m3);
r = await t.api('/messages/inbox?limit=1&after=' + r.body.next, {}, b.token);
assert.deepEqual(r.body.items.map((m) => m.id), [m1]); assert.equal(r.body.next, null);
r = await t.api('/messages/outbox', {}, a.token);
assert.deepEqual(r.body.items.map((m) => m.id), [m1]); assert.equal(r.body.items[0].to.name, 'bobby'); assert.equal(r.body.items[0].direction, 'out');
// thread alice <-> bobby, both directions, excludes carol
r = await t.api('/messages/thread/' + b.operatorId, {}, a.token);
assert.deepEqual(r.body.items.map((m) => m.id), [m2, m1]);
assert.deepEqual(r.body.items.map((m) => m.direction), ['in', 'out']);
r = await t.api('/messages/thread/' + a.operatorId, {}, b.token);
assert.deepEqual(r.body.items.map((m) => m.id), [m2, m1]);
// read
r = await t.api('/messages/read', post({ ids: [m1, 99999] }), b.token);
assert.equal(r.body.changed, true); assert.equal(r.body.count, 1);
r = await t.api('/messages/read', post({ ids: [m1] }), b.token);
assert.equal(r.body.changed, false);
r = await t.api('/messages/inbox?unread=true', {}, b.token);
assert.deepEqual(r.body.items.map((m) => m.id), [m3]);
r = await t.api('/messages/read', post({ all: true }), b.token);
assert.equal(r.body.count, 1);
r = await t.api('/messages/inbox', {}, b.token);
assert.equal(r.body.unread, 0); assert.ok(r.body.items.every((m) => m.readAt === t.clock.now()));
r = await t.api('/messages/' + m1, {}, b.token);
assert.equal(r.body.message.text, 'hi bob!');
assert.equal((await t.api('/messages/' + m1, {}, c.token)).status, 404, 'strangers cannot read it');
// delete own copy only
r = await t.api('/messages/' + m1, { method: 'DELETE' }, b.token);
assert.equal(r.body.changed, true);
r = await t.api('/messages/' + m1, { method: 'DELETE' }, b.token);
assert.equal(r.body.changed, false);
assert.equal((await t.api('/messages/' + m1, {}, c.token).then((x) => x.status)), 404);
assert.equal((await t.api('/messages/inbox', {}, b.token)).body.items.some((m) => m.id === m1), false);
assert.equal((await t.api('/messages/outbox', {}, a.token)).body.items.length, 1, 'the sender keeps theirs');
r = await t.api('/messages/' + m1, { method: 'DELETE' }, a.token);
assert.equal(r.body.changed, true);
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM messages WHERE id = ?', m1).n, 0, 'purged when nobody has a copy');
assert.equal((await t.api('/messages/' + m1, { method: 'DELETE' }, a.token)).status, 404);
// notifications for the recipient
r = await t.api('/notifications', {}, b.token);
assert.ok(r.body.items.some((n) => n.type === 'message' && n.payload.from.name === 'alice'));
});
test('messages: validation, self, empty, too long', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signup('alice'), b = await t.signup('bobby');
const send = (body) => t.api('/messages', post(body), a.token);
assert.equal((await send({ text: 'no target' })).status, 422);
assert.equal((await send({ toOperatorId: b.operatorId, toName: 'bobby', text: 'two targets' })).status, 422);
assert.equal((await send({ toOperatorId: a.operatorId, text: 'self' })).status, 422);
assert.equal((await send({ toOperatorId: b.operatorId, text: '' })).status, 422);
assert.equal((await send({ toOperatorId: b.operatorId, text: '‮​ \u0007' })).status, 422, 'nothing left after stripping');
assert.equal((await send({ toOperatorId: b.operatorId, text: 'x'.repeat(2001) })).status, 422);
assert.equal((await send({ toOperatorId: b.operatorId, text: 'x'.repeat(2000) })).status, 201);
assert.equal((await send({ toName: 'nobody', text: 'x' })).status, 404);
assert.equal((await send({ toOperatorId: 999999, text: 'x' })).status, 404);
assert.equal((await send({ toAlliance: true, text: 'x' })).body.error.code, 'not_in_alliance');
assert.equal((await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'x' }))).status, 401);
});
test('messages: per-sender rate limit follows the clock', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signup('alice'), b = await t.signup('bobby');
for (let i = 0; i < 15; i++) {
const r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'm' + i }), a.token);
assert.equal(r.status, 201, 'message ' + i);
}
let r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'one more' }), a.token);
assert.equal(r.status, 429); assert.equal(r.body.error.code, 'rate_limited');
assert.ok(r.body.error.details.retryAfter > 0 && r.body.error.details.retryAfter <= 600);
assert.equal(r.headers.get('retry-after'), String(r.body.error.details.retryAfter));
// bobby is not affected by alice's limit
assert.equal((await t.api('/messages', post({ toOperatorId: a.operatorId, text: 'hey' }), b.token)).status, 201);
t.clock.advance(11 * MIN);
assert.equal((await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'again' }), a.token)).status, 201);
// hourly cap: 60 per hour
for (let i = 0; i < 100; i++) {
t.clock.advance(11 * MIN / 15 * 1); // ~44 s apart: within the 10-minute window never more than 15
r = await t.api('/messages', post({ toOperatorId: b.operatorId, text: 'h' + i }), a.token);
if (r.status === 429) break;
}
assert.equal(r.status, 429);
assert.equal(r.body.error.details.windowMs, 60 * MIN, 'the hourly window is the one that bites');
});
test('messages: alliance broadcast, block list, and the feed', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const lead = await t.signupPeering('leader'), m1 = await t.signupPeering('memb1'), m2 = await t.signupPeering('memb2'), out = await t.signup('outsider');
const id = (await t.api('/alliances', post({ name: 'Chat Club', tag: 'CHAT' }), lead.token)).body.allianceId;
for (const u of [m1, m2]) {
const inv = await t.api('/alliances/' + id + '/invite', post({ operatorId: u.operatorId }), lead.token);
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, u.token);
}
// m2 blocks m1
let r = await t.api('/messages/blocks', post({ operatorId: m1.operatorId }), m2.token);
assert.equal(r.body.changed, true);
r = await t.api('/messages/blocks', post({ operatorId: m1.operatorId }), m2.token);
assert.equal(r.body.changed, false);
r = await t.api('/messages/blocks', {}, m2.token);
assert.deepEqual(r.body.items.map((b) => b.name), ['memb1']);
r = await t.api('/messages', post({ toAlliance: true, text: 'meeting at 8' }), m1.token);
assert.equal(r.status, 201); assert.equal(r.body.kind, 'alliance'); assert.equal(r.body.recipients, 1, 'lead only: m2 blocked the sender');
r = await t.api('/messages', post({ toAlliance: true, text: 'from the lead' }), lead.token);
assert.equal(r.body.recipients, 2);
r = await t.api('/messages/alliance', {}, lead.token);
assert.deepEqual(r.body.items.map((m) => m.text), ['from the lead', 'meeting at 8']);
assert.equal(r.body.items[0].alliance.tag, 'CHAT');
r = await t.api('/messages/alliance', {}, m2.token);
assert.deepEqual(r.body.items.map((m) => m.text), ['from the lead']);
r = await t.api('/messages/alliance', {}, m1.token);
assert.equal(r.body.items.length, 2, 'the sender sees their own broadcast and the lead\'s');
assert.equal((await t.api('/messages/alliance', {}, out.token)).body.error.code, 'not_in_alliance');
assert.equal((await t.api('/messages/inbox', {}, out.token)).body.items.length, 0);
// blocked DMs are accepted silently and never delivered
r = await t.api('/messages', post({ toOperatorId: m2.operatorId, text: 'dm to the blocker' }), m1.token);
assert.equal(r.status, 201); assert.equal(r.body.recipients, 0);
assert.equal((await t.api('/messages/inbox', {}, m2.token)).body.items.filter((m) => m.text === 'dm to the blocker').length, 0);
assert.equal((await t.api('/messages/outbox', {}, m1.token)).body.items[0].text, 'dm to the blocker');
r = await t.api('/messages/blocks/' + m1.operatorId, { method: 'DELETE' }, m2.token);
assert.equal(r.body.changed, true);
r = await t.api('/messages', post({ toOperatorId: m2.operatorId, text: 'now it arrives' }), m1.token);
assert.equal(r.body.recipients, 1);
// the broadcast stays readable after the alliance is gone
await t.api('/alliances/' + id + '/disband', { method: 'POST' }, lead.token);
r = await t.api('/messages/inbox', {}, lead.token);
assert.ok(r.body.items.some((m) => m.text === 'meeting at 8' && m.alliance.tag === 'CHAT'));
});

View file

@ -0,0 +1,76 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const post = (body) => ({ method: 'POST', body });
const DAY = 24 * 3600 * 1000;
test('rankings: operators and alliances by footprint, ties by id, rank-offset cursor', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signupPeering('rank_a'), b = await t.signupPeering('rank_b'), c = await t.signup('rank_c');
const ia = (await t.api('/alliances', post({ name: 'Rank A', tag: 'RA' }), a.token)).body.allianceId;
const ib = (await t.api('/alliances', post({ name: 'Rank B', tag: 'RB' }), b.token)).body.allianceId;
const inv = await t.api('/alliances/' + ia + '/invite', post({ operatorId: c.operatorId }), a.token);
t.setBuilding(c.townId, 'peering_office', 1);
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, c.token);
// all three have the same buildings (+ an office): after a day the footprint is equal; give b a core router bump
t.setBuilding(b.townId, 'core_router', 5);
t.clock.advance(DAY);
let r = await t.api('/rankings/operators', {}, a.token);
assert.equal(r.body.total, 3);
assert.deepEqual(r.body.items.map((x) => x.name), ['rank_b', 'rank_a', 'rank_c'], 'b leads, a and c tie and a has the lower id');
assert.deepEqual(r.body.items.map((x) => x.rank), [1, 2, 3]);
assert.equal(r.body.you.rank, 2);
assert.equal(r.body.items[1].allianceTag, 'RA'); assert.equal(r.body.items[0].towns, 1);
assert.ok(r.body.items[0].footprint > r.body.items[1].footprint && r.body.items[1].footprint > 0);
// the number is the rules' footprintAt over the town
const R = require('../public/js/rules.js');
const { loadTown } = require('../server/state');
const fpB = R.footprintAt(loadTown(t.srv.db, b.townId), t.clock.now());
assert.ok(Math.abs(r.body.items[0].footprint - fpB) < 0.01, r.body.items[0].footprint + ' vs ' + fpB);
r = await t.api('/rankings/operators?limit=2', {}, a.token);
assert.equal(r.body.items.length, 2); assert.equal(r.body.next, 2);
r = await t.api('/rankings/operators?limit=2&after=2', {}, a.token);
assert.deepEqual(r.body.items.map((x) => x.rank), [3]); assert.equal(r.body.next, null);
r = await t.api('/rankings/alliances', {}, a.token);
assert.deepEqual(r.body.items.map((x) => x.tag), ['RA', 'RB'], 'two members beat one stronger member');
assert.equal(r.body.items[0].members, 2); assert.equal(r.body.items[0].towns, 2);
assert.equal(r.body.you.rank, 1);
const sumA = r.body.items[0].footprint;
const ops = (await t.api('/rankings/operators', {}, a.token)).body.items;
const expect = ops.filter((x) => x.allianceTag === 'RA').reduce((s, x) => s + x.footprint, 0);
assert.ok(Math.abs(sumA - expect) < 0.02);
assert.ok(ib);
r = await t.api('/rankings/alliances', {}, c.token);
assert.equal(r.body.you.tag, 'RA');
});
test('rankings: battles read operator_stats when the military stage created it', async (t0) => {
const t = await createTestServer({ contract: true });
t0.after(() => t.close());
const a = await t.signup('war_a'), b = await t.signup('war_b'), c = await t.signup('war_c');
const hasTable = !!t.srv.db.get("SELECT 1 AS x FROM sqlite_master WHERE name = 'operator_stats'");
let r = await t.api('/rankings/battles', {}, a.token);
assert.equal(r.status, 200);
if (!hasTable) {
assert.equal(r.body.available, false); assert.deepEqual(r.body.items, []);
return;
}
assert.equal(r.body.available, true); assert.deepEqual(r.body.items, [], 'nobody has points yet');
t.srv.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, ?, ?)', a.operatorId, 50, 5);
t.srv.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, ?, ?)', b.operatorId, 10, 90);
r = await t.api('/rankings/battles', {}, c.token);
assert.deepEqual(r.body.items.map((x) => x.name), ['war_a', 'war_b']);
assert.equal(r.body.by, 'attack');
r = await t.api('/rankings/battles?by=defense', {}, c.token);
assert.deepEqual(r.body.items.map((x) => x.name), ['war_b', 'war_a']);
r = await t.api('/rankings/battles?by=total', {}, a.token);
assert.deepEqual(r.body.items.map((x) => x.name), ['war_b', 'war_a']); assert.equal(r.body.you.name, 'war_a');
assert.equal((await t.api('/rankings/battles?by=bogus', {}, a.token)).status, 422);
});

54
test/social-rules.test.js Normal file
View file

@ -0,0 +1,54 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { cleanText } = require('../server/text');
test('rules: alliance size cap is 10 + 2 per Peering office level', () => {
assert.equal(R.allianceCap(0), 10);
assert.equal(R.allianceCap(1), 12);
assert.equal(R.allianceCap(10), 30);
assert.equal(R.allianceCap(-3), 10);
});
test('rules: permission table and seniority', () => {
assert.ok(R.allianceCan('leader', 'disband') && !R.allianceCan('officer', 'disband'));
assert.ok(R.allianceCan('officer', 'invite') && !R.allianceCan('member', 'invite'));
assert.ok(R.allianceCan('diplomat', 'diplomacy') && !R.allianceCan('officer', 'diplomacy'));
assert.ok(!R.allianceCan('leader', 'no_such_action'));
assert.ok(R.outranks('leader', 'diplomat') && R.outranks('diplomat', 'officer') && R.outranks('officer', 'member'));
assert.ok(!R.outranks('officer', 'officer') && !R.outranks('member', 'leader'));
// every role listed in the table exists
for (const roles of Object.values(D.SOCIAL.permissions)) for (const r of roles) assert.ok(D.SOCIAL.roles.includes(r), r);
});
test('rules: diplomacy moves', () => {
assert.equal(R.diplomacyMove('neutral', 'war'), 'immediate');
assert.equal(R.diplomacyMove('neutral', 'nap'), 'proposal');
assert.equal(R.diplomacyMove('war', 'neutral'), 'proposal');
assert.equal(R.diplomacyMove('nap', 'neutral'), 'delayed');
assert.equal(R.diplomacyMove('confed', 'war'), 'delayed');
assert.equal(R.diplomacyMove('war', 'confed'), null);
assert.equal(R.diplomacyMove('war', 'war'), null);
assert.equal(R.diplomacyMove('bogus', 'war'), null);
assert.equal(R.pactCancelMs(1), 24 * 3600 * 1000);
assert.equal(R.pactCancelMs(3), 8 * 3600 * 1000);
});
test('text: control, bidi and invisible characters are stripped', () => {
assert.equal(cleanText('a‮b​c\u0007d'), 'abcd');
assert.equal(cleanText('x\u{E0041}y؜z'), 'xyz');
assert.equal(cleanText(' a \t\n b '), 'a b');
assert.equal(cleanText('l1\r\nl2\n\n\n\n\nl3', { multiline: true }), 'l1\nl2\n\n\nl3');
assert.equal(cleanText('é'), 'é'); // NFC
assert.equal(cleanText('\u{1F468}‍\u{1F469}'), '\u{1F468}‍\u{1F469}'); // ZWJ emoji sequences survive
assert.equal(cleanText(undefined), '');
});
test('helpers: the response contract check really fails on a body that breaks its schema', () => {
const { checkContract } = require('./helpers');
assert.throws(() => checkContract('GET', '/alliances/mine', 200, { serverTime: 1 }), /breaks its response schema/);
assert.throws(() => checkContract('GET', '/rankings/alliances', 200, { serverTime: 1, total: 'x', you: null, items: [], next: null }), /total/);
checkContract('GET', '/alliances/mine', 200, { serverTime: 1, operatorId: 1, worldId: 1, alliance: null, role: null, permissions: [], peeringLevel: 0 });
});

228
test/spine-core.test.js Normal file
View file

@ -0,0 +1,228 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { createServer } = require('../server');
const { FakeClock } = require('../server/clock');
const { openDb, migrate } = require('../server/db');
const { Scheduler } = require('../server/scheduler');
const { validate } = require('../server/validate');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
async function boot(opts) {
const clock = new FakeClock();
const srv = await createServer(Object.assign({ port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {} }, opts));
const base = 'http://127.0.0.1:' + srv.port + '/api/v1';
const call = async (p, o, token) => {
o = o || {};
const headers = Object.assign({ 'content-type': 'application/json' }, o.headers || {});
if (token) headers.authorization = 'Bearer ' + token;
const r = await fetch(base + p, Object.assign({}, o, { headers, body: o.body && JSON.stringify(o.body) }));
return { status: r.status, body: await r.json(), headers: r.headers };
};
const signup = async (username) => {
const r = await call('/auth/signup', { method: 'POST', body: { username, password: 'correct horse battery' } });
assert.equal(r.status, 201, JSON.stringify(r.body));
return { token: r.body.token, townId: r.body.operators[0].towns[0].id, userId: r.body.user.id };
};
return { srv, clock, call, signup };
}
test('rules: lazy resources are exact between settles and capped', () => {
const town = { speed: 1, updatedAt: 0, res: { fiber: 0, hardware: 0, capital: 0, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {},
buildings: R.initialBuildings() };
const h = D.HOUR_MS;
const a = R.resourcesAt(town, h).amounts;
assert.ok(Math.abs(a.fiber - 30) < 1e-9, 'five level-1 cable yards make 30/h');
assert.equal(R.resourcesAt(town, 1000 * h).amounts.fiber, R.storageCap(town));
assert.equal(R.resourcesAt(town, 0).amounts.fiber, 0);
// splitting the interval changes nothing
const mid = R.resourcesAt(town, 3 * h).amounts;
const t2 = Object.assign({}, town, { updatedAt: 3 * h, res: mid });
assert.ok(Math.abs(R.resourcesAt(t2, 5 * h).amounts.fiber - R.resourcesAt(town, 5 * h).amounts.fiber) < 1e-9);
});
test('rules: map generation is deterministic and spawn respects spacing', () => {
assert.deepEqual(R.tileAt(7, 50, 10, 10), R.tileAt(7, 50, 10, 10));
assert.equal(R.tileAt(7, 50, 51, 0).type, 'void');
const towns = [];
for (let i = 0; i < 40; i++) {
const s = R.pickSpawn(7, 50, i, towns);
assert.ok(s, 'spawn ' + i);
assert.equal(R.tileAt(7, 50, s.x, s.y).type, 'land');
for (const t of towns) assert.ok(Math.max(Math.abs(t.x - s.x), Math.abs(t.y - s.y)) >= D.TILE.spawnMinSpacing);
towns.push(s);
}
});
test('validate: unknown fields, types, coercion', () => {
const s = { type: 'object', required: ['a'], properties: { a: { type: 'integer', minimum: 1 }, b: { type: 'string', maxLength: 3 } } };
assert.ok(validate(s, { a: 1 }).ok);
assert.ok(!validate(s, {}).ok);
assert.ok(!validate(s, { a: 1, c: 2 }).ok);
assert.ok(!validate(s, { a: 1.5 }).ok);
assert.ok(!validate(s, { a: 1, b: 'long' }).ok);
assert.ok(validate(s, { a: '5' }, { coerce: true }).ok);
});
test('migrations: applied once, edits are detected', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mig-'));
fs.writeFileSync(path.join(dir, '001_a.sql'), 'CREATE TABLE a (x INTEGER);');
const db = openDb(':memory:');
assert.deepEqual(migrate(db, dir), ['001_a.sql']);
assert.deepEqual(migrate(db, dir), []);
fs.writeFileSync(path.join(dir, '001_a.sql'), 'CREATE TABLE a (x INTEGER, y INTEGER);');
assert.throws(() => migrate(db, dir), /edited after/);
});
test('scheduler: events run in (due_at, id) order, failures do not block, handlers see their own due time', () => {
const clock = new FakeClock(1000);
const db = openDb(':memory:');
migrate(db);
db.run("INSERT INTO worlds (name, speed, map_radius, seed, start_at, created_at) VALUES ('w', 1, 10, 1, 0, 0)");
const seen = [];
const s = new Scheduler({ db, clock, log: () => {}, autoArm: false, handlers: {
a: (ctx, ev) => { seen.push([ev.payload.n, ctx.now]); if (ev.payload.n === 2) ctx.enqueue({ worldId: 1, dueAt: 1500, type: 'a', payload: { n: 9 } }); },
boom: () => { throw new Error('nope'); },
} });
s.enqueue({ worldId: 1, dueAt: 3000, type: 'a', payload: { n: 3 } });
s.enqueue({ worldId: 1, dueAt: 2000, type: 'a', payload: { n: 2 } });
s.enqueue({ worldId: 1, dueAt: 2000, type: 'boom' });
s.enqueue({ worldId: 1, dueAt: 2000, type: 'a', payload: { n: 4 } });
assert.equal(s.runDue(1999), 0);
clock.set(10000);
assert.equal(s.runDue(), 5);
// a follow-up enqueued with an earlier due time is processed next, before later-due events
assert.deepEqual(seen, [[2, 2000], [9, 1500], [4, 2000], [3, 3000]]);
assert.equal(db.get("SELECT status FROM events WHERE type = 'boom'").status, 'failed');
assert.equal(db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'done'").n, 4);
});
test('api: signup, build lifecycle with a fake clock, queue limits, cancel refund', async () => {
const { srv, clock, call, signup } = await boot();
try {
const p = await signup('alice');
let r = await call('/towns/' + p.townId, {}, p.token);
assert.equal(r.status, 200);
const before = r.body.town.resources.fiber.amount;
r = await call('/towns/' + p.townId + '/build', { method: 'POST', body: { key: 'f1' } }, p.token);
assert.equal(r.status, 201);
const { dueAt, cost, eventId } = r.body;
// one slot only: second build is refused with a stable code
r = await call('/towns/' + p.townId + '/build', { method: 'POST', body: { key: 'f2' } }, p.token);
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'queue_full');
// not done yet one ms before
clock.set(dueAt - 1);
r = await call('/towns/' + p.townId, {}, p.token);
assert.equal(r.body.town.buildings.find((b) => b.key === 'f1').level, 1);
assert.equal(r.body.town.queue.length, 1);
clock.set(dueAt);
r = await call('/towns/' + p.townId, {}, p.token);
assert.equal(r.body.town.buildings.find((b) => b.key === 'f1').level, 2);
assert.equal(r.body.town.queue.length, 0);
const n = await call('/notifications', {}, p.token);
assert.equal(n.body.items[0].type, 'build_done');
// cancel refunds 80%
const f = r.body.town.resources.fiber.amount;
r = await call('/towns/' + p.townId + '/build', { method: 'POST', body: { key: 'rack_hall' } }, p.token);
assert.equal(r.status, 201);
const rack = r.body;
r = await call('/towns/' + p.townId + '/queue/' + rack.eventId, { method: 'DELETE' }, p.token);
assert.equal(r.status, 200);
r = await call('/towns/' + p.townId, {}, p.token);
assert.ok(r.body.town.resources.fiber.amount >= f - rack.cost.fiber + Math.floor(rack.cost.fiber * 0.8) - 1e-6);
assert.equal(r.body.town.queue.length, 0);
assert.ok(before > 0 && cost.fiber > 0 && eventId > 0);
} finally { await srv.close(); }
});
test('api: ownership is not leaked, auth is required, errors use the envelope', async () => {
const { srv, call, signup } = await boot();
try {
const a = await signup('alice'), b = await signup('bobby');
let r = await call('/towns/' + a.townId, {}, b.token);
assert.equal(r.status, 404); assert.equal(r.body.error.code, 'not_found');
r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1' } }, b.token);
assert.equal(r.status, 404);
r = await call('/towns/' + a.townId);
assert.equal(r.status, 401); assert.equal(r.body.error.code, 'unauthorized');
r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1', extra: 1 } }, a.token);
assert.equal(r.status, 422); assert.equal(r.body.error.code, 'validation_failed');
r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'nope' } }, a.token);
assert.equal(r.body.error.code, 'unknown_building');
r = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'ops_lab' } }, a.token);
assert.equal(r.body.error.code, 'requirements_not_met');
assert.ok(typeof r.body.serverTime === 'number');
} finally { await srv.close(); }
});
test('api: idempotency key replays and rejects reuse with a different request', async () => {
const { srv, call, signup } = await boot();
try {
const a = await signup('alice');
const h = { 'idempotency-key': 'abcdef123456' };
const r1 = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1' }, headers: h }, a.token);
const r2 = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f1' }, headers: h }, a.token);
assert.equal(r1.status, 201); assert.equal(r2.status, 201);
assert.equal(r2.headers.get('idempotent-replay'), 'true');
assert.equal(r1.body.eventId, r2.body.eventId);
const r3 = await call('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'f2' }, headers: h }, a.token);
assert.equal(r3.body.error.code, 'idempotency_key_reuse');
const t = await call('/towns/' + a.townId, {}, a.token);
assert.equal(t.body.town.queue.length, 1);
} finally { await srv.close(); }
});
test('auth: login, token list/revoke, wrong password, duplicate username', async () => {
const { srv, call, signup } = await boot();
try {
const a = await signup('alice');
let r = await call('/auth/signup', { method: 'POST', body: { username: 'ALICE', password: 'correct horse battery' } });
assert.equal(r.body.error.code, 'username_taken');
r = await call('/auth/login', { method: 'POST', body: { username: 'alice', password: 'wrong password!!' } });
assert.equal(r.status, 401); assert.equal(r.body.error.code, 'invalid_credentials');
r = await call('/auth/login', { method: 'POST', body: { username: 'alice', password: 'correct horse battery', device: 'phone' } });
assert.equal(r.status, 200);
const t2 = r.body.token;
r = await call('/auth/tokens', {}, a.token);
assert.equal(r.body.tokens.length, 2);
assert.equal(r.body.tokens.filter((t) => t.current).length, 1);
const phone = r.body.tokens.find((t) => t.device === 'phone');
r = await call('/auth/tokens/' + phone.id, { method: 'DELETE' }, a.token);
assert.equal(r.status, 200);
r = await call('/me', {}, t2);
assert.equal(r.status, 401);
} finally { await srv.close(); }
});
test('restart: overdue events are caught up in order before traffic', async () => {
const dbPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'restart-')), 'game.db');
const clock = new FakeClock();
const mk = () => createServer({ port: 0, host: '127.0.0.1', dbPath, clock, autoArm: false, log: () => {} });
let srv = await mk();
const base = () => 'http://127.0.0.1:' + srv.port + '/api/v1';
let r = await (await fetch(base() + '/auth/signup', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'alice', password: 'correct horse battery' }) })).json();
const token = r.token, townId = r.operators[0].towns[0].id;
const b = await (await fetch(base() + '/towns/' + townId + '/build', { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + token }, body: JSON.stringify({ key: 'f1' }) })).json();
await srv.close();
clock.set(b.dueAt + 10 * 60 * 1000);
srv = await mk();
try {
assert.equal(srv.db.get("SELECT level FROM buildings WHERE town_id = ? AND key = 'f1'", townId).level, 2, 'completed during catch-up');
assert.equal(srv.db.get("SELECT status FROM events WHERE id = ?", b.eventId).status, 'done');
} finally { await srv.close(); }
});
test('openapi.json is up to date and describes every route', () => {
const { render, FILE, build } = require('../tools/gen-openapi');
assert.equal(fs.readFileSync(FILE, 'utf8'), render(), 'run npm run openapi');
const { Router } = require('../server/http');
const routes = require('../server/routes');
const router = new Router();
routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null }) }));
const spec = build();
for (const r of router.routes) assert.ok(spec.paths[r.path.replace(/:([A-Za-z]+)/g, '{$1}')][r.method.toLowerCase()], r.method + ' ' + r.path);
});