Self-Hosting & Operations
Production Docker and Dokploy deployment, WORKER_MODE topologies, public hosting behind Cloudflare/Traefik, user-brought OpenRouter OAuth credits, prompt caching, environment reference, security boundaries, and backup/restore operations.
Cockpit Chess ships production Docker images, a Compose generator for Dokploy or plain Docker Compose, zero-downtime migration admission, optional user-brought OpenRouter billing, and verified pg_dump backup/restore tooling.
Production Deployment (Docker & Dokploy)
Two production Dockerfiles build from the repository root (both run as non-root USER node on Node 26.13.1 with PostgreSQL 18 clients):
Dockerfile— Hono API, SSR, static web app, and embedded BullMQ consumers by default (WORKER_MODE=embedded).Dockerfile.worker— dedicated BullMQ worker with a private health endpoint (WORKER_MODE=externalon the server).
| Topology | Server WORKER_MODE |
Background Jobs | Migration Admission |
|---|---|---|---|
app (default) |
embedded |
Inside server container |
Server applies migrations before HTTP startup |
app-worker (recommended for public hosting) |
external |
Dedicated worker container |
Server applies (MIGRATE_ON_START=true); worker (MIGRATE_ON_START=false) waits up to 300 s and registers |
Both topologies require PostgreSQL 18 and Valkey 9 configured with noeviction. Preserve the images’ 510-second startup allowance so admission waits (up to 300 s) plus pre-migration backup and SQL application can complete cleanly.
Generating Compose & Building Images
Generate a Dokploy-ready Compose file (docker-compose.dokploy.yml, gitignored) and a reviewable settings checklist:
# Development (follows main)
pnpm dokploy:config --environment development --git-ref main \
--url https://dev.chess.example.com
# Production (pinned immutable release/<full-commit-sha> tag + dedicated worker + backups)
pnpm dokploy:config --environment production --git-ref release/<full-commit-sha> \
--topology app-worker --backups true --url https://chess.example.com
For manual Docker builds or external orchestrators, pass the full lowercase Git SHA as BUILD_VERSION (baked into BUILD_COMMIT and reported on /ready):
docker build --build-arg BUILD_VERSION="$(git rev-parse HEAD)" -t cockpit-chess-server -f Dockerfile .
docker build --build-arg BUILD_VERSION="$(git rev-parse HEAD)" -t cockpit-chess-worker -f Dockerfile.worker .
To run a deploy-gated one-shot migration before rolling out app replicas and workers with MIGRATE_ON_START=false:
docker compose run --rm server migrate
Verify any live rollout from outside the server (requires two consecutive /ready responses matching the exact commit SHA, database, cache, and consumer readiness):
pnpm deploy:check https://chess.example.com --commit <full-commit-sha>
# Optional deeper check on the VPS (verifies container image commits & single replica invariants)
pnpm dokploy:verify --mode compose --project <compose-project> \
--topology app-worker --url https://chess.example.com --commit <full-commit-sha>
First Admin Bootstrap
Two paths create the initial administrator (sign-up is disabled by default and admins must enroll in 2FA):
- With
SETUP_KEY(no SMTP needed yet): Generate a 32–512 character key (pnpm generate:secret), setSETUP_KEYon the server, deploy, and runpnpm deploy:generate-adminfrom a checkout (prompts for URL, key, and email; prints a one-time 1-hour set-password link). Sign in, enroll 2FA, then immediately removeSETUP_KEYand redeploy (the/api/setup/adminroute disappears once unset, and is permanently refused once any admin exists). - With
ADMIN_EMAILS(SMTP configured): SetADMIN_EMAILS=you@example.com, sign up with that exact address, and click the verification link. Afterwards, admins invite users from Admin → Users.
Worker Sizing & AGPL-3.0 Source Link
- Each worker process runs up to
CHESS_RUN_CONCURRENCYmatches concurrently (default512, typical 1–3 MB RAM/match; worst case ~15 MB/match) sharing a single pool ofCHESS_ENGINE_POOL_SIZEsingle-threaded Stockfish processes (default0= half CPU cores, clamped2–16; player evaluations preempt spectator evaluations). - Raise
DATABASE_POOL_MAX(default10, minimum3) to20–30on high-concurrency workers within Postgres connection limits. - AGPL-3.0 Section 13: Every page links to “Source code”. By default this points to
FlyCockpit/chessat the running commit. If you host a modified copy, setSOURCE_CODE_URL(optionally with{commit}, e.g.,https://github.com/you/chess/tree/{commit}).
Public Hosting & Reverse Proxies
Anonymous rate limits (sign-in, OTP, CLI, anonymous RPC) derive the client IP strictly from TRUST_PROXY_HOPS—selecting exactly N entries from the right of [...X-Forwarded-For, socketPeer] and ignoring CF-Connecting-IP, X-Real-IP, and Forwarded.
| Topology | TRUST_PROXY_HOPS |
Notes |
|---|---|---|
| Direct port access (LAN / local dev) | 0 (default) |
Uses TCP socket peer; logs a warning if a private peer sends X-Forwarded-For |
| Client → Traefik → Server (generated Compose) | 1 |
Set by pnpm dokploy:config |
Client → Cloudflare edge → cloudflared → Server |
1 |
Outbound-only Cloudflare Tunnel; no open inbound ports required |
| Client → Cloudflare → trusted Traefik → Server | 2 |
Only after Traefik’s forwardedHeaders.trustedIPs is restricted to Cloudflare’s IP ranges |
[!WARNING] Whenever
TRUST_PROXY_HOPS > 0, the app container must not publish a host port or be reachable bypassing the trusted proxy—otherwise direct callers can forgeX-Forwarded-Forentries and evade rate limits.
For a public VPS behind the Cloudflare HTTP proxy:
- Enforce Full (strict) TLS, firewall inbound HTTPS exclusively to Cloudflare’s published IPv4/IPv6 ranges (auditing Docker port publishing alongside
ufw), require zone-specific custom-CA Authenticated Origin Pulls (RequireAndVerifyClientCert—never trust Cloudflare’s global AOP CA alone), and enforce strict SNI + exactHost(...)routing. - Send transactional mail through an external authenticated SMTP relay on
SMTP_PORT=465(implicit TLS; Nodemailer does not enforcerequireTLSon port 587) and inspect delivered message headers (Received,X-Originating-IP,Message-ID) to confirm the relay strips your origin VPS IP. - Alternatively, run an outbound-only Cloudflare Tunnel (
cloudflared→http://server:3000on the private Compose network, withTRUST_PROXY_HOPS=1and tunnel credentials stored outside the repo in/etc/cloudflared).
User-Brought OpenRouter Credits (CHESS_USER_MATCHES_ENABLED)
By default only admins run hosted matches on the operator’s OPENROUTER_API_KEY. To allow any verified user to connect their own OpenRouter account via OAuth PKCE (S256) and run matches billed strictly to their own credits, set on both server and worker:
CHESS_HOSTED_ENABLED=true
CHESS_USER_MATCHES_ENABLED=true
CHESS_PROVIDER_KEY_SECRET=<64-hex-chars-from-openssl-rand-hex-32>
- Callback URL:
<BETTER_AUTH_URL>/api/openrouter/callback(HTTPS required in production; no OpenRouter app registration needed). - Strict billing isolation: User matches load only that owner’s sealed key when claimed by the worker and never fall back to
OPENROUTER_API_KEY. Each side’s create-form budget caps at half of the key’s remaining OpenRouter balance, bounded byCHESS_MAX_COST_USDandCHESS_MAX_TOKENS. - Quotas & visibility: 1 active (queued or running) own-key match per user,
CHESS_USER_DAILY_MATCHES(default20) per rolling 24 hours,CHESS_QUEUE_MAX(default200) deployment-wide queue cap, and 12 creates/hour. User matches start private and never appear on the leaderboard unless published and marked official by an admin. - Immediate Disconnect & key-use leases: Every active run and status check holds a short Valkey lease refreshed continuously and checked synchronously before every provider request. Disconnecting in Settings records revocation, deletes the sealed key, cancels queued matches, broadcasts revocation (
cockpit-chess:openrouter-key-revoked) to abort running matches immediately, and confirms stop once all leases clear (users should also revoke the key on OpenRouter). - Encryption & rotation: Connected keys are sealed with AES-256-GCM using
CHESS_PROVIDER_KEY_SECRETwith the user ID bound as AAD. For routine rotation, move the old value toCHESS_PROVIDER_KEY_SECRET_PREVIOUS, set the newCHESS_PROVIDER_KEY_SECRETon server and worker simultaneously, let active users re-seal automatically on next match start, then remove_PREVIOUS. On suspected compromise, replaceCHESS_PROVIDER_KEY_SECRETwithout_PREVIOUSso no stored key can open, and instruct users to revoke their keys on OpenRouter.
Prompt Caching
The match runner keeps a static, versioned system prefix (matchSystemPrompt, immutable rules, and static tool schemas—clearing the 1,024-token cache threshold with zero turn numbers, timestamps, clocks, or budgets interpolated). All dynamic per-turn state goes in the user message. Both fresh and persistent context modes benefit, using a deterministic per-side cache/session key chess-<match id>-<side>.
| Protocol / Adapter | Cache Breakpoint Behavior | Routing / Affinity Hint |
|---|---|---|
| Anthropic Messages | System, final tool, and latest eligible user breakpoints | x-session-id (on OpenRouter) |
| OpenAI Chat Completions & Responses | Automatic prefix caching | prompt_cache_key (+ x-session-id on OpenRouter) |
| OpenRouter adapter | Anthropic system/tool breakpoints; Gemini fixed system breakpoint; implicit for others | SDK sessionId → session_id |
| Gemini via OpenRouter Chat Completions | Explicit fixed system-content breakpoint (keeps dynamic user suffix outside) | Same per-side session key |
Archives record cachedInputTokens and cacheCreationInputTokens (Anthropic’s raw input_tokens is normalized once so totals include reads and writes). Budget reservations always use conservative full quoted rates rather than assuming cache discounts.
Environment Variable Reference
Variables are validated at startup via packages/env (t3-env + Zod). Use pnpm generate:secrets to build a validated production env block.
Core, Datastores & Runtime ([shared] unless noted)
| Variable | Scope | Default | Purpose |
|---|---|---|---|
DATABASE_URL |
Shared (Required) | — | PostgreSQL 18 connection string |
REDIS_URL |
Shared (Required) | — | Valkey 9 / Redis connection string (queues, rate limits, leases) |
DATABASE_POOL_MAX |
Shared | 10 |
Per-process Postgres pool size (minimum 3 for auth lock slots) |
NODE_ENV |
Shared | development |
production enables strict boot guards (HTTPS origin, strong secrets, SMTP for signup) |
MIGRATE_ON_START |
Entrypoint shell | true (server) / false (worker) |
Apply migrations at startup (false everywhere when using a separate migrate job) |
WORKER_MODE |
Server only | embedded |
embedded or external (never silently falls back; /ready fails if external consumers vanish) |
BUILD_VERSION |
Docker build arg | — | Full Git SHA baked into BUILD_COMMIT and reported by /ready |
Auth, Admin, Proxy & SSO ([server-only])
| Variable | Default | Purpose |
|---|---|---|
BETTER_AUTH_SECRET |
Required | ≥ 32-char secret signing sessions and deriving the AES-256-GCM password pepper (back up separately!) |
BETTER_AUTH_SECRET_PREVIOUS |
— | Old auth secret during coordinated password-pepper rotation |
BETTER_AUTH_URL |
Required | Exact public HTTPS origin (https://chess.example.com; no path/query) |
CORS_ORIGIN |
— | Set only for intentional cross-origin web/API deployments |
TRUST_PROXY_HOPS |
0 |
Exact count of trusted reverse proxies (1 behind Traefik or cloudflared; 2 behind Cloudflare → trusted Traefik) |
ADMIN_EMAILS |
— | Comma-separated bootstrap admin allowlist (requires SMTP) |
SETUP_KEY |
— | Temporary 32–512 char key for pnpm deploy:generate-admin (remove after first admin signs in) |
SIGNUP_ENABLED |
false |
Public registration switch (requires SMTP in production) |
SSO_ENABLED, SSO_CLIENT_ID, SSO_CLIENT_SECRET, SSO_ISSUER, SSO_PROVIDER_NAME, FORCE_SSO |
false / — |
Enterprise OIDC/SSO login (FORCE_SSO=true disables password login) |
Hosted Chess & User OpenRouter ([shared])
| Variable | Default | Purpose |
|---|---|---|
CHESS_HOSTED_ENABLED |
false |
Master switch for hosted match inference |
OPENROUTER_API_KEY |
— | Operator OpenRouter key for admin hosted matches (and optional i18n translation) |
CHESS_USER_MATCHES_ENABLED |
false |
Allow verified users to connect their own OpenRouter account via OAuth PKCE |
CHESS_PROVIDER_KEY_SECRET |
— | 64-hex AES-256-GCM sealing key for user OpenRouter keys (same on server & worker) |
CHESS_PROVIDER_KEY_SECRET_PREVIOUS |
— | Previous sealing key during rotation |
CHESS_MAX_COST_USD / CHESS_MAX_TOKENS |
25 / 10000000 |
Per-side hard caps for hosted matches (0.01–1000 USD; 256–100M tokens) |
CHESS_RUN_CONCURRENCY |
512 |
Concurrent hosted matches per worker process (1–4096) |
CHESS_QUEUE_MAX |
200 |
Deployment-wide queued match cap |
CHESS_USER_DAILY_MATCHES |
20 |
Rolling 24-hour own-key match limit per user |
CHESS_ENGINE_POOL_SIZE |
0 (auto) |
Shared Stockfish subprocesses per worker (0 = half cores, 2–16) |
CHESS_CONVERSATION_MAX_BYTES |
2097152 (2 MiB) |
Max in-memory persistent conversation size per side (64 KiB–64 MiB) |
SOURCE_CODE_URL |
Upstream repo | AGPL-3.0 Section 13 source link (supports {commit} placeholder) |
Email, Rate Limits, Backups, CLI & Build-Time Web
| Group | Variables & Defaults |
|---|---|
Email ([shared]) |
SMTP_HOST, SMTP_PORT (465 implicit TLS recommended for public relays; 587 STARTTLS; 1025 local mailpit), SMTP_USER, SMTP_PASS, SMTP_FROM |
Backups ([shared]) |
BACKUP_ENABLED (false), BACKUP_SCHEDULE (off | daily), BACKUP_HOUR_UTC (3), BACKUP_KEEP (14), BACKUP_MAX_AGE_HOURS (36), BACKUP_S3_BUCKET, BACKUP_S3_ACCESS_KEY_ID, BACKUP_S3_SECRET_ACCESS_KEY, BACKUP_S3_REGION, BACKUP_S3_ENDPOINT, BACKUP_S3_PREFIX, BACKUP_MONITOR_S3_ACCESS_KEY_ID, BACKUP_MONITOR_S3_SECRET_ACCESS_KEY |
Rate limits & SSR ([server-only]) |
RATE_LIMIT_AUTH_POINTS (30) / WINDOW_SECONDS (60), RATE_LIMIT_RPC_POINTS (100) / WINDOW_SECONDS (60), RATE_LIMIT_EMAIL_POINTS (3) / WINDOW_SECONDS (3600), SSR_CACHE_TTL_SECONDS (60) |
CLI distribution ([server-only]) |
CLI_RELEASE_REPO, CLI_RELEASE_GITHUB_TOKEN, CLI_RELEASE_TAG |
Web build-time (apps/web/.env) |
VITE_APP_NAME (Cockpit Chess), VITE_SERVER_URL (leave unset for same-origin), VITE_DEV_PORT, VITE_DEV_SERVER_URL |
Security Boundaries
- Untrusted model text. Remarks and rejected reply tails are never rendered as HTML or Markdown; system prompts explicitly instruct models not to follow instructions inside opponent remarks.
- Full archive replay verification. Studio imports and CLI uploads never trust saved board snapshots—the server replays every move through
chess.jsfrom the starting position and enforces the 2 MB archive limit. - Spend & ownership fences. Before every model dispatch (including transport retries), the runner reserves worst-case cost/tokens (unused reservations are not refunded) and checks both a database ownership heartbeat fence (aborts after 3 failed heartbeats or 8 s stale confirmation) and any user own-key Valkey lease.
- Auth & session hardening.
- Scrypt password hashes are sealed with AES-256-GCM under a key derived from
BETTER_AUTH_SECRET(pw1:<fingerprint>:<ciphertext>), preventing offline cracking from a database dump alone. - Anonymous auth endpoints return byte-identical responses to avoid account-existence oracles; cookie cache is disabled globally; password resets serialize under per-user advisory locks and revoke all sessions, API keys, device codes, and pending 2FA challenges.
- Browser tabs send
X-Expected-Userand synchronously quarantine/reload documents (409 IDENTITY_CHANGED) if the session identity changes in another tab. - Administrators must enroll in 2FA; API keys are permanently blocked from admin endpoints; CI enforces every endpoint against
docs/access-matrix.md.
- Scrypt password hashes are sealed with AES-256-GCM under a key derived from
Backup & Restore Operations
Backups are opt-in (BACKUP_ENABLED=false, BACKUP_SCHEDULE=off by default). Always back up BETTER_AUTH_SECRET separately from the database so restored password hashes remain readable.
Enabling Automated Backups & Freshness Monitoring
- Regenerate Compose with
--backups true(mounts/backupsand adds the optionalbackupservice). - Enable the
backupCompose profile and setBACKUP_SCHEDULE=daily(keep exactly one daily scheduler per database). - Configure an off-site versioned S3/R2 bucket with a unique
BACKUP_S3_PREFIXper deployment (e.g.,cockpit-chess/production/chess.example.com/database). Use two separate IAM identities:- Writer (
BACKUP_S3_*):GetObject,GetObjectVersion,PutObject,AbortMultipartUpload(no delete permission; bucket lifecycle rules handle expiration). The container entrypoint drops writer keys from the environment beforeexecing the long-running server/worker process. - Monitor (
BACKUP_MONITOR_S3_*): ListBucket only on<prefix>/for the worker’s 6-hour freshness check (BACKUP_MAX_AGE_HOURS, default36).
- Writer (
- Set
BACKUP_ENABLED=trueto require verified pre-migration (keeps 5 locally) and pre-drop (contract.sql, keeps 5 locally)pg_dumpsnapshots—if a destination is missing or a dump fails, migrations halt safely before changing the database.
[!IMPORTANT] The
PG_MAJORrule:pg_dumpcannot dump a newer PostgreSQL major version. Whenever you upgrade Postgres’s major version, bumpARG PG_MAJORin bothDockerfileandDockerfile.workerand rebuild (pnpm docker:check-copyenforces parity).
Restore & Quarterly Restore Drills
Production restores run inside the target network by the operator—always preview first without --confirm, and run quarterly drills against a throwaway restore_drill database:
# Extract the Dokploy host helper once from the running server container
docker exec "$(docker ps -q -f label=com.docker.compose.service=server | head -n1)" \
cat /app/scripts/backup/host.sh > app-db.sh
bash app-db.sh list # list /backups newest first
bash app-db.sh backup # immediate verified manual dump
bash app-db.sh drill # restore into throwaway restore_drill DB & verify every table
bash app-db.sh drill s3://<bucket>/<key> --etag <etag> # drill pinned off-site S3 object
bash app-db.sh restore daily-20261110T030000Z.dump # guided stop -> preview -> confirm -> restore -> start
Direct image commands (restore, restore-drill, backup, hold-deletions) follow strict transactional safety:
- Replacing a non-empty database requires
--replace, exact--confirm RESTORE:<database>, and takes a pre-restore snapshot unless--skip-snapshotis explicitly passed alongside a provider snapshot. S3 restores require--etag(and optional--version-id). - Definite vs. uncertain exits:
0= restored;3= refused/cancelled before any mutation;4= transaction started, failed, and provably rolled back;1(or signals129/130/143afterCOMMITwas sent) = uncertain (leave writers stopped and inspect the database). - 7-day deletion hold: Every
restorecommits a 7-day hold on scheduledcontract.sqlcolumn/table deletions atomically. If you restore from an untracked volume snapshot orpg_restore --data-only, start only Postgres and runbash app-db.sh hold-deletions(or the image’shold-deletionscommand) before starting the app.