Compare commits

..

4 Commits

Author SHA1 Message Date
Benjamin Oezcan
06b60a45d4 docs: update commands, mark firebase docs outdated, close phase 0 (P0-5, P0-6) 2026-11-19 01:42:08 +01:00
Benjamin Oezcan
1156bc68eb chore: add eslint, remove dead variables, pin line endings (P0-4) 2026-11-19 01:41:27 +01:00
Benjamin Oezcan
fa68ef620d feat(server): healthz, testable app, local dev script (P0-3) 2026-11-19 01:40:31 +01:00
Benjamin Oezcan
35348324d6 test: single npm test entry point, drop firebase live test (P0-2) 2026-11-19 01:40:30 +01:00
20 changed files with 2657 additions and 128 deletions

10
.gitattributes vendored Normal file
View File

@@ -0,0 +1,10 @@
* text=auto
*.sh text eol=lf
*.ps1 text eol=crlf
*.png binary
*.jpg binary
*.ogg binary
*.wav binary
*.mp3 binary
*.ttf binary
*.sqlite binary

View File

@@ -93,7 +93,7 @@ Host* ruckelt es, während der Gast flüssig bleibt. Zahlen werden auf 3 Nachkom
Rangliste: `Kit.scores.top()` zeigt **jeden Spieler nur einmal** (bester Lauf) – jeder Eintrag ist eine eigene
Zeile in der DB, die Entdopplung passiert beim Lesen (Fix liegt in `_Tools\Library\web\kit\kit-scores.js`).
**Online (Firebase, optional):** Titel → „Online spielen" (nur wenn `NET_CFG.apiKey` gesetzt), Login per
**Online (Firebase, optional) – VERALTET, wird in Plan-Task P1-8 ersetzt (eigener Server, WebSocket):** Titel → „Online spielen" (nur wenn `NET_CFG.apiKey` gesetzt), Login per
E-Mail/Passwort, globale Lobby (alle Online-Spieler + Länderflagge), Klick auf Spieler = Herausfordern → Live-Kampf.
Rangliste läuft schon mit `DB_URL` allein. Einrichtung + Grenzen: `docs/firebase/README.md`.
@@ -122,7 +122,9 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
· `game/profiles.js` Konten (v1 lokal: Name + Passwort-Hash, je Konto eigener Spielstand; später Firebase)
· `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen.
- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten).
- Tests: `node tests/sim.test.js` (Regeln, Kämpfe ohne NaN, Grube), `node tests/balance.js [-v]` (Zahlen).
- Kommandos (Repo-Root): `npm run setup` (einmal), `npm test` (alle Tests: `tests/*.test.js` Regeln/Kämpfe ohne NaN/
Grube + `server/test/*.test.js` echter Server mit In-Memory-DB), `npm run lint` (ESLint), `npm run balance`
(Zahlen), `npm run dev` (Server lokal auf :8080, braucht `server/.env` aus `.env.example`).
- Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG),
`gen make_tileable tex_floor`, `gen adopt_audio --all`. Fehlende Bilder → Ersatz-Symbol (`RC.pic`), fehlende Sounds → Synth.
- `game/uicheck.js` Layout-Selbsttest: `&uicheck` misst Scrollen, Überläufe, Überlappungen, zu kleine Tap-Ziele,

View File

@@ -23,7 +23,18 @@ Angelegt am 2026-11-13 aus `_Tools\Library` (Vorlage `webgame`). Sprachen: Engli
Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (direkt in den Shop, als Gast), `?play&paint` (Lackiererei mit Testbild), `?fight=N` (Training gegen Liga-Gegner N = 0…7),
`&auto` (KI fährt deinen Roboter), `&ff=30` (30 Sekunden vorspulen), `&cam=chase|fpv` (Kamera).
Tests (Node, ohne Browser): `node tests/sim.test.js` · Balance-Zahlen: `node tests/balance.js -v`
Entwickeln (Node ≥ 22, im Repo-Root):
```
npm run setup # einmal: Abhängigkeiten (Root + server/)
npm test # alle Tests (Spiel-Logik + Server)
npm run lint # ESLint
npm run dev # Server + Spiel lokal auf http://localhost:8080 (vorher server/.env aus .env.example)
npm run balance # Balance-Zahlen
```
**Laufender Umbau** (Multiplayer server-autoritativ, Firebase raus, Deploy): [`docs/MULTIPLAYER-PLAN.md`](docs/MULTIPLAYER-PLAN.md).
Git: direkt auf `main` (= Dev), Conventional Commits, Regeln in `CLAUDE.md`.
## Aufbau
@@ -58,8 +69,8 @@ build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.z
## Online (optional)
Rangliste läuft mit der Firebase-DB-URL allein. Für die Lobby + Live-PvP den Web-API-Key in
`game/game.js` (`NET_CFG.apiKey`) eintragen – Anleitung `docs/firebase/README.md`.
Online läuft über den eigenen Node-Server (`server/`, Deploy siehe `server/deploy/README.md`).
> **Veraltet:** Firebase-Hinweise (`docs/firebase/`, `NET_CFG.apiKey`) gelten nicht mehr und werden mit Plan-Task P1-8 entfernt.
## Release

View File

@@ -149,19 +149,23 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
- [x] **P0-1 Git-Ablauf.** Kein Branch-Workflow: Michi und Benni arbeiten im Pair Programming und committen **direkt
auf `main`** (= Dev). Branches nur für echte Experimente, die evtl. verworfen werden. Keine PRs, keine Merges.
*AK:* README beschreibt den Ablauf.
- [ ] **P0-2 Ein Test-Kommando.** Root-`package.json`: `npm test` führt alle Tests aus (Node-eigener Runner
`node --test`, keine weitere Bibliothek nötig). `tests/sim.test.js` und `tests/balance.js` eingebunden.
`tests/online.test.js` (Firebase) löschen. *AK:* `npm test` grün, Exit-Code ≠ 0 bei Fehler.
- [ ] **P0-3 Server lokal startbar.** `server/package.json`: `dev` (mit `node --env-file=.env --watch app.js`,
Node ≥ 20.6, kein dotenv nötig), `test`. Server bricht ab, wenn `JWT_SECRET` fehlt oder der Standardwert ist
(außer `NODE_ENV=test`). `GET /healthz` → `{ ok, version, commit, uptime }`. *AK:* `npm run dev` startet, `/healthz` antwortet.
- [ ] **P0-4 Lint + Format.** ESLint (flat config, `eslint:recommended`, Browser- und Node-Globals) + Prettier mit den
bestehenden Konventionen (Zeilenlänge 120). `npm run lint`. Bestehende Fehler beheben oder gezielt deaktivieren
(dokumentieren). *AK:* `npm run lint` ohne Fehler.
- [ ] **P0-5 Qualitätsregeln in `CLAUDE.md`** (Abschnitt „Qualitätsregeln“ steht schon drin – prüfen, ergänzen).
- [ ] **P0-6 Doku bereinigen.** Alle Firebase-Erwähnungen in `CLAUDE.md`, `README.md`, Kommentaren markieren
(werden in P1-8 entfernt). Dieses Dokument im README verlinken.
*AK:* CLAUDE.md beschreibt den Ablauf.
- [x] **P0-2 Ein Test-Kommando.** `npm test` (Root) = `node --test` über `tests/**/*.test.js` + `server/test/**/*.test.js`;
`npm run balance` für die Balance-Zahlen (kein Test, nur Ausgabe). `tests/online.test.js` (Firebase) gelöscht.
Einmalig `npm run setup` (installiert Root + `server/`). Versionen auf `0.1.0` (SemVer, 0.x bis Prod).
- [x] **P0-3 Server lokal startbar.** `npm run dev` (Root oder `server/`) = `node --env-file=.env --watch app.js`.
Ohne `JWT_SECRET` nimmt der Server ein zufälliges Secret pro Start (kein bekannter Fallback-String mehr).
`GET /healthz` → `{ ok, version, commit, uptime }`; `app.js` exportiert `{ app, listen }` für Tests.
Erste Server-Tests: `server/test/health.test.js` (Health, Register/Login, Refresh-Rotation, falsches Passwort).
- [x] **P0-4 Lint.** ESLint 9 (flat config `eslint.config.js`, nur `recommended`, keine Stilregeln), `npm run lint`:
0 Fehler. **Bewusst kein Prettier** – ein Massen-Reformat würde den kompakten Stil zerstören und jede Zeile im
Diff ändern. Ignoriert: `game/vendor`, `game/kit` (Library-Kopie), `admin/` (fliegt in P1-8 raus).
Toten Code entfernt. Zwei Warnungen bleiben absichtlich: `scores` in `game.js` (Firebase-Rest → P1-8) und
`bye` in `tests/sim.test.js:442` – **halbfertiger Test** (Wert berechnet, nie geprüft) → beim nächsten Anfassen
der Turnier-Logik eine echte Prüfung ergänzen. `.gitattributes`: `*.sh` immer LF (sonst bricht `setup.sh` unter Linux).
- [x] **P0-5 Qualitätsregeln in `CLAUDE.md`** inkl. Conventional Commits, SemVer, Test-System-Hinweis.
- [x] **P0-6 Doku.** README verlinkt diesen Plan und die neuen Kommandos. Firebase-Texte in README/CLAUDE.md sind als
veraltet markiert und werden mit dem Code in P1-8 entfernt.
### Phase 1 – Server-autoritativer Kampf über WebSocket
@@ -231,6 +235,9 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
und `deploy` (SSH-Key, darf nur Deploy-Skript + `systemctl restart robotclash*` per sudoers), Passwort-Login in
SSH aus, `unattended-upgrades`, ufw (22/80/443), fail2ban. Root-Login erst abschalten, wenn `deploy` sicher geht.
*AK:* `ssh deploy@roboclash.michael-media.de` per Key geht, Dienst läuft nicht mehr als root.
- [ ] **P3-1b Node auf 24 LTS heben.** Auf dem Server läuft Node **20.20** – seit 30.04.2026 ohne Support (EOL).
`setup.sh` auf NodeSource `setup_24.x` umstellen, auf der VM aktualisieren, `npm rebuild` (better-sqlite3 ist
nativ). Lokal wird schon mit Node 24 entwickelt. *AK:* `node -v` auf der VM = v24.x, `/healthz` ok.
- [ ] **P3-2 Dienst + Caddy für die Umgebung `dev`** (Abschnitt 5): systemd-Unit mit `User=robotclash`,
`NoNewPrivileges`, `ProtectSystem=strict`, `ReadWritePaths` nur Datenordner. Caddyfile: **kein `encode` auf
`/ws`**. Produktion später = zweite Unit + zweiter Caddy-Block. *AK:* `/healthz` per HTTPS erreichbar.

33
eslint.config.js Normal file
View File

@@ -0,0 +1,33 @@
// ESLint (flat config). `npm run lint`. Catches real bugs (undefined names, unused code, typos) - no style rules.
'use strict';
const js = require('@eslint/js');
const globals = require('globals');
// shared across the classic <script> files of the game (no modules, see CLAUDE.md)
const gameGlobals = { RC: 'writable', Kit: 'writable', THREE: 'readonly', KIT_ASSETS: 'readonly', module: 'readonly', require: 'readonly' };
module.exports = [
{
ignores: ['node_modules/**', 'server/node_modules/**', 'release/**', 'game/vendor/**', 'game/kit/**',
'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**'],
},
js.configs.recommended,
{
rules: {
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }],
'no-empty': ['error', { allowEmptyCatch: true }],
},
},
{
files: ['game/**/*.js', 'tools/**/*.js'],
languageOptions: { sourceType: 'script', globals: { ...globals.browser, ...gameGlobals } },
},
{
files: ['server/**/*.js', 'tests/**/*.js', 'eslint.config.js'],
languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } },
},
{
files: ['**/*.mjs'],
languageOptions: { sourceType: 'module', globals: { ...globals.node } },
},
];

View File

@@ -33,7 +33,6 @@
}
const saw = (x, z, phase) => ({ x, z, r: 0.95, period: 6, on: 2.2, phase });
const flame = (x, z, phase) => ({ x, z, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase });
const saw2 = saw, flame2 = flame;
const block = (kind, x, z, hw, hd, h2) => ({ kind, x, z, hw, hd, h: h2 || 0.8 });
const belt = (x, z, hw, hd, ax, az, force) => ({ x, z, hw, hd, ax, az, force });
const ram = (x, z, hw, hd, nx, nz, phase) => ({ x, z, hw, hd, nx, nz, period: 5, on: 1.3, phase });

View File

@@ -661,7 +661,6 @@
// per-frame robot animation from the combat state
function poseRobot(R, r, dt) {
const w = R.st.weapon;
R.root.position.set(r.x, r.y, r.z);
R.root.rotation.y = -r.a;
// upside down when flipped
@@ -759,7 +758,7 @@
const scene_add = o => group.add(o);
scene.background = new T.Color(th.bg);
scene.fog = new T.Fog(th.fog, half * 3, half * 5.5);
const { key, rimA, rimB, flashLight } = out.lights;
const { key, rimA, rimB } = out.lights;
const sc = Math.max(11, half + 3);
Object.assign(key.shadow.camera, { left: -sc, right: sc, top: sc, bottom: -sc }); key.shadow.camera.updateProjectionMatrix();
rimA.color.setHex(th.rimA); rimA.position.set(-half - 1, 5, half + 1); rimA.distance = half * 2.6;
@@ -1343,7 +1342,6 @@
// ---- intro: dark arena -> floodlights flicker on -> camera sweeps up -> two robots are lowered in
const INTRO_END = RC.INTRO_END = 5.2;
const ease = u => (u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2);
function lightsOn(k) {
const L = arena.lights;
L.key.intensity = 1.25 * k; L.rimA.intensity = 1.1 * k; L.rimB.intensity = 0.9 * k;

View File

@@ -15,7 +15,6 @@
// ready-made [body, accent] combinations
RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230],
[0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]];
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
const SELL = 0.5;
const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_gadget' };
const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥', gadget: '🧰' };

1094
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,25 @@
{
"name": "robot-clash",
"version": "1.0.0",
"version": "0.1.0",
"private": true,
"description": "Robot Clash - build helpers only (the game itself needs no build step).",
"description": "Robot Clash - tests, lint and build helpers (the game itself needs no build step).",
"engines": {
"node": ">=22"
},
"scripts": {
"setup": "npm install && npm --prefix server install",
"test": "node --test \"tests/**/*.test.js\" \"server/test/**/*.test.js\"",
"test:game": "node --test \"tests/**/*.test.js\"",
"test:server": "npm --prefix server test",
"balance": "node tests/balance.js -v",
"lint": "eslint .",
"dev": "npm --prefix server run dev",
"build:web": "node build-web.mjs"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"eslint": "^9.39.5",
"globals": "^16.5.0",
"terser": "^5.46.1"
}
}

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
JWT_SECRET=change-me-to-a-long-random-string
# comma-separated uids allowed to write /db/live (admin). Fill after you create your admin account.
# Long random string. Empty = random per start (fine locally; sessions end on restart).
JWT_SECRET=
# comma-separated uids allowed to write /db/live (admin). Replaced by seed accounts later (plan P2-1b).
ADMIN_UID=
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
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
cp .env.example .env # JWT_SECRET setzen
npm install # express, better-sqlite3 (braucht build-essential), bcryptjs, jsonwebtoken
npm start # Server auf http://localhost:8080
npm run setup # einmal im Repo-Root: Abhängigkeiten für Root + server/
cp server/.env.example server/.env # einmal
npm run dev # Server mit Auto-Neustart auf http://localhost:8080
```
`better-sqlite3` braucht einen Compiler: `sudo apt install -y build-essential python3`.
Spiel dann unter `http://localhost:8080/`. SQLite-Datei: `server/data.sqlite` (per `.gitignore` ignoriert).
Spiel unter `http://localhost:8080/`, Status unter `/healthz`. SQLite-Datei: `server/data.sqlite` (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)

