big update

This commit is contained in:
2026-11-18 15:18:38 +01:00
parent e0496fa089
commit 64c5b65543
39 changed files with 1938 additions and 367 deletions

6
server/.env.example Normal file
View File

@@ -0,0 +1,6 @@
# Copy to server/.env and fill in. 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.
ADMIN_UID=
DB_FILE=./data.sqlite

32
server/README.md Normal file
View File

@@ -0,0 +1,32 @@
# Robot Clash – Server
Node-Backend: Konten, Spielstände, Rangliste, Lobby, Live-PvP und **server-autoritäres Geld**. Spiegelt die
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)
```
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
```
`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).
## API (Kurzüberblick)
- `POST /api/auth/register|login|guest|refresh|logout` → `{ idToken, refreshToken, uid, name, email }`
- `GET /api/wallet` (mit `?auth=<idToken>`) → `{ money, fame }` (nur lesen)
- `GET|PUT|PATCH|POST|DELETE /db/<pfad>.json?auth=<idToken>` – RTDB-kompatibel; `GET` mit
`Accept: text/event-stream` liefert Live-Updates (SSE). Schreibzugriff per `rules.js`.
- **Saves:** beim Schreiben von `saves/<uid>` entfernt der Server `money`/`fame` (die kommen nur aus dem Wallet).
## Nächste Schritte (noch offen, Plan 13)
- Client (`game/net.js`, `game.js`) auf diesen Server umstellen (Basis-URL, Auth-Mapping).
- Anti-Cheat: `/api/shop/buy|sell` + `/api/fight/claim` (Server re-simuliert Seed-Kämpfe), Geld nur so änderbar.
- Deploy: **per Skript/PowerShell** (Ansible verschoben) – Caddy (TLS) + systemd + ufw auf den Hetzner-Server,
DNS `play.michael-media.de` → Server.

78
server/app.js Normal file
View File

@@ -0,0 +1,78 @@
/* 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). */
'use strict';
const express = require('express');
const path = require('path');
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 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)
function run(res, fn) { try { res.json(fn()); } catch (e) { res.status(e.status || 500).json({ error: e.code || 'ERROR' }); } }
// --- 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 }); });
// --- 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)) }));
// --- 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)); });
// --- 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/<path>.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) ------------------------------------------
app.use(express.static(path.join(__dirname, '..', 'game')));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log('Robot Clash server on :' + PORT));

63
server/auth.js Normal file
View File

@@ -0,0 +1,63 @@
/* 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. */
'use strict';
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { Users, Wallet, Tokens } = require('./db');
const SECRET = process.env.JWT_SECRET || 'dev-insecure-change-me';
const ACCESS_TTL = 3600; // seconds
const REFRESH_TTL = 30 * 864e5; // 30 days (ms)
const START_MONEY = 800;
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; }
function issue(u) {
const idToken = jwt.sign({ uid: u.uid, name: u.name, guest: !!u.guest }, SECRET, { expiresIn: ACCESS_TTL });
const refreshToken = newRefresh();
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 };
}
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 login(email, pass) {
email = String(email || '').trim().toLowerCase();
const u = Users.byEmail.get(email);
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 refresh(refreshToken) {
const row = Tokens.get.get(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
return issue(u);
}
function logout(refreshToken) { if (refreshToken) Tokens.del.run(refreshToken); }
// express middleware: reads ?auth=<idToken> 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; }
next();
}
module.exports = { register, login, guest, refresh, logout, auth, cleanName };

97
server/db.js Normal file
View File

@@ -0,0 +1,97 @@
/* 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 ---------------------------------------------------------
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 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 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
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 };

53
server/deploy/README.md Normal file
View File

@@ -0,0 +1,53 @@
# Robot Clash – Deploy auf den Hetzner-Server
Spiel + API laufen auf **einem** Server unter `https://roboclash.michael-media.de/` (Caddy macht TLS automatisch,
reverse-proxyt auf den Node-Dienst). Kein Ansible nötig – ein Setup-Skript + ein PowerShell-Push.
## 0) DNS (einmal)
Beim DNS-Anbieter von `michael-media.de` einen **A-Record** anlegen:
`roboclash` → `91.99.166.238` (die Server-IP). Kurz warten, bis er aktiv ist.
## 1) Server einrichten (einmal, von Windows PowerShell)
```powershell
scp server\deploy\setup.sh root@91.99.166.238:/root/
ssh root@91.99.166.238 "bash /root/setup.sh roboclash.michael-media.de"
```
Das installiert Node + Caddy, legt den systemd-Dienst, die Firewall (ufw) und ein tägliches DB-Backup an und
schreibt `/opt/robotclash/server/.env` mit zufälligem `JWT_SECRET`.
## 2) Code hochladen + starten
```powershell
.\server\deploy\push.ps1
ssh root@91.99.166.238 "systemctl start robotclash"
```
Fertig → **https://roboclash.michael-media.de/** (TLS kommt beim ersten Aufruf automatisch; ein paar Sekunden).
## 3) Updates später
Einfach erneut:
```powershell
.\server\deploy\push.ps1
```
(lädt Spiel + Server neu hoch, `npm ci`, startet den Dienst neu). `.env` und die Datenbank bleiben erhalten.
## Admin werden (für die Live-Steuerung / `/db/live`)
Im Spiel registrieren, dann auf dem Server die uid holen und in die `.env` eintragen:
```
ssh root@91.99.166.238
sqlite3 /opt/robotclash/server/data.sqlite "select uid,email from users"
nano /opt/robotclash/server/.env # ADMIN_UID=<deine uid>
systemctl restart robotclash
```
## Anti-Cheat scharf schalten (nach Schritt 3 der Umsetzung)
In `.env` `ANTICHEAT=1` setzen + `systemctl restart robotclash`. Dann entfernt der Server `money`/`fame` aus
`saves/` und Geld läuft nur noch über die Server-Endpunkte. **Vorher** muss der Client-Geldfluss umgestellt sein,
sonst steht das Geld auf 0.
## Logs / Status
```
systemctl status robotclash
journalctl -u robotclash -f
```
Schneller (optional, aus WSL statt PowerShell): `rsync -az --delete game server root@91.99.166.238:/opt/robotclash/`
statt `scp` – nur Änderungen, kein erneutes Hochladen der ~13 MB Assets.

