'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); });