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:
jvanvik 2026-10-11 18:07:42 +02:00
parent 9fa76d53a8
commit b56b13880e
39 changed files with 4450 additions and 0 deletions

61
server/auth.js Normal file
View 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 };