View File

@@ -0,0 +1,31 @@
# Komplett-Deploy in einem: Server einrichten, Code hochladen, starten, Status prüfen.
# Aus dem Projektordner in Windows PowerShell: .\server\deploy\deploy-all.ps1
# Beim ersten Mal fragt SSH nach dem Hetzner-Root-Passwort (mehrfach) und einmal nach dem Fingerprint (yes).
param(
[string]$Server = "root@91.99.166.238",
[string]$Domain = "roboclash.michael-media.de",
[string]$App = "/opt/robotclash"
)
$ErrorActionPreference = "Stop"
$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
Write-Host "== 1/4 Server einrichten (Node, Caddy, Dienst, Firewall) ==" -ForegroundColor Cyan
scp "$repo\server\deploy\setup.sh" "${Server}:/root/setup.sh"
ssh $Server "bash /root/setup.sh $Domain"
Write-Host "== 2/4 Code hochladen (Spiel + Server) ==" -ForegroundColor Cyan
ssh $Server "mkdir -p $App/game $App/server"
scp -r -q "$repo\game" "${Server}:$App/"
Get-ChildItem "$repo\server" -File |
Where-Object { $_.Name -ne ".env" -and $_.Name -notlike "*.sqlite*" } |
ForEach-Object { scp -q $_.FullName "${Server}:$App/server/" }
Write-Host "== 3/4 Abhaengigkeiten installieren + Dienst starten ==" -ForegroundColor Cyan
ssh $Server "cd $App/server && (npm ci --omit=dev 2>/dev/null || npm install --omit=dev) && systemctl restart robotclash"
Write-Host "== 4/4 Status ==" -ForegroundColor Cyan
ssh $Server "sleep 1; systemctl --no-pager --lines=6 status robotclash; echo '--- lokal (Node) ---'; curl -s -o /dev/null -w 'node:8080 -> HTTP %{http_code}\n' http://localhost:8080/; echo -n '--- caddy: '; systemctl is-active caddy"
Write-Host ""
Write-Host "Fertig. Oeffne: https://$Domain/ (Browser: Strg+F5 oder Inkognito)" -ForegroundColor Green
Write-Host "Beim ersten Aufruf holt Caddy automatisch das TLS-Zertifikat (ein paar Sekunden)." -ForegroundColor Green

29
server/deploy/push.ps1 Normal file
View File

@@ -0,0 +1,29 @@
# Push the game + server to the Hetzner box and restart. Run from Windows PowerShell (needs OpenSSH: ssh/scp).
# .\server\deploy\push.ps1
# .\server\deploy\push.ps1 -Server root@91.99.166.238
param(
[string]$Server = "root@91.99.166.238",
[string]$App = "/opt/robotclash"
)
$ErrorActionPreference = "Stop"
$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
Write-Host "Deploy from $repo -> ${Server}:$App"
# make sure target dirs exist
ssh $Server "mkdir -p $App/game $App/server"
# game/ (no node_modules inside) - full tree incl. assets
Write-Host "Uploading game/ ..."
scp -r -q "$repo\game" "${Server}:$App/"
# server source only: skip .env, node_modules and the live DB
Write-Host "Uploading server/ source ..."
Get-ChildItem "$repo\server" -File |
Where-Object { $_.Name -ne ".env" -and $_.Name -notlike "*.sqlite*" } |
ForEach-Object { scp -q $_.FullName "${Server}:$App/server/" }
# install deps + restart
Write-Host "Installing deps + restarting ..."
ssh $Server "cd $App/server && (npm ci --omit=dev 2>/dev/null || npm install --omit=dev) && systemctl restart robotclash && sleep 1 && systemctl --no-pager --lines=5 status robotclash"
Write-Host "Done. https://roboclash.michael-media.de/"