View File

@@ -9,10 +9,18 @@ const rtdb = require('./rtdb');
const eco = require('./economy');
const { getTree, putTree, patchTree, pushTree, delTreeAt, norm } = require('./db');
const pkg = require('./package.json');
const STARTED = Date.now();
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)
// --- 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' }); } }
// --- accounts --------------------------------------------------------------------------------------
@@ -81,5 +89,10 @@ app.use(express.static(path.join(__dirname, '..', 'game'), {
},
}));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log('Robot Clash server on :' + PORT));
// started directly (node app.js) -> listen; required by tests -> they call listen() themselves
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 { 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 REFRESH_TTL = 30 * 864e5; // 30 days (ms)
const START_MONEY = 800;

View File

@@ -64,7 +64,6 @@ function getTree(p) {
}
const setNode = db.prepare('INSERT INTO nodes (path, data, ts) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET data = excluded.data, ts = excluded.ts');
const delExact = db.prepare('DELETE FROM nodes WHERE path = ?');
const delTree = db.prepare('DELETE FROM nodes WHERE path = ? OR path LIKE ?');
function putTree(p, value) { // replace the whole subtree at p

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",
"version": "1.0.0",
"version": "0.1.0",
"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",
"engines": {
"node": ">=20.6"
},
"scripts": {
"start": "node app.js",
"test": "node test.js"
"dev": "node --env-file=.env --watch app.js",
"test": "node --test \"test/**/*.test.js\""
},
"dependencies": {
"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 };

View File

@@ -1,84 +0,0 @@
// Live test against the real Firebase project (needs network): node --experimental-eventsource tests/online.test.js
// Creates two throw-away accounts, runs lobby -> challenge -> match -> state/input sync, then deletes everything.
'use strict';
const path = require('path');
const mem = {};
global.window = globalThis;
global.Kit = { store: () => ({ get: (k, d) => (k in mem ? mem[k] : d), set: (k, v) => { mem[k] = v; } }), cleanName: s => String(s || '').slice(0, 20) };
for (const f of ['parts.js', 'robot.js', 'combat.js', 'ai.js', 'net.js', 'lobby.js', 'netfight.js']) require(path.join(__dirname, '..', 'game', f));
const RC = globalThis.RC;
const CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: 'https://robot-clash-aa37b-default-rtdb.firebaseio.com' };
const sleep = ms => new Promise(r => setTimeout(r, ms));
let fails = 0;
const ok = (c, msg) => { console.log((c ? 'ok ' : 'FAIL ') + msg); if (!c) fails++; };
(async () => {
const stamp = Date.now();
const A = RC.Net(CFG), B = RC.Net(CFG);
ok(A.enabled, 'config accepted');
const ra = await A.auth.register(`rc-test-a-${stamp}@example.com`, 'test-pass-123', 'TestA');
const rb = await B.auth.register(`rc-test-b-${stamp}@example.com`, 'test-pass-123', 'TestB');
ok(ra.ok && rb.ok, `register two accounts ${ra.error || ''} ${rb.error || ''}`);
if (!ra.ok || !rb.ok) process.exit(1);
const again = RC.Net(CFG); const rl = await again.auth.login(`RC-TEST-A-${stamp}@example.com `, 'test-pass-123');
ok(rl.ok && again.auth.current.name === 'TestA', `login again shows the real name (${again.auth.current && again.auth.current.name}), e-mail case/space tolerant`);
const G = RC.Net(CFG); const rg = await G.auth.guest('GastTest');
ok(rg.ok && G.auth.current.guest, 'anonymous guest sign-in ' + (rg.error || ''));
const LG = RC.Lobby({ net: G, getProfile: () => ({ name: 'GastTest', flag: 'DE', build: RC.STARTER, paint: { body: 1, accent: 2 }, fame: 0 }) });
await LG.enter();
const wrong = await RC.Net(CFG).auth.login(`rc-test-a-${stamp}@example.com`, 'nope-nope');
ok(!wrong.ok, 'wrong password rejected: ' + wrong.error);
const prof = n => () => ({ name: n, flag: 'DE', build: RC.STARTER, paint: { body: 1, accent: 2 }, fame: 5 });
const LA = RC.Lobby({ net: A, getProfile: prof('TestA') }), LB = RC.Lobby({ net: B, getProfile: prof('TestB') });
let listA = [], incomingB = null, matchA = null, matchB = null;
LA.onList(r => { listA = r; }); LB.onIncoming(c => { incomingB = c; });
LA.onMatch(m => { matchA = m; }); LB.onMatch(m => { matchB = m; });
await LA.enter(); await LB.enter();
await sleep(2500);
ok(listA.some(r => r.uid === B.uid && r.name === 'TestB' && r.flag === 'DE'), 'A sees B in the lobby (push stream)');
ok(listA.some(r => r.uid === G.uid && r.name === 'GastTest'), 'A sees the anonymous guest in the lobby');
LG.leave();
LA.challenge(B.uid);
await sleep(2500);
ok(incomingB && incomingB.from === A.uid, 'B receives the challenge');
const t0 = Date.now();
if (incomingB) await LB.accept(A.uid);
while (!(matchA && matchB) && Date.now() - t0 < 12000) await sleep(100);
console.log(` match start took ${Date.now() - t0} ms (A ${!!matchA}, B ${!!matchB})`);
ok(matchA && matchB && matchA.id === matchB.id, 'both sides get the match');
ok(matchA && matchB && matchA.host !== matchB.host, 'exactly one host');
ok(matchA && matchA.opp.name === 'TestB' && matchB.opp.name === 'TestA', 'opponent data arrives');
if (matchA && matchB) {
const host = matchA.host ? A : B, guest = matchA.host ? B : A, id = matchA.id;
const mk = () => RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: matchA.seed });
const sH = mk(), sG = mk();
const nfH = RC.NetFight({ net: host, id, host: true }), nfG = RC.NetFight({ net: guest, id, host: false });
nfH.start(); nfG.start();
for (let i = 0; i < 35; i++) { nfH.idle(0.1); nfG.idle(0.1); await sleep(100); } // 3.5 s countdown like the game
for (let i = 0; i < 180; i++) { // 3 s real time
nfH.hostStep(sH, { throttle: 1, turn: 0 }, 1 / 60); sH.events.length = 0;
nfG.guestFrame(sG, { throttle: 1, turn: 0.5, fire: false, fire2: false }, 1 / 60);
await sleep(16);
}
await sleep(800);
nfG.guestFrame(sG, { throttle: 1, turn: 0.5, fire: false, fire2: false }, 1 / 60);
ok(sG.t > 1, `guest receives host snapshots (t=${sG.t.toFixed(2)})`);
ok(Math.abs(sG.robots[1].x - sH.robots[0].x) < 1.5, `guest sees host robot near its real place (${sG.robots[1].x.toFixed(2)} vs ${sH.robots[0].x.toFixed(2)})`);
ok(Math.abs(sH.robots[1].a - Math.PI) > 0.2, `host applies guest input (guest robot turned, a=${sH.robots[1].a.toFixed(2)})`);
ok(nfH.peerAlive && nfG.peerAlive, 'both peers alive');
// rules: guest must not be able to write the state, a stranger must not read the match
ok((await guest.db.put(`matches/${id}/state`, { seq: 1 })) === false, 'rule: guest cannot write host state');
nfH.stop(); nfG.stop();
}
// cleanup: lobby, match, challenge, accounts
LA.endMatch(); LB.endMatch(); await sleep(500); LA.leave(); LB.leave(); await sleep(800);
for (const n of [A, B, G]) {
const t = await n.token();
await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:delete?key=${CFG.apiKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ idToken: t }) });
}
console.log(fails ? `${fails} failure(s)` : 'all ok');
process.exit(fails ? 1 : 0);
})();