build(deploy): release-based deploy with health check and rollback, node 24, service user (P3-1b, P3-2, P3-3)

This commit is contained in:
Benjamin Oezcan
2026-11-19 02:12:53 +01:00
parent b587d12f37
commit 101dd7c44b
6 changed files with 181 additions and 137 deletions

View File

@@ -1,53 +1,56 @@
# Robot Clash – Deploy auf den Hetzner-Server
# Robot Clash – Deploy auf den Hetzner-Server (Dev/Test-System)
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.
Spiel + API laufen auf **einem** Server unter `https://roboclash.michael-media.de/` (Caddy macht TLS automatisch und
leitet an den Node-Dienst weiter, WebSocket `/ws` inklusive). Alle Befehle aus dem Repo-Root in **Git Bash**
(Windows) oder einer Linux-Shell; SSH-Zugang `root@roboclash.michael-media.de` per Schlüssel.
## 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.
## Aufbau auf dem Server
## 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
/opt/robotclash/
releases/<zeit>-<commit>/ je Deploy ein vollständiges Release (game/, server/, admin/), die letzten 5 bleiben
current -> releases/... aktives Release (Symlink)
shared/.env PORT, JWT_SECRET, DB_FILE (bleibt über Deploys erhalten, nur root/Dienst lesbar)
shared/data.sqlite Datenbank
backups/ pre-<release>.sqlite vor jedem Deploy, daily-<datum>.sqlite (cron, 14 Tage)
```
## 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.
Dienst `robotclash` (systemd) läuft als eigener Nutzer `robotclash`, darf nur nach `shared/` schreiben.
## 1) Server einrichten (einmal; erneut ausführen schadet nicht)
```bash
scp server/deploy/setup.sh root@roboclash.michael-media.de:/root/
ssh root@roboclash.michael-media.de "bash /root/setup.sh roboclash.michael-media.de"
```
Installiert Node 24 + Caddy, legt Nutzer, Ordner, Dienst, Firewall und Backup an. Ein altes Layout
(`/opt/robotclash/server`, `/game`) wird nach `/opt/robotclash/legacy-<datum>/` verschoben, `JWT_SECRET` übernommen.
## 2) Deployen
```bash
bash server/deploy/deploy.sh # aktuellen Commit (HEAD) ausrollen
bash server/deploy/deploy.sh --reset-db # ... und DB frisch aufsetzen (Testkonten michi / benni)
bash server/deploy/deploy.sh --ref <commit> # einen bestimmten Stand (z. B. zurück auf einen alten)
```
Es wird **nur Committetes** ausgerollt (`git archive`). Ablauf: hochladen → `npm ci` → DB-Backup → Dienst stoppen →
(optional Reset) → `current` umschalten → starten → `/healthz` muss den neuen Commit melden, sonst **automatisch
zurück** auf das vorige Release.
## Testkonten (nur Test-System, siehe CLAUDE.md)
`michi` / `Michi2000!` und `benni` / `Benni2000!` – beide Admin (Dev-Münzen, `/admin/`). Kommen per `--reset-db`.
## Logs / Status
```
systemctl status robotclash
journalctl -u robotclash -f
```bash
ssh root@roboclash.michael-media.de "systemctl status robotclash; journalctl -u robotclash -n 50"
curl -s https://roboclash.michael-media.de/healthz
```
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.
## Später (Plan)
Eigener SSH-Nutzer `deploy` statt root (P3-1), Deploy aus Gitea Actions bei Push auf `main` (P3-6), Produktion als
zweite Umgebung erst nach T-4.

View File

@@ -1,31 +0,0 @@
# 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

31
server/deploy/deploy.sh Normal file
View File

