Stage 0-2 server spine: db, scheduler, REST, auth, economy, map
Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map + spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused. Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet. NOT done: military, expansion, social, client, push, deploy docs, bots/admin. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
9fa76d53a8
commit
b56b13880e
39 changed files with 4450 additions and 0 deletions
61
server/auth.js
Normal file
61
server/auth.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Passwords (scrypt via node:crypto) and opaque bearer tokens (random 32 bytes, only the sha256 stored, one per
|
||||
* device, listable and revocable). No cookies: the same scheme serves web and mobile.
|
||||
*/
|
||||
const crypto = require('crypto');
|
||||
const { promisify } = require('util');
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
|
||||
const N = 16384, R = 8, P = 1, KEYLEN = 64;
|
||||
|
||||
async function hashPassword(password) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const key = await scrypt(password, salt, KEYLEN, { N, r: R, p: P });
|
||||
return ['scrypt', N, R, P, salt.toString('base64'), key.toString('base64')].join('$');
|
||||
}
|
||||
|
||||
// A well-formed hash that matches nothing, used so an unknown username costs the same time as a wrong password.
|
||||
const DUMMY = ['scrypt', N, R, P, Buffer.alloc(16).toString('base64'), Buffer.alloc(KEYLEN).toString('base64')].join('$');
|
||||
|
||||
async function verifyPassword(password, stored) {
|
||||
const s = stored || DUMMY;
|
||||
const parts = String(s).split('$');
|
||||
if (parts.length !== 6 || parts[0] !== 'scrypt') return false;
|
||||
const salt = Buffer.from(parts[4], 'base64'), want = Buffer.from(parts[5], 'base64');
|
||||
const got = await scrypt(password, salt, want.length, { N: Number(parts[1]), r: Number(parts[2]), p: Number(parts[3]) });
|
||||
return crypto.timingSafeEqual(got, want) && s !== DUMMY;
|
||||
}
|
||||
|
||||
const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
||||
const newToken = () => crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
function createAuth({ db }) {
|
||||
const touched = new Map(); // tokenId -> last write, so last_used_at is not written on every request
|
||||
|
||||
// Authorization: Bearer <token> -> { user, tokenId } | null
|
||||
function authenticate(header, now) {
|
||||
if (typeof header !== 'string') return null;
|
||||
const m = /^Bearer ([A-Za-z0-9_-]{20,100})$/.exec(header);
|
||||
if (!m) return null;
|
||||
const row = db.get(`SELECT t.id AS tid, t.last_used_at AS used, u.id AS uid, u.username AS username, u.banned AS banned
|
||||
FROM tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.revoked_at IS NULL`, sha256(m[1]));
|
||||
if (!row || row.banned) return null;
|
||||
if (now - (touched.get(row.tid) || row.used) > 60000) {
|
||||
touched.set(row.tid, now);
|
||||
db.run('UPDATE tokens SET last_used_at = ? WHERE id = ?', now, row.tid);
|
||||
}
|
||||
return { user: { id: row.uid, username: row.username }, tokenId: row.tid };
|
||||
}
|
||||
|
||||
// Create a token for a user. Returns { token, tokenId }; the plain token is shown exactly once.
|
||||
function issueToken(userId, device, now) {
|
||||
const token = newToken();
|
||||
const r = db.run('INSERT INTO tokens (user_id, token_hash, device, created_at, last_used_at) VALUES (?, ?, ?, ?, ?)', userId, sha256(token), device || '', now, now);
|
||||
return { token, tokenId: Number(r.lastInsertRowid) };
|
||||
}
|
||||
|
||||
return { authenticate, issueToken, hashPassword, verifyPassword };
|
||||
}
|
||||
|
||||
module.exports = { createAuth, hashPassword, verifyPassword, sha256, newToken };
|
||||
17
server/clock.js
Normal file
17
server/clock.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The only place server code reads time. Every other module takes a clock; tests inject FakeClock.
|
||||
* All times are integer ms since the epoch, UTC.
|
||||
*/
|
||||
class RealClock {
|
||||
now() { return Date.now(); }
|
||||
}
|
||||
|
||||
class FakeClock {
|
||||
constructor(start) { this.t = start === undefined ? Date.UTC(2026, 0, 1) : start; }
|
||||
now() { return this.t; }
|
||||
set(t) { this.t = t; }
|
||||
advance(ms) { this.t += ms; return this.t; }
|
||||
}
|
||||
|
||||
module.exports = { RealClock, FakeClock };
|
||||
32
server/commands/build.js
Normal file
32
server/commands/build.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
'use strict';
|
||||
/* POST /towns/:id/build. Validate ownership and rules (rules.buildPlan), pay, enqueue the completion event. */
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadTown, settle, spend, pendingBuilds } = require('../state');
|
||||
|
||||
module.exports = function build(ctx, { userId, townId, key }) {
|
||||
const { db, now, scheduler } = ctx;
|
||||
const town = ownedTown(db, userId, townId);
|
||||
settle(db, town, now);
|
||||
const pending = pendingBuilds(db, town.id);
|
||||
const plan = R.buildPlan(town, key, now, pending);
|
||||
if (!plan.ok) {
|
||||
throw new GameError(plan.code, { key, type: plan.type, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing });
|
||||
}
|
||||
spend(db, town, plan.cost);
|
||||
const id = scheduler.enqueue({
|
||||
worldId: town.worldId, townId: town.id, type: 'buildDone', dueAt: now + plan.durationMs,
|
||||
payload: { key, type: plan.type, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId },
|
||||
});
|
||||
return { eventId: id, key, type: plan.type, toLevel: plan.toLevel, startedAt: now, dueAt: now + plan.durationMs, cost: plan.cost };
|
||||
};
|
||||
|
||||
// The town, if the user owns it; otherwise not_found (never reveal that a foreign town exists).
|
||||
function ownedTown(db, userId, townId) {
|
||||
const row = db.get(`SELECT t.id FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?`, townId, userId);
|
||||
const town = row ? loadTown(db, row.id) : null;
|
||||
if (!town) throw new GameError('not_found', { what: 'town' });
|
||||
return town;
|
||||
}
|
||||
|
||||
module.exports.ownedTown = ownedTown;
|
||||
22
server/commands/cancelBuild.js
Normal file
22
server/commands/cancelBuild.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use strict';
|
||||
/* DELETE /towns/:id/queue/:eventId. Cancels a running build and refunds 80% (rounded down). */
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { settle } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
|
||||
const REFUND = 0.8;
|
||||
|
||||
module.exports = function cancelBuild(ctx, { userId, townId, eventId }) {
|
||||
const { db, now } = ctx;
|
||||
const town = ownedTown(db, userId, townId);
|
||||
const ev = db.get("SELECT id, payload FROM events WHERE id = ? AND town_id = ? AND type = 'buildDone' AND status = 'pending'", eventId, town.id);
|
||||
if (!ev) throw new GameError('not_found', { what: 'queue entry' });
|
||||
settle(db, town, now);
|
||||
const cost = JSON.parse(ev.payload).cost || {};
|
||||
const cap = require('../../public/js/rules.js').storageCap(town);
|
||||
for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(cap, town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND));
|
||||
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
|
||||
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ?", now, ev.id);
|
||||
return { cancelled: ev.id };
|
||||
};
|
||||
28
server/commands/index.js
Normal file
28
server/commands/index.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Player commands: one file each, validate + apply in one transaction. `run` first catches the event queue up to now
|
||||
* (so a town is never touched with an overdue event pending), then runs the command in a transaction, then re-arms the
|
||||
* scheduler timer because the command may have enqueued events.
|
||||
*/
|
||||
const handlers = {
|
||||
signup: require('./signup'),
|
||||
joinWorld: require('./joinWorld'),
|
||||
build: require('./build'),
|
||||
cancelBuild: require('./cancelBuild'),
|
||||
renameTown: require('./renameTown'),
|
||||
};
|
||||
|
||||
function createCommands({ db, clock, scheduler }) {
|
||||
function run(name, args) {
|
||||
const fn = handlers[name];
|
||||
if (!fn) throw new Error('unknown command ' + name);
|
||||
scheduler.runDue();
|
||||
const now = clock.now();
|
||||
const out = db.tx(() => fn({ db, clock, now, scheduler }, args));
|
||||
scheduler.arm();
|
||||
return out;
|
||||
}
|
||||
return { run, handlers };
|
||||
}
|
||||
|
||||
module.exports = { createCommands };
|
||||
51
server/commands/joinWorld.js
Normal file
51
server/commands/joinWorld.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
'use strict';
|
||||
/* Create an operator for a user in a world, with a capital POP placed by the spawn ring. Not a player-facing route
|
||||
* on its own: signup and `POST /worlds/:id/join` call it. */
|
||||
const crypto = require('crypto');
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadWorld } = require('../state');
|
||||
|
||||
module.exports = function joinWorld(ctx, { userId, worldId }) {
|
||||
const { db, now } = ctx;
|
||||
const world = loadWorld(db, worldId);
|
||||
if (!world || world.status !== 'running') throw new GameError('not_found', { what: 'world' });
|
||||
const user = db.get('SELECT id, username FROM users WHERE id = ?', userId);
|
||||
if (!user) throw new GameError('not_found', { what: 'user' });
|
||||
if (db.get('SELECT 1 AS x FROM operators WHERE world_id = ? AND user_id = ?', worldId, userId)) throw new GameError('conflict', { what: 'already joined' });
|
||||
|
||||
const towns = db.all('SELECT x, y FROM towns WHERE world_id = ?', worldId);
|
||||
const spot = R.pickSpawn(world.seed, world.map_radius, towns.length, towns);
|
||||
if (!spot) throw new GameError('world_full');
|
||||
|
||||
let asn;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
asn = crypto.randomInt(D.AS_RANGE.min, D.AS_RANGE.max);
|
||||
if (!db.get('SELECT 1 AS x FROM operators WHERE world_id = ? AND as_number = ?', worldId, asn)) break;
|
||||
asn = null;
|
||||
}
|
||||
if (!asn) throw new GameError('internal_error');
|
||||
|
||||
const protectionMs = Math.round(D.PROTECTION_HOURS * D.HOUR_MS / world.speed);
|
||||
const op = db.run('INSERT INTO operators (world_id, user_id, name, as_number, protection_until, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
worldId, userId, user.username, asn, now + protectionMs, now);
|
||||
const operatorId = Number(op.lastInsertRowid);
|
||||
|
||||
const townId = createTown(db, { worldId, ownerId: operatorId, name: user.username + ' POP 1', x: spot.x, y: spot.y, isCapital: true, now });
|
||||
return { operatorId, townId, x: spot.x, y: spot.y, asNumber: asn };
|
||||
};
|
||||
|
||||
// A town with the starting buildings and resources. Also used by expansion (stage 4) with different `start` data.
|
||||
function createTown(db, { worldId, ownerId, name, x, y, isCapital, now, buildings, res }) {
|
||||
const start = res || D.START.resources;
|
||||
const t = db.run(`INSERT INTO towns (world_id, owner_id, name, x, y, is_capital, loyalty, loyalty_at, fiber, hardware, capital,
|
||||
battery, footprint, res_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
|
||||
worldId, ownerId, name, x, y, isCapital ? 1 : 0, D.START.loyalty, now, start.fiber, start.hardware, start.capital, D.START.battery, now, now);
|
||||
const id = Number(t.lastInsertRowid);
|
||||
const b = buildings || R.initialBuildings();
|
||||
for (const key of Object.keys(b)) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', id, key, b[key].type, b[key].level);
|
||||
return id;
|
||||
}
|
||||
|
||||
module.exports.createTown = createTown;
|
||||
20
server/commands/renameTown.js
Normal file
20
server/commands/renameTown.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
const { GameError } = require('../errors');
|
||||
const { ownedTown } = require('./build');
|
||||
|
||||
const STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
|
||||
|
||||
// Display-name hygiene: no control or bidi characters, collapsed whitespace, 2..24 characters.
|
||||
function cleanName(v) {
|
||||
const s = Array.from(String(v).replace(STRIP, '').replace(/\s+/g, ' ').trim()).slice(0, 24).join('').trim();
|
||||
return s;
|
||||
}
|
||||
|
||||
module.exports = function renameTown(ctx, { userId, townId, name }) {
|
||||
const town = ownedTown(ctx.db, userId, townId);
|
||||
const clean = cleanName(name);
|
||||
if (clean.length < 2) throw new GameError('validation_failed', { errors: [{ path: 'name', message: 'too short' }] });
|
||||
ctx.db.run('UPDATE towns SET name = ? WHERE id = ?', clean, town.id);
|
||||
return { name: clean };
|
||||
};
|
||||
module.exports.cleanName = cleanName;
|
||||
18
server/commands/signup.js
Normal file
18
server/commands/signup.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
'use strict';
|
||||
/* Create account + operator + capital POP + first token in one transaction. The password hash and token hash are
|
||||
* computed by the route before the transaction (scrypt is async, a transaction never spans an await). */
|
||||
const { GameError } = require('../errors');
|
||||
const joinWorld = require('./joinWorld');
|
||||
|
||||
module.exports = function signup(ctx, { username, passHash, tokenHash, device, worldId }) {
|
||||
const { db, now } = ctx;
|
||||
if (db.get('SELECT 1 AS x FROM users WHERE username = ?', username)) throw new GameError('username_taken');
|
||||
const w = worldId !== undefined ? db.get("SELECT id FROM worlds WHERE id = ? AND status = 'running'", worldId)
|
||||
: db.get("SELECT id FROM worlds WHERE status = 'running' ORDER BY id LIMIT 1");
|
||||
if (!w) throw new GameError('not_found', { what: 'world' });
|
||||
const u = db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', username, passHash, now);
|
||||
const userId = Number(u.lastInsertRowid);
|
||||
const joined = joinWorld(ctx, { userId, worldId: w.id });
|
||||
const t = db.run('INSERT INTO tokens (user_id, token_hash, device, created_at, last_used_at) VALUES (?, ?, ?, ?, ?)', userId, tokenHash, device || '', now, now);
|
||||
return Object.assign({ userId, tokenId: Number(t.lastInsertRowid) }, joined);
|
||||
};
|
||||
96
server/db.js
Normal file
96
server/db.js
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The only module that touches SQLite. Wraps node:sqlite so the driver can be swapped for better-sqlite3 by
|
||||
* rewriting this file. One connection, owned by the one Node process, WAL mode.
|
||||
*
|
||||
* const db = openDb('./data/game.db');
|
||||
* migrate(db);
|
||||
* db.tx(() => { db.run('INSERT ...', a, b); return db.get('SELECT ...', id); });
|
||||
*
|
||||
* Parameters are always positional (`?`), never interpolated. `tx` nests through savepoints.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { DatabaseSync } = require('node:sqlite');
|
||||
|
||||
class Db {
|
||||
constructor(file) {
|
||||
this.file = file;
|
||||
if (file !== ':memory:') fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
|
||||
this.raw = new DatabaseSync(file);
|
||||
this.raw.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
|
||||
this.cache = new Map();
|
||||
this.depth = 0;
|
||||
}
|
||||
|
||||
stmt(sql) {
|
||||
let s = this.cache.get(sql);
|
||||
if (!s) { s = this.raw.prepare(sql); this.cache.set(sql, s); }
|
||||
return s;
|
||||
}
|
||||
|
||||
static params(p) { return p.map((v) => (v === undefined ? null : v)); }
|
||||
|
||||
run(sql, ...p) { return this.stmt(sql).run(...Db.params(p)); }
|
||||
get(sql, ...p) { return this.stmt(sql).get(...Db.params(p)); }
|
||||
all(sql, ...p) { return this.stmt(sql).all(...Db.params(p)); }
|
||||
exec(sql) { this.raw.exec(sql); }
|
||||
|
||||
// Runs fn inside a transaction (BEGIN IMMEDIATE at the top level, a savepoint when nested). Rolls back and
|
||||
// rethrows on any exception. fn must be synchronous: a transaction never spans an await.
|
||||
tx(fn) {
|
||||
const top = this.depth === 0;
|
||||
const sp = 'sp' + this.depth;
|
||||
this.raw.exec(top ? 'BEGIN IMMEDIATE' : 'SAVEPOINT ' + sp);
|
||||
this.depth++;
|
||||
let out;
|
||||
try {
|
||||
out = fn();
|
||||
if (out && typeof out.then === 'function') throw new Error('db.tx callback must not be async');
|
||||
} catch (err) {
|
||||
this.depth--;
|
||||
this.raw.exec(top ? 'ROLLBACK' : 'ROLLBACK TO ' + sp + '; RELEASE ' + sp);
|
||||
throw err;
|
||||
}
|
||||
this.depth--;
|
||||
this.raw.exec(top ? 'COMMIT' : 'RELEASE ' + sp);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Consistent snapshot into a new file (docs/DEPLOY.md: a systemd timer calls tools/admin.js backup).
|
||||
backup(dest) {
|
||||
if (fs.existsSync(dest)) throw new Error('backup target exists: ' + dest);
|
||||
this.raw.exec("VACUUM INTO '" + dest.replace(/'/g, "''") + "'");
|
||||
}
|
||||
|
||||
close() { this.cache.clear(); this.raw.close(); }
|
||||
}
|
||||
|
||||
function openDb(file) { return new Db(file); }
|
||||
|
||||
// Applies server/migrations/NNN_name.sql in order. Applied migrations are recorded with a checksum: editing one
|
||||
// after the fact is an error ("never edited after merge").
|
||||
function migrate(db, dir) {
|
||||
dir = dir || path.join(__dirname, 'migrations');
|
||||
db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, sha TEXT NOT NULL, applied_at INTEGER NOT NULL)');
|
||||
const files = fs.readdirSync(dir).filter((f) => /^\d+.*\.sql$/.test(f)).sort();
|
||||
const applied = [];
|
||||
for (const f of files) {
|
||||
const sql = fs.readFileSync(path.join(dir, f), 'utf8');
|
||||
const sha = crypto.createHash('sha256').update(sql).digest('hex');
|
||||
const row = db.get('SELECT sha FROM schema_migrations WHERE name = ?', f);
|
||||
if (row) {
|
||||
if (row.sha !== sha) throw new Error('migration ' + f + ' was edited after it was applied');
|
||||
continue;
|
||||
}
|
||||
db.tx(() => {
|
||||
db.exec(sql);
|
||||
db.run('INSERT INTO schema_migrations (name, sha, applied_at) VALUES (?, ?, ?)', f, sha, Date.now());
|
||||
});
|
||||
applied.push(f);
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
module.exports = { openDb, migrate, Db };
|
||||
43
server/errors.js
Normal file
43
server/errors.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Stable API error codes. Clients switch on `code`, never on `message`. Every code the API can return is listed
|
||||
* here with its HTTP status; docs/API.md and openapi.json are generated from this table.
|
||||
*/
|
||||
const CODES = {
|
||||
bad_request: [400, 'The request could not be parsed.'],
|
||||
validation_failed: [422, 'A field is missing or has the wrong shape.'],
|
||||
unauthorized: [401, 'Missing, invalid or revoked token.'],
|
||||
invalid_credentials: [401, 'Wrong username or password.'],
|
||||
forbidden: [403, 'You may not do that.'],
|
||||
not_found: [404, 'No such thing.'],
|
||||
method_not_allowed: [405, 'Wrong HTTP method for this path.'],
|
||||
conflict: [409, 'The request conflicts with the current state.'],
|
||||
request_in_progress: [409, 'A request with this Idempotency-Key is still running.'],
|
||||
idempotency_key_reuse: [422, 'This Idempotency-Key was used for a different request.'],
|
||||
payload_too_large: [413, 'Request body too large.'],
|
||||
rate_limited: [429, 'Too many requests, slow down.'],
|
||||
internal_error: [500, 'Something broke on our side.'],
|
||||
signup_closed: [403, 'Signup needs a valid invite code.'],
|
||||
username_taken: [409, 'That username is taken.'],
|
||||
world_full: [409, 'There is no room left on the map.'],
|
||||
// game rules
|
||||
unknown_building: [404, 'No such building or slot.'],
|
||||
not_buildable: [409, 'That building cannot be built here.'],
|
||||
max_level: [409, 'Already at the maximum level.'],
|
||||
requirements_not_met: [409, 'A required building level is missing.'],
|
||||
already_queued: [409, 'That building is already being built.'],
|
||||
queue_full: [409, 'All build slots are busy.'],
|
||||
not_enough_resources: [409, 'Not enough resources.'],
|
||||
};
|
||||
|
||||
class GameError extends Error {
|
||||
constructor(code, details, message) {
|
||||
const def = CODES[code];
|
||||
super(message || (def ? def[1] : code));
|
||||
this.code = code;
|
||||
this.status = def ? def[0] : 400;
|
||||
this.details = details || {};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { CODES, GameError };
|
||||
15
server/events/buildDone.js
Normal file
15
server/events/buildDone.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
'use strict';
|
||||
/* A building level finished. Payload: { key, type, toLevel, userId }. Idempotent: a level never goes down. */
|
||||
const { loadTown, settle } = require('../state');
|
||||
|
||||
module.exports = function buildDone(ctx, ev) {
|
||||
const { db } = ctx;
|
||||
const { key, type, toLevel, userId } = ev.payload;
|
||||
const town = loadTown(db, ev.townId);
|
||||
if (!town) return;
|
||||
settle(db, town, ev.dueAt); // values up to the moment of completion, at the OLD rates
|
||||
const cur = town.buildings[key];
|
||||
if (!cur) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, toLevel);
|
||||
else if (cur.level < toLevel) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', toLevel, town.id, key);
|
||||
if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel });
|
||||
};
|
||||
5
server/events/index.js
Normal file
5
server/events/index.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
'use strict';
|
||||
/* Event type -> handler. One file per event type. */
|
||||
module.exports = {
|
||||
buildDone: require('./buildDone'),
|
||||
};
|
||||
227
server/http.js
Normal file
227
server/http.js
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Tiny REST layer on node:http: router, JSON in/out, error envelope, bearer auth, rate limits, Idempotency-Key.
|
||||
*
|
||||
* const api = createApi({ db, clock, log, opts, services });
|
||||
* routes.register(api.router, services);
|
||||
* server.on('request', (req, res) => url.startsWith('/api/') ? api.handle(req, res) : serveStatic(req, res));
|
||||
*
|
||||
* Route meta (also the source of docs/openapi.json, see tools/gen-openapi.js):
|
||||
* { summary, tag, auth: true|false, query: schema, body: schema, response: schema, errors: [codes], limit: 'auth' }
|
||||
* Every JSON response is an object carrying `serverTime`. Errors are { error: { code, message, details } }.
|
||||
*/
|
||||
const crypto = require('crypto');
|
||||
const { GameError, CODES } = require('./errors');
|
||||
const { validate } = require('./validate');
|
||||
const { TokenBucket, clientIp } = require('./net');
|
||||
const { applySecurityHeaders } = require('./static');
|
||||
|
||||
const MAX_BODY = 32 * 1024;
|
||||
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId']);
|
||||
|
||||
// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound.
|
||||
class Limiter {
|
||||
constructor(ratePerSec, burst, maxKeys) { this.rate = ratePerSec; this.burst = burst; this.maxKeys = maxKeys || 20000; this.m = new Map(); }
|
||||
take(key) {
|
||||
let b = this.m.get(key);
|
||||
if (!b) {
|
||||
if (this.m.size >= this.maxKeys) this.prune();
|
||||
b = new TokenBucket(this.rate, this.burst); this.m.set(key, b);
|
||||
}
|
||||
return b.take();
|
||||
}
|
||||
prune() {
|
||||
for (const [k, b] of this.m) if (b.tokens >= b.burst - 0.5) this.m.delete(k);
|
||||
if (this.m.size >= this.maxKeys) this.m.clear(); // under attack from >maxKeys distinct keys: forget, do not grow
|
||||
}
|
||||
}
|
||||
|
||||
class Router {
|
||||
constructor() { this.routes = []; }
|
||||
// path like '/towns/:id/build' (relative to /api/v1)
|
||||
add(method, path, meta, handler) {
|
||||
const names = [];
|
||||
const re = new RegExp('^' + path.replace(/:([A-Za-z]+)/g, (m, n) => { names.push(n); return '([^/]+)'; }) + '$');
|
||||
this.routes.push({ method, path, re, names, meta: meta || {}, handler });
|
||||
}
|
||||
get(path, meta, h) { this.add('GET', path, meta, h); }
|
||||
post(path, meta, h) { this.add('POST', path, meta, h); }
|
||||
del(path, meta, h) { this.add('DELETE', path, meta, h); }
|
||||
// -> { route, params } | { methods: [...] } (path matches, method does not) | null
|
||||
find(method, pathname) {
|
||||
const allowed = [];
|
||||
for (const r of this.routes) {
|
||||
const m = r.re.exec(pathname);
|
||||
if (!m) continue;
|
||||
if (r.method !== method) { allowed.push(r.method); continue; }
|
||||
const params = {};
|
||||
for (let i = 0; i < r.names.length; i++) {
|
||||
let v;
|
||||
try { v = decodeURIComponent(m[i + 1]); } catch (e) { return null; }
|
||||
if (INT_PARAMS.has(r.names[i])) {
|
||||
if (!/^\d{1,12}$/.test(v)) return null;
|
||||
v = Number(v);
|
||||
}
|
||||
params[r.names[i]] = v;
|
||||
}
|
||||
return { route: r, params };
|
||||
}
|
||||
return allowed.length ? { methods: allowed } : null;
|
||||
}
|
||||
}
|
||||
|
||||
// A handler returns a plain object (HTTP 200) or reply(status, object).
|
||||
class Reply { constructor(status, body) { this.status = status; this.body = body; } }
|
||||
const reply = (status, body) => new Reply(status, body);
|
||||
|
||||
function createApi({ db, clock, log, opts, auth }) {
|
||||
const router = new Router();
|
||||
const ipLimit = new Limiter(opts.ipRate || 30, opts.ipBurst || 90);
|
||||
const tokenLimit = new Limiter(opts.tokenRate || 15, opts.tokenBurst || 45);
|
||||
const authLimit = new Limiter(opts.authRate || 0.1, opts.authBurst || 8); // login / signup: ~1 per 10 s sustained
|
||||
const inflight = new Set();
|
||||
|
||||
function send(res, status, body, extra) {
|
||||
const text = JSON.stringify(body);
|
||||
applySecurityHeaders(res);
|
||||
res.writeHead(status, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text), 'Cache-Control': 'no-store' }, extra));
|
||||
res.end(text);
|
||||
}
|
||||
|
||||
function fail(res, err, ctx) {
|
||||
let ge = err;
|
||||
if (!(err instanceof GameError)) {
|
||||
log('internal error ' + (ctx || '') + ': ' + (err && err.stack || err));
|
||||
ge = new GameError('internal_error');
|
||||
}
|
||||
const extra = ge.status === 429 && ge.details.retryAfter ? { 'Retry-After': String(ge.details.retryAfter) } : undefined;
|
||||
send(res, ge.status, { serverTime: clock.now(), error: { code: ge.code, message: ge.message, details: ge.details } }, extra);
|
||||
}
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const len = Number(req.headers['content-length'] || 0);
|
||||
if (len > MAX_BODY) return reject(new GameError('payload_too_large'));
|
||||
const chunks = []; let size = 0;
|
||||
req.on('data', (c) => {
|
||||
size += c.length;
|
||||
if (size > MAX_BODY) { reject(new GameError('payload_too_large')); req.destroy(); return; }
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
req.on('error', () => reject(new GameError('bad_request')));
|
||||
});
|
||||
}
|
||||
|
||||
async function handle(req, res) {
|
||||
const ip = clientIp(req, opts.trustProxy, opts.trustedProxies);
|
||||
const started = clock.now();
|
||||
let pathname = '', routeKey = '';
|
||||
try {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
pathname = u.pathname;
|
||||
if (!ipLimit.take(ip)) { log('refused rate_limited(ip) ip=' + ip + ' path=' + pathname); throw new GameError('rate_limited', { retryAfter: 1 }); }
|
||||
if (!pathname.startsWith('/api/v1/')) throw new GameError('not_found');
|
||||
const found = router.find(req.method, pathname.slice('/api/v1'.length));
|
||||
if (!found) throw new GameError('not_found');
|
||||
if (found.methods) { const e = new GameError('method_not_allowed', { allowed: found.methods }); throw e; }
|
||||
const { route, params } = found;
|
||||
routeKey = route.method + ' ' + route.path;
|
||||
const meta = route.meta;
|
||||
|
||||
if (meta.limit === 'auth' && !authLimit.take(ip)) { log('refused rate_limited(auth) ip=' + ip + ' route=' + routeKey); throw new GameError('rate_limited', { retryAfter: 10 }); }
|
||||
|
||||
let user = null, tokenId = null;
|
||||
if (meta.auth !== false) {
|
||||
const a = auth.authenticate(req.headers.authorization, clock.now());
|
||||
if (!a) { log('refused unauthorized ip=' + ip + ' route=' + routeKey); throw new GameError('unauthorized'); }
|
||||
user = a.user; tokenId = a.tokenId;
|
||||
if (!tokenLimit.take('t' + tokenId)) { log('refused rate_limited(token) token=' + tokenId + ' route=' + routeKey); throw new GameError('rate_limited', { retryAfter: 1 }); }
|
||||
}
|
||||
|
||||
// query
|
||||
const query = {};
|
||||
for (const [k, v] of u.searchParams) query[k] = v;
|
||||
let q = {};
|
||||
if (meta.query) {
|
||||
const v = validate(meta.query, query, { coerce: true });
|
||||
if (!v.ok) throw new GameError('validation_failed', { errors: v.errors });
|
||||
q = v.value;
|
||||
}
|
||||
|
||||
// body
|
||||
let body = {};
|
||||
if (meta.body) {
|
||||
const raw = await readBody(req);
|
||||
let parsed = {};
|
||||
if (raw.length) {
|
||||
if (!/^application\/json\b/i.test(req.headers['content-type'] || '')) throw new GameError('bad_request', { reason: 'content-type must be application/json' });
|
||||
try { parsed = JSON.parse(raw.toString('utf8')); } catch (e) { throw new GameError('bad_request', { reason: 'invalid JSON' }); }
|
||||
}
|
||||
const v = validate(meta.body, parsed);
|
||||
if (!v.ok) throw new GameError('validation_failed', { errors: v.errors });
|
||||
body = v.value;
|
||||
} else if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
await readBody(req).catch(() => null); // drain
|
||||
}
|
||||
|
||||
const ctx = { req, ip, user, tokenId, params, query: q, body, now: clock.now() };
|
||||
|
||||
// Idempotency-Key on mutating POSTs of authenticated users
|
||||
const idem = req.method === 'POST' && user ? req.headers['idempotency-key'] : undefined;
|
||||
let idemId = null;
|
||||
if (idem !== undefined) {
|
||||
if (typeof idem !== 'string' || !/^[A-Za-z0-9_.:-]{8,64}$/.test(idem)) throw new GameError('validation_failed', { errors: [{ path: 'Idempotency-Key', message: 'must be 8-64 of A-Za-z0-9_.:-' }] });
|
||||
const sig = req.method + ' ' + pathname + ' ' + crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
|
||||
idemId = user.id + ':' + idem;
|
||||
const row = db.get('SELECT request, status, body FROM idempotency WHERE user_id = ? AND key = ?', user.id, idem);
|
||||
if (row) {
|
||||
if (row.request !== sig) throw new GameError('idempotency_key_reuse');
|
||||
return send(res, row.status, JSON.parse(row.body), { 'Idempotent-Replay': 'true' });
|
||||
}
|
||||
if (inflight.has(idemId)) throw new GameError('request_in_progress');
|
||||
inflight.add(idemId);
|
||||
ctx.idem = { key: idem, sig };
|
||||
}
|
||||
try {
|
||||
let out;
|
||||
let status = 200;
|
||||
try {
|
||||
out = await route.handler(ctx);
|
||||
if (out instanceof Reply) { status = out.status; out = out.body; }
|
||||
out = Object.assign({ serverTime: clock.now() }, out);
|
||||
} catch (err) {
|
||||
if (ctx.idem && err instanceof GameError && err.status < 500) {
|
||||
// Replaying a rejected request must give the same rejection, not run it again.
|
||||
const eb = { serverTime: clock.now(), error: { code: err.code, message: err.message, details: err.details } };
|
||||
storeIdem(user.id, ctx.idem, err.status, eb);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (ctx.idem) storeIdem(user.id, ctx.idem, status, out);
|
||||
send(res, status, out);
|
||||
} finally { if (idemId) inflight.delete(idemId); }
|
||||
} catch (err) {
|
||||
if (!(err instanceof GameError)) log('request failed ' + routeKey + ' ' + pathname + ': ' + (err && err.stack || err));
|
||||
else if (err.status >= 400 && err.code !== 'not_found' && err.code !== 'unauthorized' && err.status !== 429) {
|
||||
// game-rule refusals are normal traffic; keep them out of the log except for the security-relevant codes
|
||||
if (err.code === 'forbidden' || err.code === 'validation_failed' || err.code === 'bad_request') log('refused ' + err.code + ' ip=' + ip + ' route=' + routeKey);
|
||||
}
|
||||
if (!res.headersSent) fail(res, err, routeKey);
|
||||
}
|
||||
}
|
||||
|
||||
function storeIdem(userId, idem, status, body) {
|
||||
try {
|
||||
db.run('INSERT OR IGNORE INTO idempotency (user_id, key, request, status, body, created_at) VALUES (?, ?, ?, ?, ?, ?)', userId, idem.key, idem.sig, status, JSON.stringify(body), clock.now());
|
||||
} catch (e) { log('could not store idempotency key: ' + e.message); }
|
||||
}
|
||||
|
||||
function pruneIdempotency() {
|
||||
db.run('DELETE FROM idempotency WHERE created_at < ?', clock.now() - 24 * 3600 * 1000);
|
||||
}
|
||||
|
||||
return { router, handle, pruneIdempotency, CODES };
|
||||
}
|
||||
|
||||
module.exports = { createApi, Router, Reply, reply, Limiter };
|
||||
132
server/index.js
Normal file
132
server/index.js
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
'use strict';
|
||||
/*
|
||||
* UPSTREAM server: static client + REST API under /api/v1 + (stage 6) WebSocket push, one SQLite file.
|
||||
* See docs/API.md, docs/DEPLOY.md.
|
||||
*
|
||||
* const { createServer } = require('./server');
|
||||
* const srv = await createServer({ port: 8080, dbPath: './data/game.db' }); // srv.port, srv.close(), srv.db, ...
|
||||
*
|
||||
* Run directly: PORT=8080 HOST=:: DB_PATH=./data/game.db TRUST_PROXY=auto ALLOWED_ORIGINS=https://game.example.com node server/index.js
|
||||
*/
|
||||
const http = require('http');
|
||||
const path = require('path');
|
||||
const { openDb, migrate } = require('./db');
|
||||
const { RealClock } = require('./clock');
|
||||
const { Scheduler } = require('./scheduler');
|
||||
const { createCommands } = require('./commands');
|
||||
const { createQueries } = require('./queries');
|
||||
const { createApi } = require('./http');
|
||||
const { createAuth } = require('./auth');
|
||||
const { ensureWorld } = require('./world');
|
||||
const routes = require('./routes');
|
||||
const eventHandlers = require('./events');
|
||||
const { createStaticHandler, applySecurityHeaders } = require('./static');
|
||||
const { parseTrustProxy, parseTrustedProxies, listenDual, listUrls } = require('./net');
|
||||
|
||||
function defaultLog(msg) { console.log(new Date().toISOString() + ' ' + msg); }
|
||||
|
||||
async function createServer(userOpts) {
|
||||
const o = {
|
||||
port: 8080, host: '::', publicDir: path.join(__dirname, '..', 'public'), dbPath: process.env.DB_PATH || './data/game.db',
|
||||
trustProxy: 'auto', trustedProxies: null, allowedOrigins: [], maxConnPerIp: 40, log: defaultLog,
|
||||
clock: null, autoArm: true, signupCode: process.env.SIGNUP_CODE || '',
|
||||
world: { speed: Number(process.env.WORLD_SPEED) || undefined, mapRadius: Number(process.env.WORLD_RADIUS) || undefined, name: process.env.WORLD_NAME || undefined },
|
||||
};
|
||||
for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k];
|
||||
o.trustProxy = parseTrustProxy(o.trustProxy);
|
||||
o.trustedProxies = parseTrustedProxies(o.trustedProxies);
|
||||
const log = typeof o.log === 'function' ? o.log : () => {};
|
||||
const clock = o.clock || new RealClock();
|
||||
|
||||
const db = openDb(o.dbPath);
|
||||
const applied = migrate(db);
|
||||
if (applied.length) log('applied migrations: ' + applied.join(', '));
|
||||
const worldId = ensureWorld(db, clock.now(), o.world);
|
||||
if (worldId) log('created world ' + worldId);
|
||||
|
||||
const scheduler = new Scheduler({ db, clock, handlers: eventHandlers, log, autoArm: o.autoArm });
|
||||
const caught = scheduler.catchUp(); // everything overdue, in order, before accepting traffic
|
||||
if (caught) log('caught up ' + caught + ' overdue event(s)');
|
||||
const commands = createCommands({ db, clock, scheduler });
|
||||
const queries = createQueries({ db, clock, scheduler });
|
||||
const auth = createAuth({ db });
|
||||
const api = createApi({ db, clock, log, opts: o, auth });
|
||||
const services = { db, clock, scheduler, commands, queries, auth, opts: o, log };
|
||||
routes.register(api.router, services);
|
||||
api.services = services;
|
||||
|
||||
const serveStatic = createStaticHandler(o.publicDir);
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = req.url || '/';
|
||||
if (url === '/healthz' || url.startsWith('/healthz?')) {
|
||||
applySecurityHeaders(res);
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
||||
return res.end(req.method === 'HEAD' ? undefined : 'ok');
|
||||
}
|
||||
if (url.startsWith('/api/')) return api.handle(req, res);
|
||||
return serveStatic(req, res).catch((err) => { log('static error: ' + (err && err.message)); if (!res.headersSent) res.writeHead(500); res.end(); });
|
||||
});
|
||||
server.headersTimeout = 20000; server.requestTimeout = 30000; server.keepAliveTimeout = 5000;
|
||||
const sockets = new Set();
|
||||
server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
|
||||
|
||||
const bound = await listenDual(server, o.port, o.host, log);
|
||||
const port = server.address().port;
|
||||
scheduler.arm();
|
||||
const idemTimer = setInterval(() => { try { api.pruneIdempotency(); } catch (e) { log('prune failed: ' + e.message); } }, 3600 * 1000);
|
||||
idemTimer.unref();
|
||||
|
||||
let closePromise = null;
|
||||
function close() {
|
||||
if (closePromise) return closePromise;
|
||||
closePromise = (async () => {
|
||||
scheduler.stop(); clearInterval(idemTimer);
|
||||
await new Promise((r) => { server.close(() => r()); if (server.closeIdleConnections) server.closeIdleConnections(); setTimeout(() => { for (const s of sockets) s.destroy(); }, 1000).unref(); });
|
||||
db.close();
|
||||
})();
|
||||
return closePromise;
|
||||
}
|
||||
|
||||
return Object.assign(services, { port, host: bound, server, api, close, options: o });
|
||||
}
|
||||
|
||||
function envInt(name, def) {
|
||||
const v = process.env[name];
|
||||
if (v === undefined || v === '') return def;
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < 0) throw new Error(name + ' must be a non-negative integer (got ' + JSON.stringify(v) + ')');
|
||||
return n;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const opts = {
|
||||
port: envInt('PORT', 8080), host: process.env.HOST || '::',
|
||||
trustProxy: process.env.TRUST_PROXY || 'auto', trustedProxies: process.env.TRUSTED_PROXIES || '',
|
||||
allowedOrigins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
};
|
||||
if (process.env.MAX_CONN_PER_IP) opts.maxConnPerIp = envInt('MAX_CONN_PER_IP', 40);
|
||||
const srv = await createServer(opts);
|
||||
console.log('UPSTREAM is listening on ' + (srv.host.includes(':') ? '[' + srv.host + ']' : srv.host) + ':' + srv.port +
|
||||
(srv.host === '::' ? ' (dual stack: IPv4 + IPv6)' : srv.host === '0.0.0.0' ? ' (IPv4 only)' : ''));
|
||||
console.log(' database: ' + path.resolve(srv.options.dbPath));
|
||||
console.log('Open:');
|
||||
for (const u of listUrls(srv.host, srv.port)) console.log(' ' + u);
|
||||
|
||||
let stopping = false;
|
||||
const stop = (sig) => {
|
||||
if (stopping) { console.log('second ' + sig + ', exiting now'); process.exit(0); }
|
||||
stopping = true;
|
||||
console.log('received ' + sig + ', shutting down');
|
||||
const force = setTimeout(() => { console.log('shutdown timed out, exiting'); process.exit(0); }, 5000);
|
||||
force.unref();
|
||||
srv.close().then(() => process.exit(0), (err) => { console.error(err); process.exit(0); });
|
||||
};
|
||||
process.on('SIGINT', () => stop('SIGINT'));
|
||||
process.on('SIGTERM', () => stop('SIGTERM'));
|
||||
}
|
||||
|
||||
module.exports = { createServer };
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((err) => { console.error('UPSTREAM failed to start: ' + (err && err.message || err)); process.exit(1); });
|
||||
}
|
||||
120
server/migrations/001_init.sql
Normal file
120
server/migrations/001_init.sql
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
-- Stage 0/1/2 schema: worlds, accounts, tokens, operators, towns, buildings, the event queue.
|
||||
-- Every game row carries world_id. Times are integer ms since the epoch (UTC).
|
||||
|
||||
CREATE TABLE worlds (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
speed REAL NOT NULL DEFAULT 1,
|
||||
map_radius INTEGER NOT NULL,
|
||||
seed INTEGER NOT NULL,
|
||||
start_at INTEGER NOT NULL,
|
||||
end_at INTEGER,
|
||||
status TEXT NOT NULL DEFAULT 'running', -- running | ended
|
||||
preset TEXT NOT NULL DEFAULT 'standard',
|
||||
config TEXT NOT NULL DEFAULT '{}',
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
pass_hash TEXT NOT NULL,
|
||||
banned INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- Opaque bearer tokens, one per device. Only the sha256 of the token is stored.
|
||||
CREATE TABLE tokens (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
device TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
last_used_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER
|
||||
);
|
||||
CREATE INDEX tokens_user ON tokens(user_id);
|
||||
|
||||
-- A user's presence in one world.
|
||||
CREATE TABLE operators (
|
||||
id INTEGER PRIMARY KEY,
|
||||
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||
name TEXT NOT NULL,
|
||||
as_number INTEGER NOT NULL,
|
||||
alliance_id INTEGER,
|
||||
protection_until INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (world_id, user_id),
|
||||
UNIQUE (world_id, as_number)
|
||||
);
|
||||
|
||||
-- A POP. Growing quantities are (amount, res_at): current value = rules.resourcesAt(town, now).
|
||||
CREATE TABLE towns (
|
||||
id INTEGER PRIMARY KEY,
|
||||
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||
owner_id INTEGER NOT NULL REFERENCES operators(id),
|
||||
name TEXT NOT NULL,
|
||||
x INTEGER NOT NULL,
|
||||
y INTEGER NOT NULL,
|
||||
is_capital INTEGER NOT NULL DEFAULT 0,
|
||||
loyalty REAL NOT NULL DEFAULT 100,
|
||||
loyalty_at INTEGER NOT NULL,
|
||||
fiber REAL NOT NULL,
|
||||
hardware REAL NOT NULL,
|
||||
capital REAL NOT NULL,
|
||||
battery REAL NOT NULL,
|
||||
footprint REAL NOT NULL DEFAULT 0,
|
||||
res_at INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (world_id, x, y)
|
||||
);
|
||||
CREATE INDEX towns_owner ON towns(owner_id);
|
||||
|
||||
-- key: 'f1'..'f18' for resource fields, the building type for infrastructure.
|
||||
CREATE TABLE buildings (
|
||||
town_id INTEGER NOT NULL REFERENCES towns(id),
|
||||
key TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
level INTEGER NOT NULL,
|
||||
PRIMARY KEY (town_id, key)
|
||||
);
|
||||
|
||||
-- Every future thing is a row here; scheduler.js processes them in (due_at, id) order.
|
||||
CREATE TABLE events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
world_id INTEGER NOT NULL,
|
||||
due_at INTEGER NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
town_id INTEGER, -- the main town the event is about (queue listings)
|
||||
payload TEXT NOT NULL DEFAULT '{}',
|
||||
status TEXT NOT NULL DEFAULT 'pending', -- pending | done | failed | cancelled
|
||||
created_at INTEGER NOT NULL,
|
||||
done_at INTEGER,
|
||||
error TEXT
|
||||
);
|
||||
CREATE INDEX events_due ON events(status, due_at, id);
|
||||
CREATE INDEX events_town ON events(town_id, status);
|
||||
|
||||
-- Written by event handlers so APNs/FCM push can be added later without touching game logic.
|
||||
CREATE TABLE notifications (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||
world_id INTEGER,
|
||||
type TEXT NOT NULL,
|
||||
payload TEXT NOT NULL DEFAULT '{}',
|
||||
created_at INTEGER NOT NULL,
|
||||
read_at INTEGER
|
||||
);
|
||||
CREATE INDEX notifications_user ON notifications(user_id, id);
|
||||
|
||||
-- Idempotency-Key replay store for mutating POSTs.
|
||||
CREATE TABLE idempotency (
|
||||
user_id INTEGER NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
request TEXT NOT NULL,
|
||||
status INTEGER NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (user_id, key)
|
||||
);
|
||||
274
server/net.js
Normal file
274
server/net.js
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Networking helpers: client IP / reverse-proxy awareness, Origin check, token bucket,
|
||||
* dual-stack listen and the "what URLs can I open" list for the start-up banner.
|
||||
* No dependencies beyond Node core.
|
||||
*/
|
||||
const net = require('net');
|
||||
const os = require('os');
|
||||
const { performance } = require('perf_hooks');
|
||||
|
||||
// ---------------------------------------------------------------- addresses
|
||||
// "::ffff:1.2.3.4" -> "1.2.3.4"; strips an IPv6 zone ("fe80::1%eth0"); lower-cases.
|
||||
function normalizeIp(addr) {
|
||||
if (typeof addr !== 'string') return '';
|
||||
let a = addr.trim().toLowerCase();
|
||||
const z = a.indexOf('%');
|
||||
if (z >= 0) a = a.slice(0, z);
|
||||
if (a.startsWith('::ffff:') && net.isIPv4(a.slice(7))) a = a.slice(7);
|
||||
return a;
|
||||
}
|
||||
|
||||
// Loopback, RFC1918, link-local, unique-local (fc00::/7) and the unspecified address.
|
||||
function isPrivateIp(addr) {
|
||||
const ip = normalizeIp(addr);
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number);
|
||||
return a === 127 || a === 10 || a === 0 ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 169 && b === 254);
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
if (ip === '::1' || ip === '::') return true;
|
||||
const first = ip.startsWith('::') ? 0 : parseInt(ip.split(':')[0], 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 'auto' | true | false, also from env-style strings ('1', '0', 'true', 'off' ...).
|
||||
function parseTrustProxy(v) {
|
||||
if (v === undefined || v === null || v === '') return 'auto';
|
||||
if (v === true || v === false) return v;
|
||||
if (typeof v === 'number') return v !== 0;
|
||||
const s = String(v).trim().toLowerCase();
|
||||
if (s === 'auto') return 'auto';
|
||||
if (['1', 'true', 'yes', 'on'].includes(s)) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(s)) return false;
|
||||
throw new Error('invalid trustProxy value: ' + JSON.stringify(v) + " (use 'auto', '1' or '0')");
|
||||
}
|
||||
|
||||
function peerIp(req) {
|
||||
return normalizeIp(req.socket && req.socket.remoteAddress) || 'unknown';
|
||||
}
|
||||
|
||||
// TRUSTED_PROXIES: extra proxy addresses believed under TRUST_PROXY=auto, on top of the private ranges. The built-in
|
||||
// "private" list misses a proxy that reaches the game over a global IPv6 address, Tailscale / CGNAT (100.64.0.0/10) or
|
||||
// any other routable address. Accepts an array or a comma separated string of IPs and CIDRs, IPv4 or IPv6
|
||||
// ("100.64.0.0/10, 2001:db8::6, 2001:db8:1::/48"). Returns null for an empty list, throws on a malformed entry (a
|
||||
// typo must stop the start-up, not silently leave the proxy untrusted). The result has .has(ip) and .list.
|
||||
function parseTrustedProxies(v) {
|
||||
const items = Array.isArray(v) ? v : String(v === undefined || v === null ? '' : v).split(',');
|
||||
const list = items.map((s) => String(s).trim()).filter(Boolean);
|
||||
if (!list.length) return null;
|
||||
const bl = new net.BlockList();
|
||||
for (const item of list) {
|
||||
const slash = item.indexOf('/');
|
||||
const addr = normalizeIp(slash < 0 ? item : item.slice(0, slash));
|
||||
const type = net.isIPv4(addr) ? 'ipv4' : net.isIPv6(addr) ? 'ipv6' : null;
|
||||
const max = type === 'ipv4' ? 32 : 128;
|
||||
const prefixText = slash < 0 ? null : item.slice(slash + 1);
|
||||
const prefix = prefixText === null ? max : (/^\d{1,3}$/.test(prefixText) ? Number(prefixText) : NaN);
|
||||
if (!type || !(prefix >= 0 && prefix <= max) ||
|
||||
(item.startsWith('::ffff:') && slash >= 0)) { // a v4-mapped prefix would need its own arithmetic: write the IPv4 form
|
||||
throw new Error('invalid TRUSTED_PROXIES entry ' + JSON.stringify(item) + ' (use an IP or CIDR such as 100.64.0.0/10 or 2001:db8::6)');
|
||||
}
|
||||
if (prefixText === null) bl.addAddress(addr, type); else bl.addSubnet(addr, prefix, type);
|
||||
}
|
||||
return {
|
||||
list,
|
||||
has(ip) {
|
||||
const a = normalizeIp(ip);
|
||||
return net.isIPv4(a) ? bl.check(a, 'ipv4') : net.isIPv6(a) ? bl.check(a, 'ipv6') : false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Does this request come from a proxy whose X-Forwarded-* headers we believe? `trusted` = parseTrustedProxies() result.
|
||||
function isTrustedPeer(req, trustProxy, trusted) {
|
||||
if (trustProxy === true) return true;
|
||||
if (trustProxy === false) return false;
|
||||
const ip = peerIp(req);
|
||||
return isPrivateIp(ip) || !!(trusted && trusted.has(ip));
|
||||
}
|
||||
|
||||
// One entry of a forwarding header ("203.0.113.9", "[2001:db8::5]:443", "1.2.3.4:5555") -> bare IP or null.
|
||||
function parseForwardedEntry(raw) {
|
||||
let a = String(raw).trim();
|
||||
if (!a) return null;
|
||||
if (a[0] === '[') { const e = a.indexOf(']'); if (e < 0) return null; a = a.slice(1, e); }
|
||||
else if (/^\d+\.\d+\.\d+\.\d+:\d+$/.test(a)) a = a.slice(0, a.lastIndexOf(':'));
|
||||
a = normalizeIp(a);
|
||||
return net.isIP(a) ? a : null;
|
||||
}
|
||||
|
||||
// First address of a header value like "203.0.113.9, 10.0.0.2" (used for X-Real-IP, which holds one address).
|
||||
function firstForwardedIp(value) {
|
||||
return typeof value === 'string' ? parseForwardedEntry(value.split(',')[0]) : null;
|
||||
}
|
||||
|
||||
// The client address in an X-Forwarded-For built by proxies that APPEND (nginx $proxy_add_x_forwarded_for, which is
|
||||
// what nginx Proxy Manager does): everything left of the proxy's own entry is whatever the client chose to send, so
|
||||
// the first entry is forgeable (it lets a client dodge the per-IP cap or use up somebody else's). Walk from the
|
||||
// right instead, skip the private addresses of our own proxy hops and take the first public one. A chain that is
|
||||
// private all the way (LAN clients) yields its rightmost entry, i.e. what the nearest proxy saw; junk -> null.
|
||||
function forwardedClientIp(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const parts = value.split(',');
|
||||
let nearest = null;
|
||||
for (let i = parts.length - 1; i >= 0; i--) {
|
||||
const ip = parseForwardedEntry(parts[i]);
|
||||
if (!ip) return nearest;
|
||||
if (!isPrivateIp(ip)) return ip;
|
||||
if (!nearest) nearest = ip;
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
// The address used for logging and the per-IP socket cap.
|
||||
function clientIp(req, trustProxy, trusted) {
|
||||
const peer = peerIp(req);
|
||||
if (!isTrustedPeer(req, trustProxy, trusted)) return peer;
|
||||
return forwardedClientIp(req.headers['x-forwarded-for']) ||
|
||||
firstForwardedIp(req.headers['x-real-ip']) || peer;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Origin check
|
||||
// Scheme-less, lower-case host name and port of a bare host ("Game.Example.com:443"), a Host header or a full origin
|
||||
// ("https://x.example"): { name, port }, with port '' for none or for the default ports 80 / 443. null if unusable.
|
||||
function hostParts(s) {
|
||||
if (typeof s !== 'string') return null;
|
||||
let v = s.trim();
|
||||
if (!v) return null;
|
||||
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) {
|
||||
if (!/^[a-z0-9._:\[\]-]+$/i.test(v)) return null; // a bare host[:port], nothing else
|
||||
v = 'http://' + v;
|
||||
}
|
||||
let u;
|
||||
try { u = new URL(v); } catch (e) { return null; }
|
||||
if (!u.hostname) return null;
|
||||
const port = u.port; // '' for the scheme's own default
|
||||
return { name: u.hostname.toLowerCase(), port: port && port !== '80' && port !== '443' ? port : '' }; // IPv6 keeps its brackets
|
||||
}
|
||||
|
||||
// "host[:port]" form of hostParts().
|
||||
function normalizeHost(s) {
|
||||
const p = hostParts(s);
|
||||
return p ? (p.port ? p.name + ':' + p.port : p.name) : null;
|
||||
}
|
||||
|
||||
// Returns true when a WebSocket upgrade with this Origin may proceed.
|
||||
// no Origin header -> true (non-browser clients)
|
||||
// Origin host == Host -> true
|
||||
// Origin host == X-Forwarded-Host (first) -> true, only when the peer is a trusted proxy
|
||||
// Origin host name == Host name, Host without a port -> true, only when the peer is a trusted proxy (see below)
|
||||
// Origin host in allowedOrigins -> true
|
||||
// opts: { trustProxy, trustedProxies (parseTrustedProxies() result), allowedOrigins }.
|
||||
function originAllowed(req, opts) {
|
||||
const origin = req.headers.origin;
|
||||
if (origin === undefined) return true;
|
||||
const o = (typeof origin === 'string' && origin.toLowerCase() !== 'null' && /^[a-z][a-z0-9+.-]*:\/\//i.test(origin))
|
||||
? hostParts(origin) : null;
|
||||
if (!o) return false;
|
||||
const h = hostParts(req.headers.host);
|
||||
if (h && o.name === h.name && o.port === h.port) return true;
|
||||
if (isTrustedPeer(req, opts.trustProxy, opts.trustedProxies)) {
|
||||
const xfh = req.headers['x-forwarded-host'];
|
||||
if (typeof xfh === 'string' && normalizeHost(xfh.split(',')[0]) === normalizeHost(origin)) return true;
|
||||
// Published on a port other than 80/443 (https://game.example.com:8443) behind nginx / nginx Proxy Manager: their
|
||||
// "proxy_set_header Host $host" drops the port, so Host is "game.example.com" while the browser's Origin keeps
|
||||
// ":8443", and neither the X-Forwarded-Host nor an ALLOWED_ORIGINS entry written without the port helps. A browser that
|
||||
// talks to this server directly on its port (8080 by default, never 80/443 unless you chose that) puts the port in
|
||||
// Host, so a Host WITHOUT one from a trusted proxy is what a stripped port looks like: accept the same host name on
|
||||
// any port. Another name still fails.
|
||||
if (h && !h.port && o.name === h.name) return true;
|
||||
}
|
||||
const on = normalizeHost(origin);
|
||||
for (const a of opts.allowedOrigins || []) if (on === normalizeHost(a)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- token bucket
|
||||
class TokenBucket {
|
||||
constructor(ratePerSec, burst) {
|
||||
this.rate = ratePerSec; this.burst = burst;
|
||||
this.tokens = burst; this.last = performance.now();
|
||||
}
|
||||
// true when the event is allowed. `now` (ms) defaults to a monotonic clock: with Date.now() a wall-clock step
|
||||
// backwards (NTP, a VM resume) would stop the refill for as long as the step is large and get sockets closed 4429.
|
||||
take(now) {
|
||||
now = now === undefined ? performance.now() : now;
|
||||
const dt = now - this.last;
|
||||
if (dt > 0) { this.tokens = Math.min(this.burst, this.tokens + dt * this.rate / 1000); this.last = now; }
|
||||
if (this.tokens < 1) return false;
|
||||
this.tokens -= 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- listen
|
||||
const V6_FALLBACK_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EPROTONOSUPPORT', 'ENOTSUP', 'EINVAL', 'ENOPROTOOPT', 'EPFNOSUPPORT']);
|
||||
|
||||
function listenOnce(server, opts) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (err) => { server.removeListener('listening', onListening); reject(err); };
|
||||
const onListening = () => { server.removeListener('error', onError); resolve(); };
|
||||
server.once('error', onError);
|
||||
server.once('listening', onListening);
|
||||
try { server.listen(opts); } catch (err) { onError(err); }
|
||||
});
|
||||
}
|
||||
|
||||
// Binds `host`. The default '::' is bound dual-stack (ipv6Only:false: one socket for IPv4 and IPv6);
|
||||
// if IPv6 is unavailable (EAFNOSUPPORT, EADDRNOTAVAIL, ...) it falls back to 0.0.0.0. Any other host is
|
||||
// used as given, and any other failure (EADDRINUSE, EACCES) is rejected, never papered over.
|
||||
// Resolves to the host that ended up bound.
|
||||
async function listenDual(server, port, host, log) {
|
||||
if (host !== '::') { await listenOnce(server, { port, host }); return host; }
|
||||
try {
|
||||
await listenOnce(server, { port, host: '::', ipv6Only: false });
|
||||
return '::';
|
||||
} catch (err) {
|
||||
if (!err || !V6_FALLBACK_CODES.has(err.code)) throw err;
|
||||
if (log) log('IPv6 is not available (' + err.code + '); falling back to 0.0.0.0 (IPv4 only)');
|
||||
await listenOnce(server, { port, host: '0.0.0.0' });
|
||||
return '0.0.0.0';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- start-up banner
|
||||
function fmtUrl(host, port) {
|
||||
return 'http://' + (host.includes(':') ? '[' + host + ']' : host) + ':' + port + '/';
|
||||
}
|
||||
|
||||
// os.networkInterfaces() throws in some sandboxes (seccomp / RestrictAddressFamilies without AF_NETLINK, certain
|
||||
// containers). The banner is cosmetic, so that must never stop a server that is already listening.
|
||||
function interfaces() {
|
||||
try { return os.networkInterfaces(); } catch (e) { return {}; }
|
||||
}
|
||||
|
||||
// URLs worth printing for a server bound to `bound` on `port`.
|
||||
function listUrls(bound, port, ifaces) {
|
||||
const out = ['http://localhost:' + port + '/'];
|
||||
if (bound !== '::' && bound !== '0.0.0.0') {
|
||||
if (bound !== '127.0.0.1' && bound !== '::1') out.push(fmtUrl(bound, port));
|
||||
return out;
|
||||
}
|
||||
ifaces = ifaces || interfaces();
|
||||
for (const name of Object.keys(ifaces)) {
|
||||
for (const a of ifaces[name] || []) {
|
||||
if (a.internal) continue;
|
||||
const v4 = a.family === 'IPv4' || a.family === 4;
|
||||
if (v4) out.push(fmtUrl(a.address, port));
|
||||
else if (bound === '::' && !/^fe80:/i.test(a.address)) out.push(fmtUrl(a.address.split('%')[0], port));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeIp, isPrivateIp, parseTrustProxy, parseTrustedProxies, peerIp, isTrustedPeer, firstForwardedIp, forwardedClientIp, clientIp,
|
||||
hostParts, normalizeHost, originAllowed, TokenBucket, listenDual, listUrls, fmtUrl,
|
||||
};
|
||||
116
server/queries.js
Normal file
116
server/queries.js
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Read models. Every read first catches the event queue up to now, so what a player sees is never stale by an
|
||||
* overdue event. Reads never write (settling is only done by commands and events).
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const { loadWorld, townFromRow, pendingBuilds } = require('./state');
|
||||
|
||||
function createQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
|
||||
function worldView(w) {
|
||||
return { id: w.id, name: w.name, speed: w.speed, mapRadius: w.map_radius, seed: w.seed, startAt: w.start_at, endAt: w.end_at, status: w.status, preset: w.preset };
|
||||
}
|
||||
|
||||
function me(userId) {
|
||||
const now = fresh();
|
||||
const user = db.get('SELECT id, username, created_at FROM users WHERE id = ?', userId);
|
||||
if (!user) throw new GameError('unauthorized');
|
||||
const operators = db.all('SELECT * FROM operators WHERE user_id = ? ORDER BY id', userId).map((o) => {
|
||||
const world = loadWorld(db, o.world_id);
|
||||
const towns = db.all('SELECT id, name, x, y, is_capital FROM towns WHERE owner_id = ? ORDER BY id', o.id)
|
||||
.map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital }));
|
||||
return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protectionUntil: o.protection_until, world: worldView(world), towns };
|
||||
});
|
||||
return { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators };
|
||||
}
|
||||
|
||||
function planView(p) {
|
||||
return { ok: p.ok, code: p.ok ? null : p.code, toLevel: p.toLevel, cost: p.cost, durationMs: p.durationMs, missing: p.missing || [] };
|
||||
}
|
||||
|
||||
// Full POP state for its owner.
|
||||
function town(userId, townId) {
|
||||
const now = fresh();
|
||||
const row = db.get('SELECT t.* FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ? AND o.user_id = ?', townId, userId);
|
||||
if (!row) throw new GameError('not_found', { what: 'town' });
|
||||
const world = loadWorld(db, row.world_id);
|
||||
const t = townFromRow(db, row, world);
|
||||
const pending = pendingBuilds(db, t.id);
|
||||
const cur = R.resourcesAt(t, now);
|
||||
const rates = cur.rates;
|
||||
const resources = {};
|
||||
for (const r of D.RESOURCES) resources[r] = { amount: cur.amounts[r], rate: rates[r], cap: cur.caps[r] };
|
||||
const power = { out: rates.powerOut, draw: rates.powerDraw, net: rates.powerNet, buffer: cur.amounts.battery, bufferCap: cur.caps.battery, bufferRate: rates.powerNet * world.speed, online: R.unitsOnline(t, now) };
|
||||
|
||||
const buildings = [];
|
||||
const entry = (key, type, level) => {
|
||||
const plan = R.buildPlan(t, key, now, pending);
|
||||
const def = D.BUILDINGS[type];
|
||||
buildings.push({ key, type, kind: def.kind, level, maxLevel: def.maxLevel, next: planView(plan) });
|
||||
};
|
||||
for (let i = 1; i <= D.FIELD_SLOTS; i++) { const k = 'f' + i; if (t.buildings[k]) entry(k, t.buildings[k].type, t.buildings[k].level); }
|
||||
for (const type of Object.keys(D.BUILDINGS)) {
|
||||
const def = D.BUILDINGS[type];
|
||||
if (def.kind !== 'infra') continue;
|
||||
if (def.special && !t.buildings[type]) continue;
|
||||
entry(type, type, t.buildings[type] ? t.buildings[type].level : 0);
|
||||
}
|
||||
const queue = pending.map((p) => ({ id: p.id, key: p.key, type: p.type, toLevel: p.toLevel, startedAt: p.startedAt, dueAt: p.dueAt }));
|
||||
const loyalty = R.loyaltyAt(t.loyalty, t.loyaltyAt, now, world.speed);
|
||||
return {
|
||||
serverTime: now,
|
||||
town: {
|
||||
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: t.isCapital, ownerId: t.ownerId, worldId: t.worldId,
|
||||
loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t),
|
||||
resources, power, buildings, queue, queueSlots: R.queueSlots(t),
|
||||
bonus: t.bonus,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Map viewport: everything non-trivial inside the square (x±r, y±r). Land tiles are implied (not listed).
|
||||
function map(userId, { worldId, x, y, r }) {
|
||||
const now = fresh();
|
||||
let world;
|
||||
if (worldId !== undefined) world = loadWorld(db, worldId);
|
||||
else {
|
||||
const op = db.get('SELECT world_id FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
|
||||
world = op ? loadWorld(db, op.world_id) : null;
|
||||
}
|
||||
if (!world) throw new GameError('not_found', { what: 'world' });
|
||||
if (!db.get('SELECT 1 AS x FROM operators WHERE user_id = ? AND world_id = ?', userId, world.id)) throw new GameError('not_found', { what: 'world' });
|
||||
const rad = world.map_radius;
|
||||
r = Math.min(r, 40);
|
||||
const x0 = Math.max(-rad, x - r), x1 = Math.min(rad, x + r), y0 = Math.max(-rad, y - r), y1 = Math.min(rad, y + r);
|
||||
const specials = [];
|
||||
for (let yy = y0; yy <= y1; yy++) {
|
||||
for (let xx = x0; xx <= x1; xx++) {
|
||||
const t = R.tileAt(world.seed, rad, xx, yy);
|
||||
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
|
||||
}
|
||||
}
|
||||
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, o.protection_until AS prot
|
||||
FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`,
|
||||
world.id, x0, x1, y0, y1).map((t) => ({
|
||||
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital,
|
||||
owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, protected: t.prot > now },
|
||||
}));
|
||||
return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns };
|
||||
}
|
||||
|
||||
function notifications(userId, { after, limit }) {
|
||||
const now = fresh();
|
||||
const rows = db.all('SELECT id, type, payload, created_at, read_at, world_id FROM notifications WHERE user_id = ? AND id > ? ORDER BY id LIMIT ?', userId, after || 0, (limit || 50) + 1);
|
||||
const more = rows.length > (limit || 50);
|
||||
const items = rows.slice(0, limit || 50).map((n) => ({ id: n.id, type: n.type, worldId: n.world_id, payload: JSON.parse(n.payload), createdAt: n.created_at, readAt: n.read_at }));
|
||||
return { serverTime: now, items, next: more ? items[items.length - 1].id : null };
|
||||
}
|
||||
|
||||
return { me, town, map, notifications, worldView };
|
||||
}
|
||||
|
||||
module.exports = { createQueries };
|
||||
61
server/routes/auth.js
Normal file
61
server/routes/auth.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
'use strict';
|
||||
const { GameError } = require('../errors');
|
||||
const { reply } = require('../http');
|
||||
const { sha256, newToken, hashPassword, verifyPassword } = require('../auth');
|
||||
|
||||
function register(router, { db, clock, commands, queries, auth, opts }) {
|
||||
const creds = {
|
||||
username: { type: 'string', minLength: 3, maxLength: 20, pattern: '^[A-Za-z0-9_-]+$' },
|
||||
password: { type: 'string', minLength: 8, maxLength: 128 },
|
||||
device: { type: 'string', maxLength: 40 },
|
||||
};
|
||||
|
||||
router.post('/auth/signup', {
|
||||
summary: 'Create an account, join the world and get a bearer token', tag: 'auth', auth: false, limit: 'auth',
|
||||
body: { type: 'object', required: ['username', 'password'], properties: Object.assign({ invite: { type: 'string', maxLength: 64 }, worldId: { type: 'integer', minimum: 1 } }, creds) },
|
||||
response: { $ref: 'AuthResult' }, status: 201, errors: ['validation_failed', 'username_taken', 'signup_closed', 'world_full', 'rate_limited'],
|
||||
}, async ({ body }) => {
|
||||
if (opts.signupCode && body.invite !== opts.signupCode) throw new GameError('signup_closed');
|
||||
const passHash = await hashPassword(body.password);
|
||||
const token = newToken();
|
||||
const r = commands.run('signup', { username: body.username, passHash, tokenHash: sha256(token), device: body.device, worldId: body.worldId });
|
||||
const me = queries.me(r.userId);
|
||||
return reply(201, { token, tokenId: r.tokenId, user: { id: r.userId, username: body.username }, operators: me.operators });
|
||||
});
|
||||
|
||||
router.post('/auth/login', {
|
||||
summary: 'Log in on a device and get a bearer token', tag: 'auth', auth: false, limit: 'auth',
|
||||
body: { type: 'object', required: ['username', 'password'], properties: creds },
|
||||
response: { $ref: 'AuthResult' }, errors: ['validation_failed', 'invalid_credentials', 'forbidden', 'rate_limited'],
|
||||
}, async ({ body }) => {
|
||||
const u = db.get('SELECT id, username, pass_hash, banned FROM users WHERE username = ?', body.username);
|
||||
const ok = await verifyPassword(body.password, u && u.pass_hash);
|
||||
if (!u || !ok) throw new GameError('invalid_credentials');
|
||||
if (u.banned) throw new GameError('forbidden');
|
||||
const { token, tokenId } = auth.issueToken(u.id, body.device, clock.now());
|
||||
return { token, tokenId, user: { id: u.id, username: u.username }, operators: queries.me(u.id).operators };
|
||||
});
|
||||
|
||||
router.post('/auth/logout', { summary: 'Revoke the token used for this request', tag: 'auth', response: { $ref: 'Ok' }, errors: ['unauthorized'] },
|
||||
({ user, tokenId }) => {
|
||||
db.run('UPDATE tokens SET revoked_at = ? WHERE id = ? AND user_id = ?', clock.now(), tokenId, user.id);
|
||||
return {};
|
||||
});
|
||||
|
||||
router.get('/auth/tokens', {
|
||||
summary: 'List this account\'s active device tokens', tag: 'auth',
|
||||
response: { type: 'object', required: ['serverTime', 'tokens'], properties: { serverTime: { type: 'integer' }, tokens: { type: 'array', items: { $ref: 'Token' } } } }, errors: ['unauthorized'],
|
||||
}, ({ user, tokenId }) => ({
|
||||
tokens: db.all('SELECT id, device, created_at, last_used_at FROM tokens WHERE user_id = ? AND revoked_at IS NULL ORDER BY id', user.id)
|
||||
.map((t) => ({ id: t.id, device: t.device, createdAt: t.created_at, lastUsedAt: t.last_used_at, current: t.id === tokenId })),
|
||||
}));
|
||||
|
||||
router.del('/auth/tokens/:tokenId', { summary: 'Revoke one of this account\'s tokens', tag: 'auth', response: { $ref: 'Ok' }, errors: ['unauthorized', 'not_found'] },
|
||||
({ user, params }) => {
|
||||
const r = db.run('UPDATE tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL', clock.now(), params.tokenId, user.id);
|
||||
if (!r.changes) throw new GameError('not_found', { what: 'token' });
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { register };
|
||||
9
server/routes/index.js
Normal file
9
server/routes/index.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
'use strict';
|
||||
/* Registers every REST route. One file per resource; each exports register(router, services). */
|
||||
const files = [require('./auth'), require('./me'), require('./towns'), require('./map')];
|
||||
|
||||
function register(router, services) {
|
||||
for (const f of files) f.register(router, services);
|
||||
}
|
||||
|
||||
module.exports = { register };
|
||||
9
server/routes/map.js
Normal file
9
server/routes/map.js
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
'use strict';
|
||||
function register(router, { queries }) {
|
||||
router.get('/map', {
|
||||
summary: 'Map viewport: rural areas, incumbent sites and POPs within (x±r, y±r); land tiles are implied', tag: 'map',
|
||||
query: { type: 'object', required: ['x', 'y', 'r'], properties: { x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, r: { type: 'integer', minimum: 1, maximum: 40 }, worldId: { type: 'integer', minimum: 1 } } },
|
||||
response: { $ref: 'MapResponse' }, errors: ['unauthorized', 'validation_failed', 'not_found'],
|
||||
}, ({ user, query }) => queries.map(user.id, { worldId: query.worldId, x: query.x, y: query.y, r: query.r }));
|
||||
}
|
||||
module.exports = { register };
|
||||
12
server/routes/me.js
Normal file
12
server/routes/me.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
'use strict';
|
||||
function register(router, { queries }) {
|
||||
router.get('/me', { summary: 'The current user, their operators and POPs', tag: 'me', response: { $ref: 'Me' }, errors: ['unauthorized'] },
|
||||
({ user }) => queries.me(user.id));
|
||||
|
||||
router.get('/notifications', {
|
||||
summary: 'Notifications for this user (cursor: after = last seen id)', tag: 'me',
|
||||
query: { type: 'object', properties: { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } } },
|
||||
response: { $ref: 'NotificationList' }, errors: ['unauthorized', 'validation_failed'],
|
||||
}, ({ user, query }) => queries.notifications(user.id, query));
|
||||
}
|
||||
module.exports = { register };
|
||||
43
server/routes/schemas.js
Normal file
43
server/routes/schemas.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
'use strict';
|
||||
/* Shared response schemas (JSON-schema subset), referenced from route meta as { $ref: 'Name' } and emitted into
|
||||
* openapi.json components. Responses are documentation (and checked by test/api-contract.test.js), not enforced at runtime. */
|
||||
const int = { type: 'integer' };
|
||||
const num = { type: 'number' };
|
||||
const str = { type: 'string' };
|
||||
const bool = { type: 'boolean' };
|
||||
const obj = (properties, required) => ({ type: 'object', properties, required: required || Object.keys(properties), additionalProperties: true });
|
||||
const arr = (items) => ({ type: 'array', items });
|
||||
|
||||
const Cost = obj({ fiber: int, hardware: int, capital: int });
|
||||
|
||||
const schemas = {
|
||||
Cost,
|
||||
Error: obj({ serverTime: int, error: obj({ code: str, message: str, details: { type: 'object', additionalProperties: true } }) }),
|
||||
World: obj({ id: int, name: str, speed: num, mapRadius: int, seed: int, startAt: int, endAt: { type: ['integer', 'null'] }, status: str, preset: str }),
|
||||
TownSummary: obj({ id: int, name: str, x: int, y: int, isCapital: bool }),
|
||||
Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }),
|
||||
Me: obj({ serverTime: int, user: obj({ id: int, username: str, createdAt: int }), operators: arr({ $ref: 'Operator' }) }),
|
||||
AuthResult: obj({ serverTime: int, token: str, tokenId: int, user: obj({ id: int, username: str }), operators: arr({ $ref: 'Operator' }) }),
|
||||
Token: obj({ id: int, device: str, createdAt: int, lastUsedAt: int, current: bool }),
|
||||
BuildPlan: obj({ ok: bool, code: { type: ['string', 'null'] }, toLevel: int, cost: { $ref: 'Cost' }, durationMs: int, missing: arr(obj({ type: str, level: int, have: int })) }, ['ok', 'code', 'toLevel']),
|
||||
BuildingView: obj({ key: str, type: str, kind: str, level: int, maxLevel: int, next: { $ref: 'BuildPlan' } }),
|
||||
QueueEntry: obj({ id: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int }),
|
||||
ResourceView: obj({ amount: num, rate: num, cap: num }),
|
||||
Town: obj({
|
||||
id: int, name: str, x: int, y: int, isCapital: bool, ownerId: int, worldId: int, loyalty: num, footprint: num, footprintPerDay: num,
|
||||
resources: obj({ fiber: { $ref: 'ResourceView' }, hardware: { $ref: 'ResourceView' }, capital: { $ref: 'ResourceView' } }),
|
||||
power: obj({ out: num, draw: num, net: num, buffer: num, bufferCap: num, bufferRate: num, online: bool }),
|
||||
buildings: arr({ $ref: 'BuildingView' }), queue: arr({ $ref: 'QueueEntry' }), queueSlots: int,
|
||||
bonus: obj({ fiber: num, hardware: num, capital: num }),
|
||||
}),
|
||||
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
|
||||
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protected: bool }) }),
|
||||
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }),
|
||||
MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }),
|
||||
BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }),
|
||||
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
|
||||
NotificationList: obj({ serverTime: int, items: arr({ $ref: 'Notification' }), next: { type: ['integer', 'null'] } }),
|
||||
Ok: obj({ serverTime: int }),
|
||||
};
|
||||
|
||||
module.exports = { schemas, int, num, str, bool, obj, arr };
|
||||
27
server/routes/towns.js
Normal file
27
server/routes/towns.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
'use strict';
|
||||
const { reply } = require('../http');
|
||||
|
||||
function register(router, { queries, commands }) {
|
||||
const errs = ['unauthorized', 'not_found'];
|
||||
|
||||
router.get('/towns/:id', { summary: 'Full state of one of your POPs: resources, power, buildings, build queue', tag: 'towns', response: { $ref: 'TownResponse' }, errors: errs },
|
||||
({ user, params }) => queries.town(user.id, params.id));
|
||||
|
||||
router.post('/towns/:id/build', {
|
||||
summary: 'Build or upgrade a building (fields f1..f18 or an infrastructure building type) by one level', tag: 'towns',
|
||||
body: { type: 'object', required: ['key'], properties: { key: { type: 'string', maxLength: 32, pattern: '^[a-z0-9_]+$' } } },
|
||||
response: { $ref: 'BuildResult' }, status: 201,
|
||||
errors: errs.concat(['validation_failed', 'unknown_building', 'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources']),
|
||||
}, ({ user, params, body }) => {
|
||||
return reply(201, commands.run('build', { userId: user.id, townId: params.id, key: body.key }));
|
||||
});
|
||||
|
||||
router.del('/towns/:id/queue/:eventId', { summary: 'Cancel a running build and get 80% of its cost back', tag: 'towns', response: { $ref: 'Ok' }, errors: errs },
|
||||
({ user, params }) => { commands.run('cancelBuild', { userId: user.id, townId: params.id, eventId: params.eventId }); return {}; });
|
||||
|
||||
router.post('/towns/:id/rename', {
|
||||
summary: 'Rename a POP', tag: 'towns', body: { type: 'object', required: ['name'], properties: { name: { type: 'string', minLength: 2, maxLength: 40 } } },
|
||||
response: { type: 'object', required: ['serverTime', 'name'], properties: { serverTime: { type: 'integer' }, name: { type: 'string' } } }, errors: errs.concat(['validation_failed']),
|
||||
}, ({ user, params, body }) => commands.run('renameTown', { userId: user.id, townId: params.id, name: body.name }));
|
||||
}
|
||||
module.exports = { register };
|
||||
95
server/scheduler.js
Normal file
95
server/scheduler.js
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Persistent event queue. There is no tick loop: one timer points at the next due event, and after a restart every
|
||||
* overdue event is caught up in order before traffic is accepted.
|
||||
*
|
||||
* Rules (CLAUDE.md "Time model"):
|
||||
* - events are processed strictly in (due_at, id) order
|
||||
* - each event runs in ONE transaction: handler + mark done. A handler that throws rolls back and the event is
|
||||
* marked failed (never retried in a loop, never blocks the queue)
|
||||
* - handlers must be idempotent; they receive the event's own due_at as the time to settle towns to
|
||||
* - before any command or read touches a town, runDue() processes everything due up to `now`
|
||||
*/
|
||||
const MAX_TIMER_MS = 30 * 1000; // re-check at least this often (setTimeout cannot do more than ~24 days anyway)
|
||||
|
||||
class Scheduler {
|
||||
// handlers: { [type]: (ctx, event) => void }; ctx = { db, clock, now, enqueue, notify, log }
|
||||
constructor({ db, clock, handlers, log, autoArm }) {
|
||||
this.db = db; this.clock = clock; this.handlers = handlers || {}; this.log = log || (() => {});
|
||||
this.autoArm = autoArm !== false;
|
||||
this.timer = null; this.running = false; this.closed = false;
|
||||
this.onEvent = null; // optional hook: (event) => void after each processed event (push, tests)
|
||||
}
|
||||
|
||||
register(type, fn) { this.handlers[type] = fn; }
|
||||
|
||||
// Insert an event. Call inside a transaction together with the state change it belongs to.
|
||||
enqueue({ worldId, dueAt, type, townId, payload }) {
|
||||
const r = this.db.run('INSERT INTO events (world_id, due_at, type, town_id, payload, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
worldId, Math.round(dueAt), type, townId === undefined ? null : townId, JSON.stringify(payload || {}), 'pending', this.clock.now());
|
||||
return Number(r.lastInsertRowid);
|
||||
}
|
||||
|
||||
notify(userId, worldId, type, payload) {
|
||||
this.db.run('INSERT INTO notifications (user_id, world_id, type, payload, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
userId, worldId === undefined ? null : worldId, type, JSON.stringify(payload || {}), this.clock.now());
|
||||
}
|
||||
|
||||
next() { return this.db.get("SELECT id, due_at FROM events WHERE status = 'pending' ORDER BY due_at, id LIMIT 1"); }
|
||||
|
||||
// Process every pending event with due_at <= now, in order, including follow-ups that are also already due.
|
||||
// Returns the number processed. Reentrancy-safe: a handler cannot start a nested run.
|
||||
runDue(now) {
|
||||
if (this.running) return 0;
|
||||
this.running = true;
|
||||
let n = 0;
|
||||
try {
|
||||
now = now === undefined ? this.clock.now() : now;
|
||||
for (;;) {
|
||||
const ev = this.db.get("SELECT * FROM events WHERE status = 'pending' AND due_at <= ? ORDER BY due_at, id LIMIT 1", now);
|
||||
if (!ev) break;
|
||||
this.process(ev);
|
||||
n++;
|
||||
}
|
||||
} finally { this.running = false; }
|
||||
return n;
|
||||
}
|
||||
|
||||
process(ev) {
|
||||
const handler = this.handlers[ev.type];
|
||||
const event = { id: ev.id, worldId: ev.world_id, dueAt: ev.due_at, type: ev.type, townId: ev.town_id, payload: JSON.parse(ev.payload) };
|
||||
try {
|
||||
this.db.tx(() => {
|
||||
if (!handler) throw new Error('no handler for event type ' + ev.type);
|
||||
handler({ db: this.db, clock: this.clock, now: ev.due_at, enqueue: (e) => this.enqueue(e), notify: (u, w, t, p) => this.notify(u, w, t, p), log: this.log, scheduler: this }, event);
|
||||
this.db.run("UPDATE events SET status = 'done', done_at = ? WHERE id = ?", this.clock.now(), ev.id);
|
||||
});
|
||||
} catch (err) {
|
||||
this.log('event ' + ev.id + ' (' + ev.type + ') failed: ' + (err && err.stack || err));
|
||||
this.db.run("UPDATE events SET status = 'failed', done_at = ?, error = ? WHERE id = ?", this.clock.now(), String(err && err.message || err).slice(0, 500), ev.id);
|
||||
return;
|
||||
}
|
||||
if (this.onEvent) { try { this.onEvent(event); } catch (e) { this.log('onEvent hook failed: ' + e.message); } }
|
||||
}
|
||||
|
||||
// After a restart: process everything overdue, in order, before accepting traffic.
|
||||
catchUp() { return this.runDue(); }
|
||||
|
||||
// Point the single timer at the next due event (or re-check soon). Safe to call after every mutation.
|
||||
arm() {
|
||||
if (!this.autoArm || this.closed) return;
|
||||
if (this.timer) { clearTimeout(this.timer); this.timer = null; }
|
||||
const nx = this.next();
|
||||
const wait = nx ? Math.min(MAX_TIMER_MS, Math.max(0, nx.due_at - this.clock.now())) : MAX_TIMER_MS;
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
try { this.runDue(); } catch (err) { this.log('scheduler run failed: ' + (err && err.stack || err)); }
|
||||
this.arm();
|
||||
}, wait + 5);
|
||||
if (this.timer.unref) this.timer.unref();
|
||||
}
|
||||
|
||||
stop() { this.closed = true; if (this.timer) clearTimeout(this.timer); this.timer = null; }
|
||||
}
|
||||
|
||||
module.exports = { Scheduler };
|
||||
78
server/state.js
Normal file
78
server/state.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Loading towns from the database into the shape rules.js works on, and settling them (storing the current value at a
|
||||
* new time before something that changes a rate is applied). Shared by commands, events and queries.
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
|
||||
// Cached world rows: they never change while the server runs (config is read at boot and on admin edits).
|
||||
function loadWorld(db, id) {
|
||||
const w = db.get('SELECT * FROM worlds WHERE id = ?', id);
|
||||
return w ? Object.assign(w, { config: JSON.parse(w.config || '{}') }) : null;
|
||||
}
|
||||
|
||||
// rules.js town shape from a towns row. `unitDraw` comes from the military module when it exists.
|
||||
function townFromRow(db, row, world) {
|
||||
const buildings = {};
|
||||
for (const b of db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', row.id)) buildings[b.key] = { type: b.type, level: b.level };
|
||||
world = world || loadWorld(db, row.world_id);
|
||||
return {
|
||||
id: row.id, worldId: row.world_id, ownerId: row.owner_id, name: row.name, x: row.x, y: row.y,
|
||||
isCapital: !!row.is_capital, speed: world.speed,
|
||||
updatedAt: row.res_at, footprint: row.footprint,
|
||||
res: { fiber: row.fiber, hardware: row.hardware, capital: row.capital, battery: row.battery },
|
||||
loyalty: row.loyalty, loyaltyAt: row.loyalty_at,
|
||||
buildings,
|
||||
unitDraw: unitDraw(db, row.id),
|
||||
bonus: R.ruralBonus(world.seed, world.map_radius, row.x, row.y),
|
||||
};
|
||||
}
|
||||
|
||||
// Total power draw of units stationed in a town. Military stage fills this in (table town_units).
|
||||
function unitDraw(db, townId) {
|
||||
if (!hasTable(db, 'town_units')) return 0;
|
||||
const rows = db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId);
|
||||
let draw = 0;
|
||||
for (const r of rows) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
|
||||
return draw;
|
||||
}
|
||||
|
||||
const tableCache = new Map();
|
||||
function hasTable(db, name) {
|
||||
if (!tableCache.has(db)) tableCache.set(db, new Map());
|
||||
const m = tableCache.get(db);
|
||||
if (!m.get(name)) m.set(name, !!db.get("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?", name));
|
||||
return m.get(name);
|
||||
}
|
||||
|
||||
function loadTown(db, id) {
|
||||
const row = db.get('SELECT * FROM towns WHERE id = ?', id);
|
||||
return row ? townFromRow(db, row) : null;
|
||||
}
|
||||
|
||||
// Bring the stored values up to `at`. Call before any change to buildings or units of this town. Mutates `town`.
|
||||
function settle(db, town, at) {
|
||||
if (at < town.updatedAt) at = town.updatedAt; // never go backwards
|
||||
const cur = R.resourcesAt(town, at).amounts;
|
||||
const fp = R.footprintAt(town, at);
|
||||
const loy = R.loyaltyAt(town.loyalty, town.loyaltyAt, at, town.speed);
|
||||
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ?, res_at = ?, loyalty = ?, loyalty_at = ? WHERE id = ?',
|
||||
cur.fiber, cur.hardware, cur.capital, cur.battery, fp, at, loy, at, town.id);
|
||||
town.res = { fiber: cur.fiber, hardware: cur.hardware, capital: cur.capital, battery: cur.battery };
|
||||
town.footprint = fp; town.updatedAt = at; town.loyalty = loy; town.loyaltyAt = at;
|
||||
return town;
|
||||
}
|
||||
|
||||
// Subtract a cost from a settled town (persists). Caller has already checked affordability.
|
||||
function spend(db, town, cost) {
|
||||
for (const r of D.RESOURCES) town.res[r] -= cost[r] || 0;
|
||||
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
|
||||
}
|
||||
|
||||
function pendingBuilds(db, townId) {
|
||||
return db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'buildDone' AND status = 'pending' ORDER BY due_at, id", townId)
|
||||
.map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload)));
|
||||
}
|
||||
|
||||
module.exports = { loadWorld, loadTown, townFromRow, settle, spend, pendingBuilds, hasTable };
|
||||
181
server/static.js
Normal file
181
server/static.js
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Minimal, safe static file server for public/.
|
||||
* - GET / HEAD only (405 otherwise), never serves anything outside the root (also not via symlinks)
|
||||
* - rejects "..", %2e%2e, %2f, %5c, backslashes, NUL and control characters (400), dotfiles (404)
|
||||
* - ETag / If-None-Match / Last-Modified (304) with Cache-Control: no-cache
|
||||
* - single-range requests (206): iOS Safari will not play <audio>/<video> without them
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { pipeline } = require('stream');
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.htm': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.woff': 'font/woff',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.wav': 'audio/wav',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
const CSP = "default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; " +
|
||||
"style-src 'self' 'unsafe-inline'; media-src 'self' data:; base-uri 'none'; frame-ancestors 'none'";
|
||||
|
||||
// Headers every response carries (static files, /healthz, errors).
|
||||
function applySecurityHeaders(res) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('Content-Security-Policy', CSP);
|
||||
}
|
||||
|
||||
function sendText(req, res, status, text, extra) {
|
||||
const body = Buffer.from(text, 'utf8');
|
||||
res.writeHead(status, Object.assign({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Length': body.length,
|
||||
'Cache-Control': 'no-cache',
|
||||
}, extra));
|
||||
res.end(req.method === 'HEAD' ? undefined : body);
|
||||
}
|
||||
|
||||
// Turns a raw request target into path segments, or an HTTP status to answer with.
|
||||
function parseTarget(rawUrl) {
|
||||
if (typeof rawUrl !== 'string' || rawUrl[0] !== '/') return { status: 400 };
|
||||
const cut = rawUrl.search(/[?#]/);
|
||||
const raw = cut < 0 ? rawUrl : rawUrl.slice(0, cut);
|
||||
if (/%(2f|5c)/i.test(raw) || raw.includes('\\')) return { status: 400 };
|
||||
let dec;
|
||||
try { dec = decodeURIComponent(raw); } catch (e) { return { status: 400 }; }
|
||||
if (/[\x00-\x1f\x7f\\]/.test(dec)) return { status: 400 };
|
||||
const segs = dec.split('/').filter((s) => s !== ''); // '//' collapses
|
||||
for (const s of segs) {
|
||||
if (s === '.' || s === '..') return { status: 400 };
|
||||
if (s[0] === '.') return { status: 404 }; // dotfiles and dot-directories
|
||||
}
|
||||
return { segs, trailingSlash: dec.endsWith('/') };
|
||||
}
|
||||
|
||||
function etagOf(st) { return 'W/"' + st.size.toString(16) + '-' + Math.floor(st.mtimeMs).toString(16) + '"'; }
|
||||
|
||||
function etagMatches(header, etag) {
|
||||
if (!header) return false;
|
||||
if (header.trim() === '*') return true;
|
||||
const weak = (s) => s.trim().replace(/^W\//, '');
|
||||
const mine = weak(etag);
|
||||
return header.split(',').some((t) => weak(t) === mine);
|
||||
}
|
||||
|
||||
// Parses "bytes=a-b" for a file of `size` bytes.
|
||||
// -> null (ignore the header, serve everything) | 'unsatisfiable' | { start, end }
|
||||
function parseRange(header, size) {
|
||||
if (!header) return null;
|
||||
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); // multiple ranges: ignore, serve all
|
||||
if (!m || (m[1] === '' && m[2] === '')) return null;
|
||||
let start, end;
|
||||
if (m[1] === '') { // suffix: last N bytes
|
||||
const n = parseInt(m[2], 10);
|
||||
if (n === 0) return 'unsatisfiable';
|
||||
start = Math.max(0, size - n); end = size - 1;
|
||||
} else {
|
||||
start = parseInt(m[1], 10);
|
||||
end = m[2] === '' ? size - 1 : Math.min(parseInt(m[2], 10), size - 1);
|
||||
if (m[2] !== '' && parseInt(m[2], 10) < start) return null; // malformed spec: ignore
|
||||
}
|
||||
if (start >= size) return 'unsatisfiable';
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function createStaticHandler(publicDir) {
|
||||
const root = path.resolve(publicDir);
|
||||
|
||||
async function resolveFile(segs, trailingSlash) {
|
||||
let file = path.join(root, ...segs);
|
||||
if (file !== root && !file.startsWith(root + path.sep)) return { status: 404 };
|
||||
let st;
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
if (st.isDirectory()) {
|
||||
if (!trailingSlash && segs.length) return { redirect: encodeURIComponent(segs[segs.length - 1]) + '/' };
|
||||
file = path.join(file, 'index.html');
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
}
|
||||
if (!st.isFile()) return { status: 404 };
|
||||
let real, realRoot;
|
||||
try {
|
||||
real = await fs.promises.realpath(file);
|
||||
realRoot = await fs.promises.realpath(root);
|
||||
} catch (e) { return { status: 404 }; }
|
||||
if (real !== realRoot && !real.startsWith(realRoot + path.sep)) return { status: 404 }; // symlink escape
|
||||
return { file: real, st };
|
||||
}
|
||||
|
||||
return async function handle(req, res) {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
return sendText(req, res, 405, 'Method Not Allowed', { Allow: 'GET, HEAD' });
|
||||
}
|
||||
const target = parseTarget(req.url);
|
||||
if (target.status) return sendText(req, res, target.status, target.status === 400 ? 'Bad Request' : 'Not Found');
|
||||
let r;
|
||||
try { r = await resolveFile(target.segs, target.trailingSlash); } catch (e) { r = { status: 404 }; }
|
||||
if (r.redirect) {
|
||||
// Relative on purpose: it keeps working when a proxy serves us under a path prefix.
|
||||
return sendText(req, res, 301, 'Moved Permanently', { Location: r.redirect });
|
||||
}
|
||||
if (r.status) return sendText(req, res, r.status, 'Not Found');
|
||||
|
||||
const { file, st } = r;
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
const etag = etagOf(st);
|
||||
const lastModified = st.mtime.toUTCString();
|
||||
const base = {
|
||||
'Content-Type': MIME[ext] || 'application/octet-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'ETag': etag,
|
||||
'Last-Modified': lastModified,
|
||||
'Accept-Ranges': 'bytes',
|
||||
};
|
||||
|
||||
const inm = req.headers['if-none-match'];
|
||||
const ims = req.headers['if-modified-since'];
|
||||
const fresh = inm ? etagMatches(inm, etag)
|
||||
: (ims && Math.floor(st.mtimeMs / 1000) <= Math.floor(Date.parse(ims) / 1000));
|
||||
if (fresh) {
|
||||
res.writeHead(304, { 'Cache-Control': base['Cache-Control'], 'ETag': etag, 'Last-Modified': lastModified });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let range = parseRange(req.headers.range, st.size);
|
||||
const ifRange = req.headers['if-range'];
|
||||
if (range && ifRange && ifRange.trim() !== etag && ifRange.trim() !== lastModified) range = null;
|
||||
if (range === 'unsatisfiable') {
|
||||
res.writeHead(416, { 'Content-Range': 'bytes */' + st.size, 'Content-Length': 0, 'Cache-Control': 'no-cache' });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let status = 200, start = 0, end = st.size - 1;
|
||||
if (range) {
|
||||
status = 206; start = range.start; end = range.end;
|
||||
base['Content-Range'] = 'bytes ' + start + '-' + end + '/' + st.size;
|
||||
}
|
||||
base['Content-Length'] = st.size === 0 ? 0 : end - start + 1;
|
||||
res.writeHead(status, base);
|
||||
if (req.method === 'HEAD' || st.size === 0) return res.end();
|
||||
pipeline(fs.createReadStream(file, { start, end }), res, () => { /* client went away: nothing to do */ });
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createStaticHandler, applySecurityHeaders, parseTarget, parseRange, MIME, CSP };
|
||||
63
server/validate.js
Normal file
63
server/validate.js
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
'use strict';
|
||||
/*
|
||||
* A small JSON-schema subset used for request validation AND emitted verbatim into openapi.json, so there is one
|
||||
* source of truth. Supported: type (string|integer|number|boolean|object|array), enum, minLength, maxLength, pattern,
|
||||
* minimum, maximum, items, maxItems, properties, required. Objects reject unknown keys unless additionalProperties
|
||||
* is true. With coerce: true, strings are turned into numbers/booleans first (query strings).
|
||||
*/
|
||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
|
||||
function check(schema, v, path, errors, coerce) {
|
||||
if (coerce && typeof v === 'string') {
|
||||
if ((schema.type === 'integer' || schema.type === 'number') && v.trim() !== '' && !isNaN(Number(v))) v = Number(v);
|
||||
else if (schema.type === 'boolean' && (v === 'true' || v === 'false')) v = v === 'true';
|
||||
}
|
||||
const bad = (msg) => { errors.push({ path, message: msg }); return v; };
|
||||
switch (schema.type) {
|
||||
case 'string':
|
||||
if (typeof v !== 'string') return bad('must be a string');
|
||||
if (schema.minLength !== undefined && v.length < schema.minLength) return bad('too short (min ' + schema.minLength + ')');
|
||||
if (schema.maxLength !== undefined && v.length > schema.maxLength) return bad('too long (max ' + schema.maxLength + ')');
|
||||
if (schema.pattern && !new RegExp(schema.pattern).test(v)) return bad('has the wrong format');
|
||||
if (schema.enum && !schema.enum.includes(v)) return bad('must be one of ' + schema.enum.join(', '));
|
||||
return v;
|
||||
case 'integer':
|
||||
case 'number':
|
||||
if (typeof v !== 'number' || !Number.isFinite(v)) return bad('must be a number');
|
||||
if (schema.type === 'integer' && !Number.isInteger(v)) return bad('must be an integer');
|
||||
if (schema.minimum !== undefined && v < schema.minimum) return bad('must be >= ' + schema.minimum);
|
||||
if (schema.maximum !== undefined && v > schema.maximum) return bad('must be <= ' + schema.maximum);
|
||||
return v;
|
||||
case 'boolean':
|
||||
if (typeof v !== 'boolean') return bad('must be a boolean');
|
||||
return v;
|
||||
case 'array': {
|
||||
if (!Array.isArray(v)) return bad('must be an array');
|
||||
if (schema.maxItems !== undefined && v.length > schema.maxItems) return bad('too many items (max ' + schema.maxItems + ')');
|
||||
return schema.items ? v.map((it, i) => check(schema.items, it, path + '[' + i + ']', errors, false)) : v;
|
||||
}
|
||||
case 'object': {
|
||||
if (v === null || typeof v !== 'object' || Array.isArray(v)) return bad('must be an object');
|
||||
const out = {};
|
||||
const props = schema.properties || {};
|
||||
for (const k of schema.required || []) if (!hasOwn(v, k) || v[k] === undefined) errors.push({ path: path ? path + '.' + k : k, message: 'is required' });
|
||||
for (const k of Object.keys(v)) {
|
||||
if (hasOwn(props, k)) out[k] = check(props[k], v[k], path ? path + '.' + k : k, errors, coerce);
|
||||
else if (schema.additionalProperties) out[k] = v[k];
|
||||
else errors.push({ path: path ? path + '.' + k : k, message: 'is not a known field' });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
// -> { ok, value, errors: [{ path, message }] }
|
||||
function validate(schema, value, opts) {
|
||||
const errors = [];
|
||||
const out = check(schema, value === undefined ? {} : value, '', errors, !!(opts && opts.coerce));
|
||||
return { ok: errors.length === 0, value: out, errors };
|
||||
}
|
||||
|
||||
module.exports = { validate };
|
||||
20
server/world.js
Normal file
20
server/world.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
/* World lifecycle helpers. A world is a row in `worlds`; everything about it (speed, size, seed) is data. */
|
||||
const crypto = require('crypto');
|
||||
const D = require('../public/js/data.js');
|
||||
|
||||
function createWorld(db, now, o) {
|
||||
o = o || {};
|
||||
const seed = o.seed !== undefined ? o.seed : crypto.randomInt(1, 2 ** 31 - 1);
|
||||
const r = db.run('INSERT INTO worlds (name, speed, map_radius, seed, start_at, end_at, status, preset, config, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
o.name || D.WORLD_DEFAULTS.name, o.speed || D.WORLD_DEFAULTS.speed, o.mapRadius || D.WORLD_DEFAULTS.mapRadius, seed, now, o.endAt || null, 'running', o.preset || D.WORLD_DEFAULTS.preset, JSON.stringify(o.config || {}), now);
|
||||
return Number(r.lastInsertRowid);
|
||||
}
|
||||
|
||||
// First boot: a database without any world gets one (WORLD_SPEED / WORLD_RADIUS from the environment).
|
||||
function ensureWorld(db, now, o) {
|
||||
if (db.get('SELECT 1 AS x FROM worlds LIMIT 1')) return null;
|
||||
return createWorld(db, now, o);
|
||||
}
|
||||
|
||||
module.exports = { createWorld, ensureWorld };
|
||||
Loading…
Add table
Add a link
Reference in a new issue