87
server/deploy/setup.sh Normal file
View File

@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# One-time server setup for Robot Clash. Run ON the Hetzner box as root:
# bash setup.sh # uses roboclash.michael-media.de
# bash setup.sh my.domain.tld # custom domain
# Installs Node + Caddy (auto-TLS), creates the systemd service, firewall and a daily DB backup.
# Then push the code (deploy/push.ps1 from Windows) and: systemctl start robotclash
set -euo pipefail
DOMAIN="${1:-roboclash.michael-media.de}"
APP=/opt/robotclash
echo ">> Robot Clash setup for $DOMAIN"
# --- Node LTS -------------------------------------------------------------------------------------
if ! command -v node >/dev/null 2>&1; then
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
fi
apt-get install -y build-essential python3 git ufw sqlite3 curl
# --- Caddy (reverse proxy + automatic HTTPS) ------------------------------------------------------
if ! command -v caddy >/dev/null 2>&1; then
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list >/dev/null
apt-get update
apt-get install -y caddy
fi
mkdir -p "$APP/game" "$APP/server" "$APP/backups"
# --- .env (random JWT secret, kept across deploys) ------------------------------------------------
if [ ! -f "$APP/server/.env" ]; then
cat > "$APP/server/.env" <<EOF
PORT=8080
JWT_SECRET=$(head -c 32 /dev/urandom | base64 | tr -d '\n')
ADMIN_UID=
DB_FILE=$APP/server/data.sqlite
ANTICHEAT=0
EOF
echo ">> wrote $APP/server/.env (random JWT_SECRET)"
fi
# --- systemd service ------------------------------------------------------------------------------
cat > /etc/systemd/system/robotclash.service <<EOF
[Unit]
Description=Robot Clash server
After=network.target
[Service]
WorkingDirectory=$APP/server
EnvironmentFile=$APP/server/.env
ExecStart=/usr/bin/node app.js
Restart=always
RestartSec=2
User=root
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable robotclash
# --- Caddy site -----------------------------------------------------------------------------------
cat > /etc/caddy/Caddyfile <<EOF
$DOMAIN {
encode gzip
reverse_proxy localhost:8080
}
EOF
systemctl reload caddy 2>/dev/null || systemctl restart caddy
# --- firewall -------------------------------------------------------------------------------------
ufw allow 22 >/dev/null; ufw allow 80 >/dev/null; ufw allow 443 >/dev/null
ufw --force enable >/dev/null
# --- daily SQLite backup (keep 14) ----------------------------------------------------------------
cat > /etc/cron.daily/robotclash-backup <<EOF
#!/usr/bin/env bash
D=$APP/backups
sqlite3 $APP/server/data.sqlite ".backup '\$D/data-\$(date +%F).sqlite'" 2>/dev/null || cp $APP/server/data.sqlite "\$D/data-\$(date +%F).sqlite" 2>/dev/null || true
ls -1t "\$D"/data-*.sqlite 2>/dev/null | tail -n +15 | xargs -r rm
EOF
chmod +x /etc/cron.daily/robotclash-backup
echo ">> Setup done."
echo ">> DNS: point $DOMAIN A-record to this server's IP."
echo ">> Next: push the code (deploy/push.ps1 from Windows), then: systemctl start robotclash"

25
server/economy.js Normal file
View File

@@ -0,0 +1,25 @@
/* 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. */
'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 clampMoney = v => Math.max(0, Math.min(1e9, Math.round(+v || 0)));
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 addWallet(uid, dMoney, dFame) {
const w = wallet(uid);
return setWallet(uid, w.money + (+dMoney || 0), w.fame + (+dFame || 0));
}
module.exports = { RC, wallet, setWallet, addWallet, clampMoney };

17
server/package.json Normal file
View File

@@ -0,0 +1,17 @@
{
"name": "robotclash-server",
"version": "1.0.0",
"private": true,
"description": "Robot Clash backend - auth, saves, ranks, lobby, live PvP relay, server-authoritative economy.",
"main": "app.js",
"scripts": {
"start": "node app.js",
"test": "node test.js"
},
"dependencies": {
"express": "4.19.2",
"better-sqlite3": "11.3.0",
"bcryptjs": "2.4.3",
"jsonwebtoken": "9.0.2"
}
}

38
server/rtdb.js Normal file
View File

@@ -0,0 +1,38 @@
/* 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<res>
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 };

34
server/rules.js Normal file
View File

@@ -0,0 +1,34 @@
/* 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 };