@@ -0,0 +1,31 @@
#!/usr/bin/env bash
# Deploy a committed git ref to the server. Run from the repo root (Git Bash on Windows, or Linux/CI):
# bash server/deploy/deploy.sh deploy HEAD
# bash server/deploy/deploy.sh --reset-db ... and reset the DB (test system: seed accounts michi/benni)
# bash server/deploy/deploy.sh --ref <sha|tag> --host root@<server>
# Only committed code is deployed (git archive), never the working tree. The server side (remote-release.sh)
# installs the release, backs up the DB, switches the `current` link, checks /healthz and rolls back on failure.
set -euo pipefail
HOST="root@roboclash.michael-media.de"
REF="HEAD"
RESET=0
while [ $# -gt 0 ]; do
case "$1" in
--host) HOST="$2"; shift 2 ;;
--ref) REF="$2"; shift 2 ;;
--reset-db) RESET=1; shift ;;
*) echo "unknown option: $1"; exit 2 ;;
esac
done
cd "$(git rev-parse --show-toplevel)"
git diff --quiet HEAD -- game server admin || echo "!! uncommitted changes in game/server/admin are NOT deployed (only $REF)"
SHA=$(git rev-parse --short "$REF")
REL="$(date -u +%Y%m%d-%H%M%S)-$SHA"
TAR="$(mktemp -t rc-XXXXXX).tgz"
trap 'rm -f "$TAR"' EXIT
echo ">> release $REL -> $HOST"
git archive --format=tar.gz -o "$TAR" "$REF" game server admin
scp -q "$TAR" "$HOST:/tmp/rc-$REL.tgz"
tr -d '\r' < server/deploy/remote-release.sh | ssh "$HOST" bash -s -- "$REL" "$SHA" "$RESET"

View File

@@ -1,29 +0,0 @@
# 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/"

View File

@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Runs ON the server (piped in by deploy.sh): install release $1 (commit $2), optional DB reset ($3 = 1).
set -euo pipefail
REL="$1"; SHA="$2"; RESET="${3:-0}"
APP=/opt/robotclash
SVC=robotclash
D="$APP/releases/$REL"
PORT=$(grep -E '^PORT=' "$APP/shared/.env" | cut -d= -f2); PORT=${PORT:-8080}
mkdir -p "$D"
tar -xzf "/tmp/rc-$REL.tgz" -C "$D"
rm -f "/tmp/rc-$REL.tgz"
echo "GIT_COMMIT=$SHA" > "$D/server/.release"
echo ">> npm ci"
(cd "$D/server" && npm ci --omit=dev --no-audit --no-fund --loglevel=error)
chown -R "$SVC:$SVC" "$D"
PREV=$(readlink -f "$APP/current" 2>/dev/null || true)
if [ -f "$APP/shared/data.sqlite" ]; then
sqlite3 "$APP/shared/data.sqlite" ".backup '$APP/backups/pre-$REL.sqlite'"
echo ">> db backup: backups/pre-$REL.sqlite"
fi
systemctl stop "$SVC" || true
if [ "$RESET" = "1" ]; then
echo ">> db reset (seed accounts)"
sudo -u "$SVC" bash -c "set -a; . '$APP/shared/.env'; set +a; cd '$D/server' && node scripts/reset-db.js"
fi
ln -sfn "$D" "$APP/current"
systemctl start "$SVC"
ok=0
for i in $(seq 1 20); do
if curl -fsS "http://127.0.0.1:$PORT/healthz" 2>/dev/null | grep -q "\"commit\":\"$SHA\""; then ok=1; break; fi
sleep 0.5
done
if [ "$ok" != "1" ]; then
echo "!! health check failed for $REL"
journalctl -u "$SVC" -n 20 --no-pager || true
if [ -n "$PREV" ] && [ -d "$PREV" ]; then
echo "!! rolling back to $(basename "$PREV")"
ln -sfn "$PREV" "$APP/current"; systemctl restart "$SVC"
fi
exit 1
fi
echo ">> live: $(curl -fsS "http://127.0.0.1:$PORT/healthz")"
# keep the last 5 releases
ls -1dt "$APP"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf

View File

