feat(server): healthz, testable app, local dev script (P0-3)

This commit is contained in:
Benjamin Oezcan
2026-11-19 01:40:31 +01:00
parent 35348324d6
commit fa68ef620d
8 changed files with 1465 additions and 16 deletions

View File

@@ -1,6 +1,7 @@
# Copy to server/.env and fill in. Never commit the real .env. # Copy to server/.env (local dev: npm run dev). Never commit the real .env.
PORT=8080 PORT=8080
JWT_SECRET=change-me-to-a-long-random-string # Long random string. Empty = random per start (fine locally; sessions end on restart).
# comma-separated uids allowed to write /db/live (admin). Fill after you create your admin account. JWT_SECRET=
# comma-separated uids allowed to write /db/live (admin). Replaced by seed accounts later (plan P2-1b).
ADMIN_UID= ADMIN_UID=
DB_FILE=./data.sqlite DB_FILE=./data.sqlite

View File

@@ -4,17 +4,21 @@ Node-Backend: Konten, Spielstände, Rangliste, Lobby, Live-PvP und **server-auto
alte Firebase-Oberfläche (Auth + `/db`-REST + SSE), damit der Client nur die Basis-URL tauscht. Serviert alte Firebase-Oberfläche (Auth + `/db`-REST + SSE), damit der Client nur die Basis-URL tauscht. Serviert
zusätzlich das Spiel aus `../game` (gleiche Domain → kein CORS, kein Mixed-Content). zusätzlich das Spiel aus `../game` (gleiche Domain → kein CORS, kein Mixed-Content).
## Lokal testen (WSL/Ubuntu oder Linux) ## Lokal starten (Windows, WSL oder Linux, Node ≥ 20.6)
``` ```
cd server npm run setup # einmal im Repo-Root: Abhängigkeiten für Root + server/
cp .env.example .env # JWT_SECRET setzen cp server/.env.example server/.env # einmal
npm install # express, better-sqlite3 (braucht build-essential), bcryptjs, jsonwebtoken npm run dev # Server mit Auto-Neustart auf http://localhost:8080
npm start # Server auf http://localhost:8080
``` ```
`better-sqlite3` braucht einen Compiler: `sudo apt install -y build-essential python3`. Spiel unter `http://localhost:8080/`, Status unter `/healthz`. SQLite-Datei: `server/data.sqlite` (ignoriert).
Spiel dann unter `http://localhost:8080/`. SQLite-Datei: `server/data.sqlite` (per `.gitignore` ignoriert). Unter Linux braucht `better-sqlite3` evtl. einen Compiler: `sudo apt install -y build-essential python3`.
## Tests
`npm test` im Repo-Root startet Spiel- und Server-Tests. Server-Tests (`server/test/*.test.js`) starten den echten
Server auf einem Zufallsport mit In-Memory-DB (`test/helpers.js`).
## API (Kurzüberblick) ## API (Kurzüberblick)

View File

@@ -9,10 +9,18 @@ const rtdb = require('./rtdb');
const eco = require('./economy'); const eco = require('./economy');
const { getTree, putTree, patchTree, pushTree, delTreeAt, norm } = require('./db'); const { getTree, putTree, patchTree, pushTree, delTreeAt, norm } = require('./db');
const pkg = require('./package.json');
const STARTED = Date.now();
const app = express(); 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(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.use(auth.auth); // sets req.uid / req.user (null if not logged in)
// --- health (deploy checks, monitoring) --------------------------------------------------------------
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),
}));
function run(res, fn) { try { res.json(fn()); } catch (e) { res.status(e.status || 500).json({ error: e.code || 'ERROR' }); } } function run(res, fn) { try { res.json(fn()); } catch (e) { res.status(e.status || 500).json({ error: e.code || 'ERROR' }); } }
// --- accounts -------------------------------------------------------------------------------------- // --- accounts --------------------------------------------------------------------------------------
@@ -81,5 +89,10 @@ app.use(express.static(path.join(__dirname, '..', 'game'), {
}, },
})); }));
const PORT = process.env.PORT || 8080; // started directly (node app.js) -> listen; required by tests -> they call listen() themselves
app.listen(PORT, () => console.log('Robot Clash server on :' + PORT)); function listen(port = process.env.PORT || 8080) {
return new Promise(resolve => { const srv = app.listen(port, () => resolve(srv)); });
}
if (require.main === module) listen().then(srv => console.log('Robot Clash server on :' + srv.address().port));
module.exports = { app, listen };

View File

@@ -6,7 +6,11 @@ const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { Users, Wallet, Tokens } = require('./db'); const { Users, Wallet, Tokens } = require('./db');
const SECRET = process.env.JWT_SECRET || 'dev-insecure-change-me'; // No secret configured -> random per process (tokens die on restart). Never fall back to a known string.
const SECRET = process.env.JWT_SECRET || (() => {
if (process.env.NODE_ENV !== 'test') console.warn('[auth] JWT_SECRET not set - using a random secret, sessions end on restart');
return crypto.randomBytes(32).toString('hex');
})();
const ACCESS_TTL = 3600; // seconds const ACCESS_TTL = 3600; // seconds
const REFRESH_TTL = 30 * 864e5; // 30 days (ms) const REFRESH_TTL = 30 * 864e5; // 30 days (ms)
const START_MONEY = 800; const START_MONEY = 800;

1361
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,16 @@
{ {
"name": "robotclash-server", "name": "robotclash-server",
"version": "1.0.0", "version": "0.1.0",
"private": true, "private": true,
"description": "Robot Clash backend - auth, saves, ranks, lobby, live PvP relay, server-authoritative economy.", "description": "Robot Clash backend - auth, saves, ranks, lobby, live PvP, server-authoritative economy.",
"main": "app.js", "main": "app.js",
"engines": {
"node": ">=20.6"
},
"scripts": { "scripts": {
"start": "node app.js", "start": "node app.js",
"test": "node test.js" "dev": "node --env-file=.env --watch app.js",
"test": "node --test \"test/**/*.test.js\""
}, },
"dependencies": { "dependencies": {
"express": "4.19.2", "express": "4.19.2",

View File

@@ -0,0 +1,39 @@
'use strict';
const { test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { startServer } = require('./helpers');
let S;
before(async () => { S = await startServer(); });
after(() => S.close());
test('GET /healthz reports ok + version', async () => {
const r = await S.json('GET', '/healthz');
assert.equal(r.status, 200);
assert.equal(r.body.ok, true);
assert.equal(r.body.version, require('../package.json').version);
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' });
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' });
assert.equal(login.status, 200);
assert.equal(login.body.uid, reg.body.uid);
const me = await S.json('GET', '/api/me', undefined, login.body.idToken);
assert.equal(me.body.uid, reg.body.uid);
const r1 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken });
assert.equal(r1.status, 200);
const r2 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken });
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);
});

23
server/test/helpers.js Normal file
View File

@@ -0,0 +1,23 @@
/* Test helpers: start the real server on a random port with an in-memory database. */
'use strict';
process.env.NODE_ENV = 'test';
process.env.DB_FILE = ':memory:';
delete process.env.JWT_SECRET;
const { listen } = require('../app');
async function startServer() {
const srv = await listen(0);
const base = 'http://127.0.0.1:' + srv.address().port;
const json = async (method, path, body, token) => {
const res = await fetch(base + path, {
method,
headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}),
body: body === undefined ? undefined : JSON.stringify(body),
});
return { status: res.status, body: await res.json().catch(() => null) };
};
return { base, json, close: () => new Promise(r => { srv.closeAllConnections(); srv.close(r); }) };
}
module.exports = { startServer };