From dca1032ac441633bbd48335d4f1ec136511c4b83 Mon Sep 17 00:00:00 2001 From: Benjamin Oezcan Date: Thu, 19 Nov 2026 01:52:30 +0100 Subject: [PATCH] feat(server)!: websocket lobby, server-run matches, server economy, new schema (P1-2, P1-4, P2-1, P2-1b, P2-5) Replaces the Firebase-style /db facade (rtdb, rules, nodes tree) with explicit REST endpoints and a WebSocket hub. Login by name or optional e-mail, seed accounts via npm run db:reset. BREAKING CHANGE: old clients (lobby/netfight over /db) no longer work against this server; database is new. --- server/app.js | 130 ++++++++++++------------- server/auth.js | 78 ++++++++------- server/db.js | 109 --------------------- server/db/index.js | 70 ++++++++++++++ server/db/migrations/001_init.sql | 46 +++++++++ server/economy.js | 73 ++++++++++---- server/lobby.js | 152 ++++++++++++++++++++++++++++++ server/match/room.js | 8 ++ server/match/runner.js | 41 ++++++++ server/package-lock.json | 24 ++++- server/package.json | 10 +- server/ratelimit.js | 18 ++++ server/rtdb.js | 38 -------- server/rules.js | 34 ------- server/scripts/reset-db.js | 33 +++++++ server/test/economy.test.js | 73 ++++++++++++++ server/test/health.test.js | 32 +++++-- server/test/helpers.js | 65 +++++++++++-- server/test/lobby.test.js | 138 +++++++++++++++++++++++++++ server/ws/hub.js | 58 ++++++++++++ 20 files changed, 908 insertions(+), 322 deletions(-) delete mode 100644 server/db.js create mode 100644 server/db/index.js create mode 100644 server/db/migrations/001_init.sql create mode 100644 server/lobby.js create mode 100644 server/match/runner.js create mode 100644 server/ratelimit.js delete mode 100644 server/rtdb.js delete mode 100644 server/rules.js create mode 100644 server/scripts/reset-db.js create mode 100644 server/test/economy.test.js create mode 100644 server/test/lobby.test.js create mode 100644 server/ws/hub.js diff --git a/server/app.js b/server/app.js index ff2a91f..54db0ac 100644 --- a/server/app.js +++ b/server/app.js @@ -1,98 +1,86 @@ -/* Robot Clash backend. Serves the static game and an API/DB that mirrors the old Firebase surface, - so game/net.js only swaps its base URL. Money/fame are server-authoritative (stripped from saves). */ +/* Robot Clash server: REST (accounts, online save + shop actions, campaign cloud save, ranking, live settings), + WebSocket /ws (lobby + server-run live fights) and the static game from ../game - all on one origin. */ 'use strict'; -const express = require('express'); +const http = require('http'); const path = require('path'); +const express = require('express'); const auth = require('./auth'); -const rules = require('./rules'); -const rtdb = require('./rtdb'); -const eco = require('./economy'); -const { getTree, putTree, patchTree, pushTree, delTreeAt, norm } = require('./db'); - +const economy = require('./economy'); +const { Matches, KV, CampaignSaves } = require('./db'); +const { rateLimit } = require('./ratelimit'); +const { createRunner } = require('./match/runner'); +const { createLobby } = require('./lobby'); +const hub = require('./ws/hub'); const pkg = require('./package.json'); + const STARTED = Date.now(); +const runner = createRunner(); +const lobby = createLobby({ runner, economy, matches: Matches }); const app = express(); -app.use(express.json({ limit: '2mb', strict: false })); // strict:false so scalar values (e.g. a name string) parse too -app.use(auth.auth); // sets req.uid / req.user (null if not logged in) +app.set('trust proxy', 'loopback'); // behind Caddy: real client IP for the rate limiter +app.use(express.json({ limit: '1mb' })); +app.use(auth.middleware); -// --- health (deploy checks, monitoring) -------------------------------------------------------------- +const run = fn => (req, res) => { + try { res.json(fn(req)); } catch (e) { if (!e.status) console.error(e); res.status(e.status || 500).json({ error: e.code || 'ERROR' }); } +}; +const need = (req, admin) => { + if (!req.user) { const e = new Error('UNAUTH'); e.status = 401; e.code = 'UNAUTH'; throw e; } + if (admin && !req.user.admin) { const e = new Error('DENIED'); e.status = 403; e.code = 'DENIED'; throw e; } + return req.user; +}; +const body = req => (req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}); + +// --- health ------------------------------------------------------------------------------------------ app.get('/healthz', (_req, res) => res.json({ - ok: true, version: pkg.version, commit: process.env.GIT_COMMIT || null, uptime: Math.round((Date.now() - STARTED) / 1000), + ok: true, version: pkg.version, commit: process.env.GIT_COMMIT || null, + uptime: Math.round((Date.now() - STARTED) / 1000), players: lobby.players.size, matches: runner.rooms.size, })); -function run(res, fn) { try { res.json(fn()); } catch (e) { res.status(e.status || 500).json({ error: e.code || 'ERROR' }); } } +// --- accounts ---------------------------------------------------------------------------------------- +const authLimit = rateLimit({ name: 'auth', windowMs: 60000, max: process.env.NODE_ENV === 'test' ? 1000 : 20 }); +app.post('/api/auth/register', authLimit, run(req => auth.register(body(req).name, body(req).pass, body(req).email))); +app.post('/api/auth/login', authLimit, run(req => auth.login(body(req).login || body(req).email, body(req).pass))); +app.post('/api/auth/guest', authLimit, run(req => auth.guest(body(req).name))); +app.post('/api/auth/refresh', run(req => auth.refresh(body(req).refreshToken))); +app.post('/api/auth/logout', run(req => { auth.logout(body(req).refreshToken); return { ok: true }; })); +app.get('/api/me', (req, res) => res.json(req.user ? { uid: req.uid, name: req.user.name, guest: req.user.guest, admin: req.user.admin } : { uid: null, admin: false })); -// --- accounts -------------------------------------------------------------------------------------- -app.post('/api/auth/register', (req, res) => run(res, () => auth.register(req.body.email, req.body.pass, req.body.name))); -app.post('/api/auth/login', (req, res) => run(res, () => auth.login(req.body.email, req.body.pass))); -app.post('/api/auth/guest', (req, res) => run(res, () => auth.guest(req.body.name))); -app.post('/api/auth/refresh', (req, res) => run(res, () => auth.refresh(req.body.refreshToken))); -app.post('/api/auth/logout', (req, res) => { auth.logout(req.body.refreshToken); res.json({ ok: true }); }); +// --- online save: read, shop/workshop actions (server-authoritative), cosmetics ------------------------ +app.get('/api/online', run(req => economy.load(need(req).uid))); +app.post('/api/online/action', run(req => { + const u = need(req), r = economy.action(u, body(req)); + if (r.ok) lobby.refresh(u.uid); + return r; +})); +app.put('/api/online/save', run(req => { const u = need(req), s = economy.putCosmetics(u.uid, body(req)); lobby.refresh(u.uid); return s; })); -// --- who am I (is this account an admin? drives the in-game dev menu) ------------------------------- -app.get('/api/me', (req, res) => res.json({ uid: req.uid || null, admin: !!(req.uid && rules.ADMIN.includes(req.uid)) })); +// --- campaign cloud save (registered accounts; offline game, client-trusted) -------------------------- +app.get('/api/campaign', run(req => { const u = need(req); return CampaignSaves.get(u.uid); })); +app.put('/api/campaign', run(req => { const u = need(req); if (u.guest) return { ok: false }; CampaignSaves.put(u.uid, body(req)); return { ok: true }; })); -// --- wallet (read-only; changes only via validated actions, added in step 3) ----------------------- -app.get('/api/wallet', (req, res) => { if (!req.uid) return res.status(401).json({ error: 'UNAUTH' }); res.json(eco.wallet(req.uid)); }); +// --- ranking + live settings (public read) ----------------------------------------------------------- +app.get('/api/ranks', run(req => economy.ranks(+req.query.n || 20))); +app.get('/api/live', run(() => KV.get('live'))); +app.put('/api/admin/live', run(req => { need(req, true); KV.put('live', body(req)); return { ok: true }; })); -// --- dev: admins may set their own coins while testing (money is still in the save for now) --------- -app.post('/api/dev/coins', (req, res) => { - if (!req.uid || !rules.ADMIN.includes(req.uid)) return res.status(403).json({ error: 'DENIED' }); - res.json({ ok: true, money: eco.clampMoney(req.body && req.body.money) }); -}); - -// --- RTDB-compatible façade: /db/.json (GET also serves SSE) ---------------------------------- -// Anti-cheat: once ANTICHEAT=1 (step 3, wallet wired) the save may not carry money/fame; until then keep them -// so the game runs unchanged on the new server (transport swap first). -const ANTICHEAT = process.env.ANTICHEAT === '1'; -const stripSave = (p, v) => { - if (ANTICHEAT && norm(p).split('/')[0] === 'saves' && v && typeof v === 'object' && !Array.isArray(v)) { const c = { ...v }; delete c.money; delete c.fame; return c; } - return v; -}; -app.get(/^\/db\/(.*)\.json$/, (req, res) => { - const p = req.params[0]; - if ((req.headers.accept || '').includes('text/event-stream')) { - if (!rules.canRead(req, p)) return res.status(403).end(); - return rtdb.subscribe(p, res); - } - if (!rules.canRead(req, p)) return res.status(403).json({ error: 'DENIED' }); - res.json(getTree(p)); -}); -function write(req, res, kind) { - const p = req.params[0]; - if (!rules.canWrite(req, p)) return res.status(403).json({ error: 'DENIED' }); - (kind === 'put' ? putTree : patchTree)(p, stripSave(p, req.body)); - rtdb.notify(p); - res.json(req.body); -} -app.put(/^\/db\/(.*)\.json$/, (req, res) => write(req, res, 'put')); -app.patch(/^\/db\/(.*)\.json$/, (req, res) => write(req, res, 'patch')); -app.post(/^\/db\/(.*)\.json$/, (req, res) => { - const p = req.params[0]; - if (!rules.canWrite(req, p)) return res.status(403).json({ error: 'DENIED' }); - const id = pushTree(p, stripSave(p, req.body)); rtdb.notify(p + '/' + id); res.json({ name: id }); -}); -app.delete(/^\/db\/(.*)\.json$/, (req, res) => { - const p = req.params[0]; - if (!rules.canWrite(req, p)) return res.status(403).json({ error: 'DENIED' }); - delTreeAt(p); rtdb.notify(p); res.json(null); -}); - -// --- static game (same origin: no CORS, no mixed content) ------------------------------------------ +// --- static game (same origin: no CORS, no mixed content) -------------------------------------------- app.use(express.static(path.join(__dirname, '..', 'game'), { etag: true, setHeaders(res, p) { - // images / fonts / audio rarely change -> cache hard (fast re-renders, no re-fetch flicker) if (/\.(png|jpe?g|webp|gif|svg|woff2?|ttf|otf|mp3|ogg|wav|m4a)$/i.test(p)) res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); else res.setHeader('Cache-Control', 'no-cache'); // code/html: revalidate so deploys show up }, })); -// started directly (node app.js) -> listen; required by tests -> they call listen() themselves +const server = http.createServer(app); +const wss = hub.attach(server, { lobby }); + +// started directly (node app.js) -> listen; tests call listen(0) themselves function listen(port = process.env.PORT || 8080) { - return new Promise(resolve => { const srv = app.listen(port, () => resolve(srv)); }); + return new Promise(resolve => server.listen(port, () => resolve(server))); } if (require.main === module) listen().then(srv => console.log('Robot Clash server on :' + srv.address().port)); -module.exports = { app, listen }; +module.exports = { app, server, wss, listen, runner, lobby }; diff --git a/server/auth.js b/server/auth.js index 9a742a4..8625db2 100644 --- a/server/auth.js +++ b/server/auth.js @@ -1,10 +1,9 @@ -/* Accounts: register / login / guest / refresh, JWT access tokens + rotating refresh tokens. - Shaped like the old Firebase auth so game/net.js only swaps the base URL. */ +/* Accounts: register / login (name or e-mail) / guest / refresh. JWT access tokens + rotating refresh tokens. */ 'use strict'; const crypto = require('crypto'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); -const { Users, Wallet, Tokens } = require('./db'); +const { Users, Tokens } = require('./db'); // No secret configured -> random per process (tokens die on restart). Never fall back to a known string. const SECRET = process.env.JWT_SECRET || (() => { @@ -13,55 +12,66 @@ const SECRET = process.env.JWT_SECRET || (() => { })(); const ACCESS_TTL = 3600; // seconds const REFRESH_TTL = 30 * 864e5; // 30 days (ms) -const START_MONEY = 800; +const MIN_PASS = 8; const newUid = () => crypto.randomBytes(16).toString('hex'); -const newRefresh = () => crypto.randomBytes(32).toString('hex'); -const cleanName = n => String(n || '').replace(/[^\p{L}\p{N} _-]/gu, '').trim().slice(0, 18); -function err(code, msg) { const e = new Error(msg); e.code = msg; e.status = code; return e; } +const cleanName = n => Array.from(String(n || '')).filter(c => /[\p{L}\p{N} _-]/u.test(c)).join('').trim().slice(0, 18); +function err(status, code) { const e = new Error(code); e.code = code; e.status = status; return e; } function issue(u) { - const idToken = jwt.sign({ uid: u.uid, name: u.name, guest: !!u.guest }, SECRET, { expiresIn: ACCESS_TTL }); - const refreshToken = newRefresh(); + const idToken = jwt.sign({ uid: u.uid, name: u.name, guest: !!u.guest, role: u.role }, SECRET, { expiresIn: ACCESS_TTL }); + const refreshToken = crypto.randomBytes(32).toString('hex'); Tokens.insert.run(refreshToken, u.uid, Date.now() + REFRESH_TTL); - return { idToken, refreshToken, uid: u.uid, name: u.name, email: u.email || '', expiresIn: ACCESS_TTL }; + Users.seen.run(Date.now(), u.uid); + return { idToken, refreshToken, uid: u.uid, name: u.name, email: u.email || '', guest: !!u.guest, admin: u.role === 'admin', expiresIn: ACCESS_TTL }; } -function register(email, pass, name) { - email = String(email || '').trim().toLowerCase(); - if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) throw err(400, 'INVALID_EMAIL'); - if (String(pass || '').length < 6) throw err(400, 'WEAK_PASSWORD'); - if (Users.byEmail.get(email)) throw err(409, 'EMAIL_EXISTS'); - const u = { uid: newUid(), email, pass: bcrypt.hashSync(String(pass), 10), name: cleanName(name) || email.split('@')[0], guest: 0, created: Date.now() }; - Users.insert.run(u); Wallet.init.run(u.uid, START_MONEY); - return issue(u); +function createUser({ name, pass, email, role = 'player', guest = false }) { + const now = Date.now(); + const u = { + uid: newUid(), name, uname: guest ? null : name.toLowerCase(), email: email || null, + pass: pass ? bcrypt.hashSync(String(pass), 10) : null, role, guest: guest ? 1 : 0, created: now, seen: now, + }; + Users.insert.run(u); + return u; } -function login(email, pass) { - email = String(email || '').trim().toLowerCase(); - const u = Users.byEmail.get(email); + +function register(name, pass, email) { + name = cleanName(name); + email = String(email || '').trim().toLowerCase() || null; + if (name.length < 3) throw err(400, 'BAD_NAME'); + if (email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) throw err(400, 'INVALID_EMAIL'); + if (String(pass || '').length < MIN_PASS) throw err(400, 'WEAK_PASSWORD'); + if (Users.byLogin.get(name, email || name)) throw err(409, 'NAME_EXISTS'); + if (email && Users.byLogin.get(email, email)) throw err(409, 'EMAIL_EXISTS'); + return issue(createUser({ name, pass, email })); +} +function login(loginName, pass) { + const l = String(loginName || '').trim().toLowerCase(); + const u = l && Users.byLogin.get(l, l); if (!u || !u.pass || !bcrypt.compareSync(String(pass || ''), u.pass)) throw err(400, 'INVALID_LOGIN'); return issue(u); } -function guest(name) { - const u = { uid: newUid(), email: null, pass: null, name: cleanName(name) || 'Guest', guest: 1, created: Date.now() }; - Users.insert.run(u); Wallet.init.run(u.uid, START_MONEY); - return issue(u); -} +function guest(name) { return issue(createUser({ name: cleanName(name) || 'Guest', guest: true })); } function refresh(refreshToken) { - const row = Tokens.get.get(refreshToken || ''); + const row = Tokens.get.get(String(refreshToken || '')); if (!row || row.exp < Date.now()) throw err(401, 'INVALID_REFRESH'); const u = Users.byId.get(row.uid); if (!u) throw err(401, 'INVALID_REFRESH'); - Tokens.del.run(refreshToken); // rotate + Tokens.del.run(row.token); // rotate: every refresh token works once return issue(u); } -function logout(refreshToken) { if (refreshToken) Tokens.del.run(refreshToken); } +function logout(refreshToken) { if (refreshToken) Tokens.del.run(String(refreshToken)); } -// express middleware: reads ?auth= or Authorization: Bearer, sets req.uid / req.user (or null) -function auth(req, _res, next) { - const tok = req.query.auth || (req.headers.authorization || '').replace(/^Bearer\s+/i, ''); - try { const d = jwt.verify(tok, SECRET); req.uid = d.uid; req.user = d; } catch (e) { req.uid = null; req.user = null; } +function verify(token) { + try { const d = jwt.verify(String(token || ''), SECRET); return { uid: d.uid, name: d.name, guest: !!d.guest, admin: d.role === 'admin' }; } catch (e) { return null; } +} +// express middleware: Authorization: Bearer (or ?auth= for old clients) -> req.user / req.uid +function middleware(req, _res, next) { + const tok = (req.headers.authorization || '').replace(/^Bearer\s+/i, '') || req.query.auth; + req.user = tok ? verify(tok) : null; + req.uid = req.user ? req.user.uid : null; next(); } -module.exports = { register, login, guest, refresh, logout, auth, cleanName }; +module.exports = { register, login, guest, refresh, logout, verify, middleware, createUser, cleanName, MIN_PASS }; diff --git a/server/db.js b/server/db.js deleted file mode 100644 index 66e37dc..0000000 --- a/server/db.js +++ /dev/null @@ -1,109 +0,0 @@ -/* SQLite storage: real tables for accounts/wallet, plus a path-keyed "nodes" table that behaves - like a shallow Firebase-RTDB tree (so the client's db.get/put/patch/del/stream map 1:1). */ -'use strict'; -const path = require('path'); -const Database = require('better-sqlite3'); - -const DB_FILE = process.env.DB_FILE || path.join(__dirname, 'data.sqlite'); -const db = new Database(DB_FILE); -db.pragma('journal_mode = WAL'); -db.exec(` - CREATE TABLE IF NOT EXISTS users (uid TEXT PRIMARY KEY, email TEXT UNIQUE, pass TEXT, name TEXT, guest INTEGER DEFAULT 0, created INTEGER); - CREATE TABLE IF NOT EXISTS tokens (token TEXT PRIMARY KEY, uid TEXT, exp INTEGER); - CREATE TABLE IF NOT EXISTS wallet (uid TEXT PRIMARY KEY, money INTEGER DEFAULT 800, fame INTEGER DEFAULT 0); - CREATE TABLE IF NOT EXISTS nodes (path TEXT PRIMARY KEY, data TEXT, ts INTEGER); -`); - -const parse = s => { try { return JSON.parse(s); } catch (e) { return null; } }; -const norm = p => String(p || '').replace(/^\/+|\/+$/g, ''); - -// Firebase server values: the client sends { ".sv": "timestamp" } for "server time" (lobby heartbeat etc). -// Resolve it to the real time on write, otherwise ts stays an object and presence filtering breaks. -function resolveSV(v) { - if (Array.isArray(v)) return v.map(resolveSV); - if (v && typeof v === 'object') { - if (v['.sv'] === 'timestamp') return Date.now(); - const o = {}; for (const k in v) o[k] = resolveSV(v[k]); return o; - } - return v; -} - -// --- RTDB-like tree over the nodes table --------------------------------------------------------- -// objects are stored as ONE json node, so a deep path (e.g. matches//meta/seed) has no own row - -// read it from the nearest ancestor blob by descending into its parsed json (Firebase-like deep reads) -function readInside(p) { - const seg = p.split('/'); - for (let i = seg.length - 1; i >= 1; i--) { - const row = db.prepare('SELECT data FROM nodes WHERE path = ?').get(seg.slice(0, i).join('/')); - if (!row) continue; - let v = parse(row.data); - for (let j = i; j < seg.length; j++) { if (v && typeof v === 'object' && !Array.isArray(v)) v = v[seg[j]]; else { v = undefined; break; } } - return v === undefined ? null : v; - } - return null; -} -function getTree(p) { - p = norm(p); - const like = p ? p + '/%' : '%'; - const rows = p - ? db.prepare('SELECT path, data FROM nodes WHERE path = ? OR path LIKE ?').all(p, like) - : db.prepare('SELECT path, data FROM nodes').all(); - if (!rows.length) return p ? readInside(p) : null; - let result; - rows.sort((a, b) => a.path.length - b.path.length); - for (const row of rows) { - const val = parse(row.data); - if (row.path === p) { result = val; continue; } - const rel = (p ? row.path.slice(p.length + 1) : row.path).split('/'); - if (result == null || typeof result !== 'object') result = {}; - let o = result; - for (let i = 0; i < rel.length - 1; i++) { if (o[rel[i]] == null || typeof o[rel[i]] !== 'object') o[rel[i]] = {}; o = o[rel[i]]; } - o[rel[rel.length - 1]] = val; - } - return result === undefined ? null : result; -} - -const setNode = db.prepare('INSERT INTO nodes (path, data, ts) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET data = excluded.data, ts = excluded.ts'); -const delTree = db.prepare('DELETE FROM nodes WHERE path = ? OR path LIKE ?'); - -function putTree(p, value) { // replace the whole subtree at p - p = norm(p); - value = resolveSV(value); - delTree.run(p, p + '/%'); - if (value !== null && value !== undefined) setNode.run(p, JSON.stringify(value), Date.now()); - return value; -} -function patchTree(p, value) { // merge object fields into p (shallow) - p = norm(p); - value = resolveSV(value); - if (value == null || typeof value !== 'object') return putTree(p, value); - const cur = getTree(p) || {}; - for (const [k, v] of Object.entries(value)) { if (v === null) delete cur[k]; else cur[k] = v; } - return putTree(p, cur); -} -function pushTree(p, value) { // append with a time-sortable id (like Firebase push) - const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8); - putTree(norm(p) + '/' + id, value); - return id; -} -function delTreeAt(p) { p = norm(p); delTree.run(p, p + '/%'); } - -// --- accounts / wallet --------------------------------------------------------------------------- -const Users = { - byEmail: db.prepare('SELECT * FROM users WHERE email = ?'), - byId: db.prepare('SELECT * FROM users WHERE uid = ?'), - insert: db.prepare('INSERT INTO users (uid, email, pass, name, guest, created) VALUES (@uid, @email, @pass, @name, @guest, @created)'), - setName: db.prepare('UPDATE users SET name = ? WHERE uid = ?'), -}; -const Wallet = { - get: db.prepare('SELECT money, fame FROM wallet WHERE uid = ?'), - init: db.prepare('INSERT OR IGNORE INTO wallet (uid, money, fame) VALUES (?, ?, 0)'), - set: db.prepare('UPDATE wallet SET money = ?, fame = ? WHERE uid = ?'), -}; -const Tokens = { - insert: db.prepare('INSERT OR REPLACE INTO tokens (token, uid, exp) VALUES (?, ?, ?)'), - get: db.prepare('SELECT * FROM tokens WHERE token = ?'), - del: db.prepare('DELETE FROM tokens WHERE token = ?'), -}; - -module.exports = { db, getTree, putTree, patchTree, pushTree, delTreeAt, norm, Users, Wallet, Tokens }; diff --git a/server/db/index.js b/server/db/index.js new file mode 100644 index 0000000..6b486be --- /dev/null +++ b/server/db/index.js @@ -0,0 +1,70 @@ +/* SQLite access. Opens DB_FILE (':memory:' in tests), applies pending migrations from ./migrations + (NNN_name.sql, in order, each once - tracked in schema_version) and exposes small repositories. */ +'use strict'; +const fs = require('fs'); +const path = require('path'); +const Database = require('better-sqlite3'); + +const DB_FILE = process.env.DB_FILE || path.join(__dirname, '..', 'data.sqlite'); +const db = new Database(DB_FILE); +db.pragma('journal_mode = WAL'); +db.pragma('foreign_keys = ON'); + +function migrate() { + db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, name TEXT, applied INTEGER)'); + const done = new Set(db.prepare('SELECT version FROM schema_version').all().map(r => r.version)); + const dir = path.join(__dirname, 'migrations'); + const files = fs.readdirSync(dir).filter(f => /^\d+_.+\.sql$/.test(f)).sort(); + for (const f of files) { + const v = parseInt(f, 10); + if (done.has(v)) continue; + db.transaction(() => { + db.exec(fs.readFileSync(path.join(dir, f), 'utf8')); + db.prepare('INSERT INTO schema_version (version, name, applied) VALUES (?, ?, ?)').run(v, f, Date.now()); + })(); + } +} +migrate(); + +const json = s => { try { return JSON.parse(s); } catch (e) { return null; } }; + +const Users = { + byId: db.prepare('SELECT * FROM users WHERE uid = ?'), + byLogin: db.prepare('SELECT * FROM users WHERE uname = lower(?) OR email = lower(?)'), + insert: db.prepare('INSERT INTO users (uid, name, uname, email, pass, role, guest, created, seen) VALUES (@uid, @name, @uname, @email, @pass, @role, @guest, @created, @seen)'), + seen: db.prepare('UPDATE users SET seen = ? WHERE uid = ?'), + staleGuests: db.prepare('DELETE FROM users WHERE guest = 1 AND seen < ?'), +}; +const Tokens = { + insert: db.prepare('INSERT INTO refresh_tokens (token, uid, exp) VALUES (?, ?, ?)'), + get: db.prepare('SELECT * FROM refresh_tokens WHERE token = ?'), + del: db.prepare('DELETE FROM refresh_tokens WHERE token = ?'), + purge: db.prepare('DELETE FROM refresh_tokens WHERE exp < ?'), +}; +const OnlineSaves = { + _get: db.prepare('SELECT data FROM online_saves WHERE uid = ?'), + _put: db.prepare('INSERT INTO online_saves (uid, data, fame, updated) VALUES (?, ?, ?, ?) ON CONFLICT(uid) DO UPDATE SET data = excluded.data, fame = excluded.fame, updated = excluded.updated'), + _top: db.prepare(`SELECT u.uid, u.name, o.fame, o.data FROM online_saves o JOIN users u ON u.uid = o.uid + WHERE o.fame > 0 ORDER BY o.fame DESC, o.updated ASC LIMIT ?`), + get(uid) { const r = this._get.get(uid); return r ? json(r.data) : null; }, + put(uid, save) { this._put.run(uid, JSON.stringify(save), save.fame | 0, Date.now()); }, + top(n) { return this._top.all(n).map(r => { const d = json(r.data) || {}; return { uid: r.uid, name: r.name, fame: r.fame, flag: d.flag || 'XX' }; }); }, +}; +const CampaignSaves = { + _get: db.prepare('SELECT data FROM campaign_saves WHERE uid = ?'), + _put: db.prepare('INSERT INTO campaign_saves (uid, data, updated) VALUES (?, ?, ?) ON CONFLICT(uid) DO UPDATE SET data = excluded.data, updated = excluded.updated'), + get(uid) { const r = this._get.get(uid); return r ? json(r.data) : null; }, + put(uid, data) { this._put.run(uid, JSON.stringify(data), Date.now()); }, +}; +const Matches = { + start: db.prepare('INSERT INTO matches (id, seed, arena, uid0, uid1, started) VALUES (?, ?, ?, ?, ?, ?)'), + end: db.prepare('UPDATE matches SET winner = ?, reason = ?, ended = ? WHERE id = ?'), +}; +const KV = { + _get: db.prepare('SELECT value FROM kv WHERE key = ?'), + _put: db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'), + get(k) { const r = this._get.get(k); return r ? json(r.value) : null; }, + put(k, v) { this._put.run(k, JSON.stringify(v)); }, +}; + +module.exports = { db, DB_FILE, migrate, Users, Tokens, OnlineSaves, CampaignSaves, Matches, KV }; diff --git a/server/db/migrations/001_init.sql b/server/db/migrations/001_init.sql new file mode 100644 index 0000000..ad35708 --- /dev/null +++ b/server/db/migrations/001_init.sql @@ -0,0 +1,46 @@ +-- Robot Clash schema v1. Online saves are one JSON document per player; the server changes their economy +-- fields only through game/eco.js (same rules as the client), so a document stays consistent. +CREATE TABLE users ( + uid TEXT PRIMARY KEY, + name TEXT NOT NULL, -- display name + uname TEXT UNIQUE, -- login name, lower case (NULL for guests) + email TEXT UNIQUE, -- optional + pass TEXT, -- bcrypt hash (NULL for guests) + role TEXT NOT NULL DEFAULT 'player',-- player | admin + guest INTEGER NOT NULL DEFAULT 0, + created INTEGER NOT NULL, + seen INTEGER NOT NULL +); +CREATE TABLE refresh_tokens ( + token TEXT PRIMARY KEY, + uid TEXT NOT NULL REFERENCES users(uid) ON DELETE CASCADE, + exp INTEGER NOT NULL +); +CREATE INDEX refresh_tokens_uid ON refresh_tokens(uid); +CREATE TABLE online_saves ( + uid TEXT PRIMARY KEY REFERENCES users(uid) ON DELETE CASCADE, + data TEXT NOT NULL, + fame INTEGER NOT NULL DEFAULT 0, -- copy of data.fame for the ranking + updated INTEGER NOT NULL +); +CREATE INDEX online_saves_fame ON online_saves(fame DESC); +CREATE TABLE campaign_saves ( -- offline campaign mirrored for registered accounts (client-trusted) + uid TEXT PRIMARY KEY REFERENCES users(uid) ON DELETE CASCADE, + data TEXT NOT NULL, + updated INTEGER NOT NULL +); +CREATE TABLE matches ( + id TEXT PRIMARY KEY, + seed INTEGER NOT NULL, + arena TEXT NOT NULL, + uid0 TEXT NOT NULL, + uid1 TEXT NOT NULL, + winner INTEGER, -- seat 0 / 1, -1 draw, NULL running + reason TEXT, + started INTEGER NOT NULL, + ended INTEGER +); +CREATE TABLE kv ( -- small settings, e.g. 'live' (admin live control) + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); diff --git a/server/economy.js b/server/economy.js index ec1580d..552bd99 100644 --- a/server/economy.js +++ b/server/economy.js @@ -1,25 +1,60 @@ -/* Server-authoritative money/fame. The client can read its wallet but never set it directly; - it changes only through validated actions (buy/sell, fight result) added in step 3. - Loads the game's DOM-free logic (parts/robot/combat) so the server is the single source of truth. */ +/* Server-authoritative online economy. The online save of every player lives here; money, fame, parts and + robots change ONLY through RC.Eco (game/eco.js - the same rules the client runs) or fight rewards. */ 'use strict'; -const RC = require('../game/robot.js'); // pulls in parts.js too, sets globalThis.RC -require('../game/combat.js'); -require('../game/ai.js'); -const { Wallet } = require('./db'); +const RC = require('../game/robot.js'); // pulls in parts.js, sets globalThis.RC +require('../game/eco.js'); +const { OnlineSaves, KV } = require('./db'); -const clampMoney = v => Math.max(0, Math.min(1e9, Math.round(+v || 0))); +const Eco = RC.Eco; -function wallet(uid) { Wallet.init.run(uid, 800); return Wallet.get.get(uid); } -function setWallet(uid, money, fame) { - const w = wallet(uid); - const m = money == null ? w.money : clampMoney(money); - const f = fame == null ? w.fame : clampMoney(fame); - Wallet.set.run(m, f, uid); - return { money: m, fame: f }; +function load(uid) { + let s = OnlineSaves.get(uid); + if (!s || !Array.isArray(s.robots) || !s.robots.length) { s = Eco.newOnlineSave(); OnlineSaves.put(uid, s); } + s.active = Math.max(0, Math.min(s.active | 0, s.robots.length - 1)); + Eco.mirror(s); // build/paint/robotName point at robots[active] again after JSON + return s; } -function addWallet(uid, dMoney, dFame) { - const w = wallet(uid); - return setWallet(uid, w.money + (+dMoney || 0), w.fame + (+dFame || 0)); +const store = (uid, s) => OnlineSaves.put(uid, s); + +// what the client gets: the whole online save (it caches it locally) +const view = s => JSON.parse(JSON.stringify(s)); + +function action(user, a) { + if (a && a.type === 'devCoins' && !user.admin) return { ok: false, error: 'DENIED' }; + const s = load(user.uid); + const r = Eco.apply(s, a); + if (r.ok) store(user.uid, s); + return Object.assign(r, { save: view(s) }); // on error the client resyncs to this } -module.exports = { RC, wallet, setWallet, addWallet, clampMoney }; +function putCosmetics(uid, incoming) { + const s = load(uid); + Eco.mergeCosmetics(s, incoming); + store(uid, s); + return view(s); +} + +// the robot a player fights with (validated) + what the lobby shows +function fighter(uid, name) { + const s = load(uid); + const v = RC.validate(s.build); + return { + ok: v.ok, errors: v.errors, uid, name, flag: s.flag || 'XX', fame: s.fame | 0, + build: JSON.parse(JSON.stringify(s.build)), paint: JSON.parse(JSON.stringify(s.paint)), robotName: s.robotName, + }; +} + +// book a finished live fight; returns { money, fame, lines, save } +function reward(uid, o) { + const s = load(uid); + const live = KV.get('live') || {}; + const ev = live.event && live.event.prizeMul && Date.now() >= (live.event.from || 0) && Date.now() <= (live.event.to || Infinity) ? live.event.prizeMul : 1; + const r = Eco.pvpReward(Object.assign({}, o, { money: s.money, prizeMul: ev })); + Eco.applyReward(s, r); + store(uid, s); + return Object.assign(r, { save: view(s) }); +} + +function ranks(n = 20) { return OnlineSaves.top(Math.max(1, Math.min(100, n | 0))); } + +module.exports = { load, action, putCosmetics, fighter, reward, ranks }; diff --git a/server/lobby.js b/server/lobby.js new file mode 100644 index 0000000..2593238 --- /dev/null +++ b/server/lobby.js @@ -0,0 +1,152 @@ +/* Lobby: who is online (= has an open, authenticated socket), challenges, match creation and results. + All state is in memory and uses server time only - no heartbeats, no client clocks. + + const lobby = createLobby({ runner, economy, matches }) + lobby.join({ uid, name, admin, send }) socket authenticated (a second socket replaces the first) + lobby.leave(uid, send) socket closed (only if it is still the current one) + lobby.handle(uid, msg) validated client message */ +'use strict'; +const crypto = require('crypto'); + +const CHALLENGE_TTL = 15000; + +function createLobby({ runner, economy, matches, now = () => Date.now() }) { + const players = new Map(); // uid -> { uid, name, room, state, send, match: {id, seat} | null } + const pending = new Map(); // challenger uid -> { to, timer } + const inMatch = new Map(); // uid -> { id, seat } (survives a disconnect) + + const row = p => { + const f = economy.fighter(p.uid, p.name); + return { uid: p.uid, name: p.name, flag: f.flag, fame: f.fame, room: p.room || f.flag, state: p.state }; + }; + const tell = (uid, msg) => { const p = players.get(uid); if (p) p.send(msg); }; + const broadcast = (msg, except) => { for (const p of players.values()) if (p.uid !== except) p.send(msg); }; + const setState = (p, state) => { p.state = state; broadcast({ t: 'lobby.state', player: row(p) }); }; + + function join(c) { + const old = players.get(c.uid); + const p = { uid: c.uid, name: c.name, admin: !!c.admin, room: old ? old.room : null, state: 'idle', send: c.send }; + if (old && old.send !== c.send) old.send({ t: 'error', code: 'REPLACED' }); + players.set(c.uid, p); + const m = inMatch.get(c.uid); + const room = m && runner.get(m.id); + if (room) { p.state = 'inmatch'; room.reconnect(m.seat); } + p.send({ t: 'lobby', players: [...players.values()].filter(x => x.uid !== c.uid).map(row), you: row(p) }); + if (!old) broadcast({ t: 'lobby.join', player: row(p) }, c.uid); + if (room) p.send(room.startMsg(m.seat)); // reconnect: rebuild the running fight + } + + function leave(uid, send) { + const p = players.get(uid); + if (!p || (send && p.send !== send)) return; // an old, already replaced socket + players.delete(uid); + dropChallenges(uid); + const m = inMatch.get(uid), room = m && runner.get(m.id); + if (room) room.disconnect(m.seat); + broadcast({ t: 'lobby.leave', uid }); + } + + function dropChallenges(uid) { + const out = pending.get(uid); + if (out) { clearTimeout(out.timer); pending.delete(uid); tell(out.to, { t: 'challenge.gone', from: uid }); } + for (const [from, c] of pending) if (c.to === uid) { clearTimeout(c.timer); pending.delete(from); const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: uid }); } } + } + + function challenge(p, to) { + const q = players.get(to); + if (!q || to === p.uid) return p.send({ t: 'error', code: 'NOT_AVAILABLE' }); + if (p.state !== 'idle' || q.state !== 'idle') return p.send({ t: 'error', code: 'BUSY' }); + const f = economy.fighter(p.uid, p.name); + if (!f.ok) return p.send({ t: 'error', code: 'INVALID_ROBOT', errors: f.errors }); + const timer = setTimeout(() => { + if (!pending.has(p.uid)) return; + pending.delete(p.uid); setState(p, 'idle'); + p.send({ t: 'challenge.gone', to, reason: 'timeout' }); tell(to, { t: 'challenge.gone', from: p.uid, reason: 'timeout' }); + }, CHALLENGE_TTL); + if (timer.unref) timer.unref(); + pending.set(p.uid, { to, timer }); + setState(p, 'challenging'); + q.send({ t: 'challenge.in', from: p.uid, name: p.name, flag: f.flag, fame: f.fame }); + } + + function cancel(p) { + const c = pending.get(p.uid); if (!c) return; + clearTimeout(c.timer); pending.delete(p.uid); setState(p, 'idle'); + tell(c.to, { t: 'challenge.gone', from: p.uid, reason: 'cancelled' }); + } + + function decline(p, from) { + const c = pending.get(from); if (!c || c.to !== p.uid) return; + clearTimeout(c.timer); pending.delete(from); + const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: p.uid, reason: 'declined' }); } + } + + function accept(p, from) { + const c = pending.get(from), q = players.get(from); + if (!c || c.to !== p.uid || !q) return p.send({ t: 'error', code: 'NOT_AVAILABLE' }); + clearTimeout(c.timer); pending.delete(from); + const fa = economy.fighter(q.uid, q.name), fb = economy.fighter(p.uid, p.name); + if (!fa.ok || !fb.ok) { + setState(q, 'idle'); + const code = 'INVALID_ROBOT'; + if (!fa.ok) q.send({ t: 'error', code, errors: fa.errors }); else p.send({ t: 'error', code: 'OPPONENT_INVALID' }); + if (!fb.ok) p.send({ t: 'error', code, errors: fb.errors }); else q.send({ t: 'error', code: 'OPPONENT_INVALID' }); + return; + } + startMatch(fa, fb); + } + + function startMatch(fa, fb) { + const id = crypto.randomBytes(8).toString('hex'); + const seed = crypto.randomInt(1, 1e9); + const seats = seed % 2 ? [fa, fb] : [fb, fa]; // fair: who gets which start position is random + const room = runner.create({ + id, seed, + players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })), + send: (seat, msg) => tell(seats[seat].uid, msg), + onEnd: finish, + }); + if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now()); + seats.forEach((f, seat) => { + inMatch.set(f.uid, { id, seat }); + const pl = players.get(f.uid); if (pl) setState(pl, 'inmatch'); + tell(f.uid, room.startMsg(seat)); + }); + return room; + } + + function finish(room) { + const res = room.result; + if (matches) matches.end.run(res.winner, res.reason, now(), room.id); + room.players.forEach((pl, seat) => { + inMatch.delete(pl.uid); + const sm = room.summary(seat); + const won = res.winner === seat; + const r = economy.reward(pl.uid, Object.assign({ won, winner: res.winner === -1 ? -1 : won ? 0 : 1, reason: res.reason }, sm)); + tell(pl.uid, { t: 'match.end', matchId: room.id, seat, result: res, summary: sm, + reward: { money: r.money, fame: r.fame, lines: r.lines }, save: r.save }); + const p = players.get(pl.uid); if (p) setState(p, 'idle'); + }); + } + + function handle(uid, msg) { + const p = players.get(uid); if (!p) return; + switch (msg.t) { + case 'ping': return p.send({ t: 'pong', t0: msg.t0, serverTime: now() }); + case 'room': p.room = msg.room === 'all' ? null : msg.room; return setState(p, p.state); + case 'challenge': return challenge(p, msg.to); + case 'challenge.cancel': return cancel(p); + case 'challenge.accept': return accept(p, msg.from); + case 'challenge.decline': return decline(p, msg.from); + case 'input': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.input(m.seat, msg); return; } + case 'match.leave': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.forfeit(m.seat); return; } + } + } + + // the profile changed (robot, flag, fame): show it to everyone + function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); } + + return { join, leave, handle, refresh, startMatch, players, pending, inMatch }; +} + +module.exports = { createLobby, CHALLENGE_TTL }; diff --git a/server/match/room.js b/server/match/room.js index 4d976cd..f509ef8 100644 --- a/server/match/room.js +++ b/server/match/room.js @@ -47,6 +47,14 @@ class Room { if (raw && Number.isInteger(raw.seq)) this.acks[seat] = raw.seq; } disconnect(seat) { if (!this.away[seat]) this.away[seat] = 1; } + // player gives up: his robot is knocked out at once + forfeit(seat) { + const s = this.s, r = s.robots[seat]; + if (this.ended || !r || s.result) return; + r.hp = 0; r.dead = true; + s.result = { winner: 1 - seat, reason: 'ko' }; s.endIn = 0; + if (this.tickN <= COUNTDOWN) this.tickN = COUNTDOWN; // end now even during the countdown + } reconnect(seat) { this.away[seat] = 0; this.ai[seat] = null; } connected(seat) { return !this.away[seat]; } diff --git a/server/match/runner.js b/server/match/runner.js new file mode 100644 index 0000000..aacee77 --- /dev/null +++ b/server/match/runner.js @@ -0,0 +1,41 @@ +/* Drives all live rooms at a fixed 60 Hz. One timer for the whole server; catches up after a hitch + (max 10 ticks per wake-up), logs when a tick takes too long. */ +'use strict'; +const { Room, DT } = require('./room'); + +function createRunner(opt = {}) { + const rooms = new Map(); + const STEP = DT * 1000; + let next = 0, timer = null, slowLogged = 0; + + function loop() { + const now = performance.now(); + if (!next) next = now; + let n = 0; + while (now >= next && n < 10) { + const t0 = performance.now(); + for (const room of rooms.values()) room.tick(); + const ms = performance.now() - t0; + if (ms > 8 && Date.now() - slowLogged > 10000) { slowLogged = Date.now(); console.warn(`[match] slow tick ${ms.toFixed(1)} ms for ${rooms.size} rooms`); } + next += STEP; n++; + } + if (now - next > 250) next = now; // fell far behind (sleeping laptop, debugger): don't replay it + timer = setTimeout(loop, Math.max(0, next - performance.now())); + } + + return { + rooms, + create(o) { + const room = new Room(Object.assign({}, o, { + onEnd: r => { rooms.delete(r.id); if (o.onEnd) o.onEnd(r); }, + })); + rooms.set(room.id, room); + if (!timer && opt.autoStart !== false) loop(); + return room; + }, + get: id => rooms.get(id), + stop() { clearTimeout(timer); timer = null; next = 0; }, + }; +} + +module.exports = { createRunner }; diff --git a/server/package-lock.json b/server/package-lock.json index f7a5698..699ece4 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -11,7 +11,8 @@ "bcryptjs": "2.4.3", "better-sqlite3": "11.3.0", "express": "4.19.2", - "jsonwebtoken": "9.0.2" + "jsonwebtoken": "9.0.2", + "ws": "8.23.0" }, "engines": { "node": ">=20.6" @@ -1356,6 +1357,27 @@ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } } } } diff --git a/server/package.json b/server/package.json index f516a47..b51ce6f 100644 --- a/server/package.json +++ b/server/package.json @@ -10,12 +10,14 @@ "scripts": { "start": "node app.js", "dev": "node --env-file=.env --watch app.js", - "test": "node --test \"test/**/*.test.js\"" + "test": "node --test \"test/**/*.test.js\"", + "db:reset": "node scripts/reset-db.js" }, "dependencies": { - "express": "4.19.2", - "better-sqlite3": "11.3.0", "bcryptjs": "2.4.3", - "jsonwebtoken": "9.0.2" + "better-sqlite3": "11.3.0", + "express": "4.19.2", + "jsonwebtoken": "9.0.2", + "ws": "8.23.0" } } diff --git a/server/ratelimit.js b/server/ratelimit.js new file mode 100644 index 0000000..1aa2385 --- /dev/null +++ b/server/ratelimit.js @@ -0,0 +1,18 @@ +/* Tiny in-memory rate limiter (per IP + route group). Enough for one server; resets on restart. */ +'use strict'; + +function rateLimit({ windowMs = 60000, max = 10, name = 'rl' } = {}) { + const hits = new Map(); // key -> { n, reset } + const sweep = setInterval(() => { const now = Date.now(); for (const [k, v] of hits) if (v.reset < now) hits.delete(k); }, windowMs); + if (sweep.unref) sweep.unref(); + return (req, res, next) => { + const key = name + ':' + (req.ip || req.socket.remoteAddress); + const now = Date.now(); + let h = hits.get(key); + if (!h || h.reset < now) { h = { n: 0, reset: now + windowMs }; hits.set(key, h); } + if (++h.n > max) { res.set('Retry-After', String(Math.ceil((h.reset - now) / 1000))); return res.status(429).json({ error: 'RATE_LIMIT' }); } + next(); + }; +} + +module.exports = { rateLimit }; diff --git a/server/rtdb.js b/server/rtdb.js deleted file mode 100644 index 6742c0e..0000000 --- a/server/rtdb.js +++ /dev/null @@ -1,38 +0,0 @@ -/* Server-Sent-Events pub/sub so the client's db.stream(path) works like Firebase: - on subscribe we send one 'put' with the whole value, then a 'put' for every later change. - (The client applies 'put' by replacing the value at the given relative path; null = delete.) */ -'use strict'; -const { getTree, norm } = require('./db'); - -const subs = new Map(); // subPath -> Set - -function send(res, event, p, data) { - try { res.write(`event: ${event}\n`); res.write(`data: ${JSON.stringify({ path: p, data })}\n\n`); } catch (e) { /* closed */ } -} - -function subscribe(path, res) { - path = norm(path); - res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' }); - if (!subs.has(path)) subs.set(path, new Set()); - subs.get(path).add(res); - send(res, 'put', '/', getTree(path)); // initial snapshot - res.on('close', () => { const set = subs.get(path); if (set) { set.delete(res); if (!set.size) subs.delete(path); } }); -} - -// call after any write at writePath; pushes the change to every affected subscription -function notify(writePath) { - writePath = norm(writePath); - for (const [subPath, set] of subs) { - let evPath, data; - if (writePath === subPath) { evPath = '/'; data = getTree(subPath); } - else if (subPath === '' || writePath.startsWith(subPath + '/')) { evPath = '/' + (subPath ? writePath.slice(subPath.length + 1) : writePath); data = getTree(writePath); } - else if (subPath.startsWith(writePath + '/')) { evPath = '/'; data = getTree(subPath); } - else continue; - for (const res of set) send(res, 'put', evPath, data); - } -} - -const hb = setInterval(() => { for (const set of subs.values()) for (const res of set) { try { res.write(': ping\n\n'); } catch (e) { /* closed */ } } }, 25000); -if (hb.unref) hb.unref(); - -module.exports = { subscribe, notify }; diff --git a/server/rules.js b/server/rules.js deleted file mode 100644 index 0e34ddb..0000000 --- a/server/rules.js +++ /dev/null @@ -1,34 +0,0 @@ -/* Who may read/write which path - server-side (replaces Firebase database.rules.json). - req.uid is set by the auth middleware (null if not logged in). */ -'use strict'; -const { norm } = require('./db'); - -const ADMIN = (process.env.ADMIN_UID || '').split(',').map(s => s.trim()).filter(Boolean); -const seg = p => norm(p).split('/'); - -function canRead(req, path) { - const s = seg(path), top = s[0]; - switch (top) { - case 'ranks': case 'live': return true; // public (also without login) - case 'saves': case 'users': return !!req.uid && req.uid === s[1]; - case 'lobby': case 'tourney': return !!req.uid; - case 'challenges': return !!req.uid && req.uid === s[1]; - case 'matches': return !!req.uid && !!s[1] && s[1].includes(req.uid); - default: return false; - } -} - -function canWrite(req, path) { - const s = seg(path), top = s[0]; - if (!req.uid) return false; - switch (top) { - case 'saves': case 'ranks': case 'lobby': case 'users': return req.uid === s[1]; - case 'challenges': return s[1] === req.uid || s[2] === req.uid; // write to someone, or clear your own - case 'matches': return !!s[1] && s[1].includes(req.uid); - case 'tourney': return true; // registration is keyed by uid in the data - case 'live': return ADMIN.includes(req.uid); - default: return false; - } -} - -module.exports = { canRead, canWrite, seg, ADMIN }; diff --git a/server/scripts/reset-db.js b/server/scripts/reset-db.js new file mode 100644 index 0000000..2b2a90d --- /dev/null +++ b/server/scripts/reset-db.js @@ -0,0 +1,33 @@ +/* Reset the database to a clean state: backup copy, fresh schema, seed accounts. + Test system only (see CLAUDE.md). Stop the server first (systemctl stop robotclash), then: + npm run db:reset (in server/) + DB_FILE from the environment, default server/data.sqlite. */ +'use strict'; +const fs = require('fs'); +const path = require('path'); + +// Dev phase: fixed test accounts (plan T-1: move to .env before there is ever a production system). +const DEV_SEED_USERS = [ + { name: 'michi', pass: 'Michi2000!', role: 'admin' }, + { name: 'benni', pass: 'Benni2000!', role: 'admin' }, +]; + +const file = process.env.DB_FILE || path.join(__dirname, '..', 'data.sqlite'); +if (file !== ':memory:' && fs.existsSync(file)) { + const bak = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`; + fs.copyFileSync(file, bak); + for (const ext of ['', '-wal', '-shm']) if (fs.existsSync(file + ext)) fs.rmSync(file + ext); + console.log('backup:', bak); +} +process.env.DB_FILE = file; +process.env.JWT_SECRET = process.env.JWT_SECRET || 'reset-script-signs-nothing'; + +const { createUser } = require('../auth'); // opens + migrates the fresh database +const economy = require('../economy'); + +for (const u of DEV_SEED_USERS) { + const row = createUser({ name: u.name, pass: u.pass, role: u.role }); + economy.load(row.uid); // creates the starter online save + console.log(`seeded ${u.name} (${u.role})`); +} +console.log('database reset:', file); diff --git a/server/test/economy.test.js b/server/test/economy.test.js new file mode 100644 index 0000000..7796096 --- /dev/null +++ b/server/test/economy.test.js @@ -0,0 +1,73 @@ +'use strict'; +const { test, before, after } = require('node:test'); +const assert = require('node:assert/strict'); +const { startServer } = require('./helpers'); +const RC = globalThis.RC; + +let S; +before(async () => { S = await startServer(); }); +after(() => S.close()); + +const part = slot => Object.values(RC.PARTS).find(p => p.slot === slot && !Object.values(RC.STARTER).includes(p.id)); + +test('online save needs a login', async () => { + assert.equal((await S.json('GET', '/api/online')).status, 401); + assert.equal((await S.json('POST', '/api/online/action', { type: 'buy', part: 'x' })).status, 401); +}); + +test('shop actions run on the server and persist', async () => { + const a = await S.account(); + const p = part('armour'); + const r = await S.json('POST', '/api/online/action', { type: 'buy', part: p.id }, a.idToken); + assert.equal(r.status, 200); + assert.equal(r.body.ok, true); + assert.equal(r.body.save.money, 800 - p.cost); + const again = await S.json('GET', '/api/online', undefined, a.idToken); + assert.equal(again.body.money, 800 - p.cost, 'stored'); + assert.equal(again.body.build.armour, p.id); +}); + +test('refused actions return the authoritative save and change nothing', async () => { + const a = await S.account(); + const expensive = Object.values(RC.PARTS).filter(p => p.slot !== 'weapon').sort((x, y) => y.cost - x.cost)[0]; + const r = await S.json('POST', '/api/online/action', { type: 'buy', part: expensive.id }, a.idToken); + assert.equal(r.body.ok, false); + assert.equal(r.body.error, 'NO_MONEY'); + assert.equal(r.body.save.money, 800); +}); + +test('dev coins only for admins', async () => { + const a = await S.account(); + const r = await S.json('POST', '/api/online/action', { type: 'devCoins', money: 99999 }, a.idToken); + assert.equal(r.body.error, 'DENIED'); +}); + +test('cosmetics merge but money in the upload is ignored', async () => { + const a = await S.account(); + const r = await S.json('PUT', '/api/online/save', { money: 1e9, fame: 1e9, flag: 'AT', robots: [{ name: 'Rusty', paint: { body: 0x00ff00, accent: 0, decal: null } }] }, a.idToken); + assert.equal(r.status, 200); + assert.equal(r.body.money, 800); + assert.equal(r.body.fame, 0); + assert.equal(r.body.flag, 'AT'); + assert.equal(r.body.robotName, 'Rusty'); +}); + +test('ranking is public and only lists players with fame', async () => { + const r = await S.json('GET', '/api/ranks'); + assert.equal(r.status, 200); + assert.ok(Array.isArray(r.body)); + assert.ok(r.body.every(x => x.fame > 0)); +}); + +test('live settings: public read, admin-only write', async () => { + const a = await S.account(); + assert.equal((await S.json('PUT', '/api/admin/live', { motd: { en: 'hi' } }, a.idToken)).status, 403); + assert.equal((await S.json('GET', '/api/live')).status, 200); +}); + +test('campaign cloud save round trip', async () => { + const a = await S.account(); + await S.json('PUT', '/api/campaign', { money: 5, ts: 1 }, a.idToken); + const r = await S.json('GET', '/api/campaign', undefined, a.idToken); + assert.deepEqual(r.body, { money: 5, ts: 1 }); +}); diff --git a/server/test/health.test.js b/server/test/health.test.js index 2abadc6..19bff23 100644 --- a/server/test/health.test.js +++ b/server/test/health.test.js @@ -15,17 +15,19 @@ test('GET /healthz reports ok + version', async () => { assert.equal(typeof r.body.uptime, 'number'); }); -test('register -> login -> refresh rotates the refresh token', async () => { - const reg = await S.json('POST', '/api/auth/register', { email: 'a@test.dev', pass: 'secret123', name: 'Alice' }); +test('register by name -> login by name (any case) -> refresh rotates the token', async () => { + const reg = await S.json('POST', '/api/auth/register', { name: 'Alice', pass: 'secret123' }); assert.equal(reg.status, 200); assert.ok(reg.body.idToken && reg.body.refreshToken && reg.body.uid); - const login = await S.json('POST', '/api/auth/login', { email: 'A@test.dev ', pass: 'secret123' }); + const login = await S.json('POST', '/api/auth/login', { login: ' ALICE ', pass: 'secret123' }); assert.equal(login.status, 200); assert.equal(login.body.uid, reg.body.uid); + assert.equal(login.body.name, 'Alice'); const me = await S.json('GET', '/api/me', undefined, login.body.idToken); assert.equal(me.body.uid, reg.body.uid); + assert.equal(me.body.admin, false); const r1 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken }); assert.equal(r1.status, 200); @@ -33,7 +35,25 @@ test('register -> login -> refresh rotates the refresh token', async () => { assert.equal(r2.status, 401, 'an already used refresh token is rejected'); }); -test('wrong password is rejected', async () => { - const r = await S.json('POST', '/api/auth/login', { email: 'a@test.dev', pass: 'nope-nope' }); - assert.equal(r.status, 400); +test('register: optional e-mail works as login too; duplicates and weak passwords are refused', async () => { + const r = await S.json('POST', '/api/auth/register', { name: 'Bob', pass: 'secret123', email: 'Bob@Test.dev' }); + assert.equal(r.status, 200); + assert.equal((await S.json('POST', '/api/auth/login', { login: 'bob@test.dev', pass: 'secret123' })).status, 200); + assert.equal((await S.json('POST', '/api/auth/register', { name: 'bob', pass: 'secret123' })).body.error, 'NAME_EXISTS'); + assert.equal((await S.json('POST', '/api/auth/register', { name: 'Carl', pass: 'short' })).body.error, 'WEAK_PASSWORD'); + assert.equal((await S.json('POST', '/api/auth/register', { name: 'x', pass: 'secret123' })).body.error, 'BAD_NAME'); +}); + +test('wrong password is rejected', async () => { + const r = await S.json('POST', '/api/auth/login', { login: 'alice', pass: 'nope-nope' }); + assert.equal(r.status, 400); + assert.equal(r.body.error, 'INVALID_LOGIN'); +}); + +test('guest accounts get a token and an online save', async () => { + const g = await S.json('POST', '/api/auth/guest', { name: 'Gast' }); + assert.equal(g.status, 200); + assert.equal(g.body.guest, true); + const s = await S.json('GET', '/api/online', undefined, g.body.idToken); + assert.equal(s.body.money, 800); }); diff --git a/server/test/helpers.js b/server/test/helpers.js index 63b0915..bee525b 100644 --- a/server/test/helpers.js +++ b/server/test/helpers.js @@ -1,14 +1,18 @@ -/* Test helpers: start the real server on a random port with an in-memory database. */ +/* Test helpers: start the real server on a random port with an in-memory database; WebSocket test clients. */ 'use strict'; process.env.NODE_ENV = 'test'; process.env.DB_FILE = ':memory:'; delete process.env.JWT_SECRET; -const { listen } = require('../app'); +const WebSocket = require('ws'); +const srvMod = require('../app'); +const RC = globalThis.RC; +let n = 0; async function startServer() { - const srv = await listen(0); - const base = 'http://127.0.0.1:' + srv.address().port; + const srv = await srvMod.listen(0); + const port = srv.address().port; + const base = 'http://127.0.0.1:' + port; const json = async (method, path, body, token) => { const res = await fetch(base + path, { method, @@ -17,7 +21,56 @@ async function startServer() { }); return { status: res.status, body: await res.json().catch(() => null) }; }; - return { base, json, close: () => new Promise(r => { srv.closeAllConnections(); srv.close(r); }) }; + // a fresh registered account: { uid, idToken, ... } + const account = async (name) => { + const r = await json('POST', '/api/auth/register', { name: name || 'tester' + (++n), pass: 'secret123' }); + if (r.status !== 200) throw new Error('register failed ' + JSON.stringify(r.body)); + return r.body; + }; + // connected, greeted WebSocket client with a message inbox + const client = (token, opt = {}) => new Promise((resolve, reject) => { + const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); + const inbox = [], waiters = []; + const c = { + ws, inbox, + send: m => ws.send(JSON.stringify(m)), + // resolves with the first (already received or future) message matching type + predicate + next(t, pred = () => true, ms = 3000) { + const i = inbox.findIndex(m => m.t === t && pred(m)); + if (i >= 0) return Promise.resolve(inbox.splice(i, 1)[0]); + return new Promise((res, rej) => { + const w = { t, pred, res, timer: setTimeout(() => rej(new Error('timeout waiting for ' + t)), ms) }; + waiters.push(w); + }); + }, + closed: new Promise(r => ws.on('close', (code, reason) => r({ code, reason: String(reason) }))), + close: () => ws.close(), + }; + ws.on('message', d => { + const m = JSON.parse(d.toString()); + const wi = waiters.findIndex(w => w.t === m.t && w.pred(m)); + if (wi >= 0) { const w = waiters.splice(wi, 1)[0]; clearTimeout(w.timer); w.res(m); } else inbox.push(m); + }); + ws.on('open', () => { + if (opt.noHello) return resolve(c); + c.send({ t: 'hello', v: opt.v !== undefined ? opt.v : RC.Proto.VERSION, token }); + if (opt.expectFail) return resolve(c); + c.next('welcome').then(() => resolve(c), reject); + }); + ws.on('error', reject); + }); + const close = () => new Promise(r => { + srvMod.runner.stop(); + for (const ws of srvMod.wss.clients) ws.terminate(); + srv.closeAllConnections(); srv.close(() => r()); + }); + return { base, port, json, account, client, close, runner: srvMod.runner, lobby: srvMod.lobby }; } -module.exports = { startServer }; +// run every live room to its end without waiting for real time +function fastForward(runner, maxTicks = 60 * 300) { + runner.stop(); + for (let i = 0; i < maxTicks && runner.rooms.size; i++) for (const r of [...runner.rooms.values()]) r.tick(); +} + +module.exports = { startServer, fastForward }; diff --git a/server/test/lobby.test.js b/server/test/lobby.test.js new file mode 100644 index 0000000..c15fd21 --- /dev/null +++ b/server/test/lobby.test.js @@ -0,0 +1,138 @@ +'use strict'; +const { test, before, after } = require('node:test'); +const assert = require('node:assert/strict'); +const { startServer, fastForward } = require('./helpers'); +const RC = globalThis.RC; + +let S; +before(async () => { S = await startServer(); }); +after(() => S.close()); + +test('socket must authenticate with hello first', async () => { + const c = await S.client(null, { noHello: true }); + c.send({ t: 'room', room: 'DE' }); + assert.equal((await c.closed).code, 4001); + const bad = await S.client('not-a-token', { expectFail: true }); + assert.equal((await bad.next('error')).code, 'UNAUTH'); + assert.equal((await bad.closed).code, 4003); +}); + +test('old protocol version is told to reload', async () => { + const a = await S.account(); + const c = await S.client(a.idToken, { v: 0, expectFail: true }); + assert.equal((await c.next('error')).code, 'OUTDATED'); + assert.equal((await c.closed).code, 4002); +}); + +test('invalid messages get an error, the socket stays open', async () => { + const a = await S.account(); + const c = await S.client(a.idToken); + c.send({ t: 'input', seq: 1, throttle: 'fast' }); + assert.match((await c.next('error')).code, /BAD_FIELD/); + c.ws.send('{not json'); + assert.equal((await c.next('error')).code, 'BAD_JSON'); + c.close(); +}); + +test('presence: join and leave are pushed to the others', async () => { + const a = await S.account('Anna'), b = await S.account('Bert'); + const ca = await S.client(a.idToken); + await ca.next('lobby'); + const cb = await S.client(b.idToken); + const list = await cb.next('lobby'); + assert.ok(list.players.some(p => p.uid === a.uid && p.state === 'idle')); + assert.equal((await ca.next('lobby.join', m => m.player.uid === b.uid)).player.name, 'Bert'); + cb.close(); + assert.equal((await ca.next('lobby.leave', m => m.uid === b.uid)).uid, b.uid); + ca.close(); +}); + +test('challenge -> decline / cancel', async () => { + const a = await S.account(), b = await S.account(); + const ca = await S.client(a.idToken), cb = await S.client(b.idToken); + ca.send({ t: 'challenge', to: b.uid }); + assert.equal((await cb.next('challenge.in')).from, a.uid); + cb.send({ t: 'challenge.decline', from: a.uid }); + assert.equal((await ca.next('challenge.gone')).reason, 'declined'); + ca.send({ t: 'challenge', to: b.uid }); + await cb.next('challenge.in'); + ca.send({ t: 'challenge.cancel' }); + assert.equal((await cb.next('challenge.gone')).reason, 'cancelled'); + ca.send({ t: 'challenge', to: a.uid }); + assert.equal((await ca.next('error')).code, 'NOT_AVAILABLE', 'cannot challenge yourself'); + ca.close(); cb.close(); +}); + +test('full live match over WebSocket: both get start, snapshots, and mirrored results with rewards', async () => { + const a = await S.account(), b = await S.account(); + const ca = await S.client(a.idToken), cb = await S.client(b.idToken); + ca.send({ t: 'challenge', to: b.uid }); + await cb.next('challenge.in'); + cb.send({ t: 'challenge.accept', from: a.uid }); + const [sa, sb] = await Promise.all([ca.next('match.start'), cb.next('match.start')]); + assert.equal(sa.matchId, sb.matchId); + assert.deepEqual([sa.seat, sb.seat].sort(), [0, 1]); + assert.equal(sa.seed, sb.seed); + assert.equal(sa.arena, sb.arena); + assert.equal(sa.robots[sa.seat].uid, a.uid, 'my seat holds my robot'); + + // inputs flow in, then the server plays the rest at full speed + ca.send({ t: 'input', seq: 1, throttle: 1, turn: 0, fire: true, fire2: false, fire3: false }); + await new Promise(r => setTimeout(r, 50)); + fastForward(S.runner); + const [ea, eb] = await Promise.all([ca.next('match.end'), cb.next('match.end')]); + assert.deepEqual(ea.result, eb.result, 'same seat-based result for both'); + const la = RC.Proto.localResult(ea.seat, ea.result).winner, lb = RC.Proto.localResult(eb.seat, eb.result).winner; + if (ea.result.winner === -1) assert.ok(la === -1 && lb === -1); + else assert.ok((la === 0) !== (lb === 0), 'exactly one player won'); + assert.equal(ea.save.games, 1); + assert.equal(eb.save.games, 1); + assert.ok(ca.inbox.some(m => m.t === 'snap'), 'snapshots arrived before the end'); + + // rewards were booked on the server + const sA = await S.json('GET', '/api/online', undefined, a.idToken); + assert.equal(sA.body.money, ea.save.money); + ca.close(); cb.close(); +}); + +test('forfeit ends the match at once; disconnect + reconnect gets the running match back', async () => { + const a = await S.account(), b = await S.account(); + const ca = await S.client(a.idToken), cb = await S.client(b.idToken); + ca.send({ t: 'challenge', to: b.uid }); + await cb.next('challenge.in'); + cb.send({ t: 'challenge.accept', from: a.uid }); + const st = await ca.next('match.start'); + await cb.next('match.start'); + S.runner.stop(); + + // b drops and comes back: gets match.start again for the same match and seat + cb.close(); await cb.closed; + await ca.next('lobby.leave', m => m.uid === b.uid); + const room = S.runner.get(st.matchId); + assert.ok(room && !room.connected(1 - st.seat), 'room marks the seat as away'); + const cb2 = await S.client(b.idToken); + const again = await cb2.next('match.start'); + assert.equal(again.matchId, st.matchId); + assert.equal(again.seat, 1 - st.seat); + assert.ok(room.connected(1 - st.seat)); + + ca.send({ t: 'match.leave' }); + await new Promise(r => setTimeout(r, 30)); + fastForward(S.runner); + const ea = await ca.next('match.end'), eb = await cb2.next('match.end'); + assert.equal(RC.Proto.localResult(ea.seat, ea.result).winner, 1, 'the one who left lost'); + assert.equal(RC.Proto.localResult(eb.seat, eb.result).winner, 0); + ca.close(); cb2.close(); +}); + +test('an invalid robot cannot challenge', async () => { + const a = await S.account(), b = await S.account(); + // strip the battery via the economy: equip refuses required slots, so break the save directly + const econ = require('../economy'); + const s = econ.load(a.uid); s.robots[0].build.battery = null; require('../db').OnlineSaves.put(a.uid, s); + const ca = await S.client(a.idToken), cb = await S.client(b.idToken); + ca.send({ t: 'challenge', to: b.uid }); + const e = await ca.next('error'); + assert.equal(e.code, 'INVALID_ROBOT'); + ca.close(); cb.close(); +}); diff --git a/server/ws/hub.js b/server/ws/hub.js new file mode 100644 index 0000000..988f9a2 --- /dev/null +++ b/server/ws/hub.js @@ -0,0 +1,58 @@ +/* WebSocket endpoint /ws. Every socket must say { t:'hello', v, token } within HELLO_MS, then its messages + are validated (RC.Proto.check), rate limited and handed to the lobby. Keepalive via ws ping/pong. */ +'use strict'; +const { WebSocketServer } = require('ws'); +const RC = require('../../game/protocol.js'); +const auth = require('../auth'); + +const HELLO_MS = 5000; +const RATE = 80; // messages per second per socket (inputs ~30/s + lobby) +const PING_MS = 15000; + +function attach(server, { lobby }) { + const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG }); + + wss.on('connection', ws => { + let user = null, tokens = RATE, last = Date.now(); + ws.alive = true; + ws.on('pong', () => { ws.alive = true; }); + const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); }; + const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } }; + const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS); + + ws.on('message', (data, isBinary) => { + // token bucket + const now = Date.now(); tokens = Math.min(RATE, tokens + (now - last) * RATE / 1000); last = now; + if (--tokens < 0) return bye(4008, 'RATE_LIMIT'); + let msg; + try { msg = JSON.parse(isBinary ? data : data.toString()); } catch (e) { return send({ t: 'error', code: 'BAD_JSON' }); } + const c = RC.Proto.check(msg); + if (!c.ok) return send({ t: 'error', code: c.error }); + if (!user) { + if (msg.t !== 'hello') return bye(4001, 'HELLO_FIRST'); + if (msg.v !== RC.Proto.VERSION) { send({ t: 'error', code: 'OUTDATED', need: RC.Proto.VERSION }); return bye(4002, 'OUTDATED'); } + const u = auth.verify(msg.token); + if (!u) { send({ t: 'error', code: 'UNAUTH' }); return bye(4003, 'UNAUTH'); } + clearTimeout(helloTimer); + user = u; + send({ t: 'welcome', uid: u.uid, name: u.name, serverTime: Date.now(), v: RC.Proto.VERSION }); + lobby.join({ uid: u.uid, name: u.name, admin: u.admin, send }); + return; + } + if (msg.t === 'hello') return; + lobby.handle(user.uid, msg); + }); + + ws.on('close', () => { clearTimeout(helloTimer); if (user) lobby.leave(user.uid, send); }); + ws.on('error', () => {}); + }); + + const beat = setInterval(() => { + for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closed */ } } + }, PING_MS); + if (beat.unref) beat.unref(); + wss.on('close', () => clearInterval(beat)); + return wss; +} + +module.exports = { attach };