@@ -1,69 +1,90 @@
#!/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
# One-time (and re-runnable) server setup for Robot Clash. Run ON the server as root:
# bash setup.sh [domain] default: roboclash.michael-media.de
# Installs Node 24 + Caddy (auto-TLS), creates the service user, the release layout, the hardened systemd
# service, the firewall and a daily DB backup. Migrates the old /opt/robotclash/{game,server} layout.
# Afterwards deploy from your machine: bash server/deploy/deploy.sh --reset-db
set -euo pipefail
DOMAIN="${1:-roboclash.michael-media.de}"
APP=/opt/robotclash
SVC=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 -
# --- Node 24 LTS (Node 20 is end-of-life since 2026-04-30) ----------------------------------------
if ! node -v 2>/dev/null | grep -q '^v24\.'; then
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
apt-get install -y nodejs
fi
apt-get install -y build-essential python3 git ufw sqlite3 curl
apt-get install -y build-essential python3 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
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https gpg
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"
# --- service user + layout: releases/<time>-<commit>, current -> active release, shared/ (.env + DB) --
id "$SVC" >/dev/null 2>&1 || useradd --system --home-dir "$APP" --shell /usr/sbin/nologin "$SVC"
mkdir -p "$APP/releases" "$APP/shared" "$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)"
# old layout (code + .env + DB directly in /opt/robotclash/server): keep the secret, park the rest
if [ -f "$APP/server/.env" ] && [ ! -f "$APP/shared/.env" ]; then cp "$APP/server/.env" "$APP/shared/.env"; fi
if [ -d "$APP/server" ] || [ -d "$APP/game" ]; then
systemctl stop "$SVC" 2>/dev/null || true
LEG="$APP/legacy-$(date +%F-%H%M)"; mkdir -p "$LEG"
[ -d "$APP/server" ] && mv "$APP/server" "$LEG/"
[ -d "$APP/game" ] && mv "$APP/game" "$LEG/"
echo ">> old layout moved to $LEG (delete it once the new setup runs)"
fi
# --- systemd service ------------------------------------------------------------------------------
cat > /etc/systemd/system/robotclash.service <<EOF
if [ ! -f "$APP/shared/.env" ]; then
printf 'PORT=8080\nJWT_SECRET=%s\n' "$(head -c 32 /dev/urandom | base64 | tr -d '\n')" > "$APP/shared/.env"
echo ">> wrote $APP/shared/.env (random JWT_SECRET)"
fi
# keys the new server no longer uses; DB lives in shared/
sed -i '/^DB_FILE=/d;/^ADMIN_UID=/d;/^ANTICHEAT=/d' "$APP/shared/.env"
echo "DB_FILE=$APP/shared/data.sqlite" >> "$APP/shared/.env"
grep -q '^PORT=' "$APP/shared/.env" || echo 'PORT=8080' >> "$APP/shared/.env"
chown -R "$SVC:$SVC" "$APP/shared" "$APP/backups"
chmod 700 "$APP/shared"; chmod 600 "$APP/shared/.env"
# --- systemd service (no root, read-only system, writes only to shared/) --------------------------
cat > "/etc/systemd/system/$SVC.service" <<EOF
[Unit]
Description=Robot Clash server
After=network.target
[Service]
WorkingDirectory=$APP/server
EnvironmentFile=$APP/server/.env
User=$SVC
Group=$SVC
WorkingDirectory=$APP/current/server
EnvironmentFile=$APP/shared/.env
EnvironmentFile=-$APP/current/server/.release
Environment=NODE_ENV=development
ExecStart=/usr/bin/node app.js
Restart=always
RestartSec=2
User=root
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=$APP/shared
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable robotclash
systemctl enable "$SVC" >/dev/null
# --- Caddy site -----------------------------------------------------------------------------------
# --- Caddy site: TLS + proxy; WebSocket /ws is proxied as-is (no compression on the socket) --------
cat > /etc/caddy/Caddyfile <<EOF
$DOMAIN {
encode gzip
@compress not path /ws
encode @compress gzip
reverse_proxy localhost:8080
}
EOF
@@ -77,11 +98,11 @@ ufw --force enable >/dev/null
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
[ -f $APP/shared/data.sqlite ] && sqlite3 $APP/shared/data.sqlite ".backup '\$D/daily-\$(date +%F).sqlite'"
ls -1t "\$D"/daily-*.sqlite 2>/dev/null | tail -n +15 | xargs -r rm
ls -1t "\$D"/pre-*.sqlite 2>/dev/null | tail -n +11 | 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"
echo ">> Setup done. node $(node -v), caddy $(caddy version | cut -d' ' -f1)"
echo ">> Next (from your machine): bash server/deploy/deploy.sh --reset-db"