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:
parent
b56b13880e
commit
249818a7aa
111 changed files with 17472 additions and 13 deletions
284
test/admin-cli.test.js
Normal file
284
test/admin-cli.test.js
Normal 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();
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue