From 5ce6a6811a1935d11ed0811496c3558f80214195 Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 17 Nov 2026 19:56:39 +0200 Subject: [PATCH] Add Gitea CI/CD stack, tloto-deploy, and tagged Compose images Co-authored-by: Cursor --- .gitea/workflows/ci.yml | 58 ++++ .gitea/workflows/deploy.yml | 48 +++ backend/src/db/schema.sql | 104 ++++-- deploy/edge/certs/.gitkeep | 0 deploy/edge/docker-compose.yml | 29 ++ deploy/edge/nginx.conf | 57 ++++ deploy/gitea-stack/.env.example | 22 ++ deploy/gitea-stack/.gitignore | 2 + deploy/gitea-stack/bootstrap-env.sh | 49 +++ deploy/gitea-stack/bootstrap-gitea-admin.sh | 30 ++ deploy/gitea-stack/bootstrap-host.sh | 50 +++ .../gitea-stack/create-repo-and-push-hint.sh | 51 +++ deploy/gitea-stack/docker-compose.yml | 111 +++++++ deploy/gitea-stack/install-all.sh | 25 ++ deploy/gitea-stack/register-runner.sh | 35 ++ deploy/gitea-stack/runner/config.yaml | 23 ++ deploy/release/install-deploy-tool.sh | 57 ++++ deploy/release/setup-pgadmin-role.sh | 51 +++ deploy/release/tloto-deploy.sh | 253 +++++++++++++++ deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md | 237 ++++++++++++++ deploy/vps-hardening/PREDEPLOY-CHECKLIST.md | 65 ++++ deploy/vps-hardening/README.md | 100 ++++++ deploy/vps-hardening/allow-docker-pg.sh | 26 ++ deploy/vps-hardening/backup-ssh-key.ps1 | 83 +++++ deploy/vps-hardening/diag-pg-docker2.sh | 39 +++ deploy/vps-hardening/fix-pg-docker.sh | 24 ++ deploy/vps-hardening/fix-pg-for-docker.sh | 46 +++ deploy/vps-hardening/harden-vps.sh | 298 ++++++++++++++++++ .../vps-hardening/remote-bootstrap-env-db.sh | 111 +++++++ .../vps-hardening/remote-bootstrap-phase-a.sh | 139 ++++++++ deploy/vps-hardening/remote-migrate-and-up.sh | 26 ++ .../remote-reset-db-migrate-up.sh | 38 +++ deploy/vps-hardening/tighten-pg-listen.sh | 28 ++ deploy/vps-hardening/verify-harden.sh | 65 ++++ docker-compose.yml | 3 + docs/DEPLOY-VPS.md | 23 +- docs/GITEA-CICD.md | 69 ++++ package.json | 2 + 38 files changed, 2438 insertions(+), 39 deletions(-) create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitea/workflows/deploy.yml create mode 100644 deploy/edge/certs/.gitkeep create mode 100644 deploy/edge/docker-compose.yml create mode 100644 deploy/edge/nginx.conf create mode 100644 deploy/gitea-stack/.env.example create mode 100644 deploy/gitea-stack/.gitignore create mode 100644 deploy/gitea-stack/bootstrap-env.sh create mode 100644 deploy/gitea-stack/bootstrap-gitea-admin.sh create mode 100644 deploy/gitea-stack/bootstrap-host.sh create mode 100644 deploy/gitea-stack/create-repo-and-push-hint.sh create mode 100644 deploy/gitea-stack/docker-compose.yml create mode 100644 deploy/gitea-stack/install-all.sh create mode 100644 deploy/gitea-stack/register-runner.sh create mode 100644 deploy/gitea-stack/runner/config.yaml create mode 100644 deploy/release/install-deploy-tool.sh create mode 100644 deploy/release/setup-pgadmin-role.sh create mode 100644 deploy/release/tloto-deploy.sh create mode 100644 deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md create mode 100644 deploy/vps-hardening/PREDEPLOY-CHECKLIST.md create mode 100644 deploy/vps-hardening/README.md create mode 100644 deploy/vps-hardening/allow-docker-pg.sh create mode 100644 deploy/vps-hardening/backup-ssh-key.ps1 create mode 100644 deploy/vps-hardening/diag-pg-docker2.sh create mode 100644 deploy/vps-hardening/fix-pg-docker.sh create mode 100644 deploy/vps-hardening/fix-pg-for-docker.sh create mode 100644 deploy/vps-hardening/harden-vps.sh create mode 100644 deploy/vps-hardening/remote-bootstrap-env-db.sh create mode 100644 deploy/vps-hardening/remote-bootstrap-phase-a.sh create mode 100644 deploy/vps-hardening/remote-migrate-and-up.sh create mode 100644 deploy/vps-hardening/remote-reset-db-migrate-up.sh create mode 100644 deploy/vps-hardening/tighten-pg-listen.sh create mode 100644 deploy/vps-hardening/verify-harden.sh create mode 100644 docs/GITEA-CICD.md diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 00000000..5025cc7d --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,58 @@ +# CI only — never deploys production. +name: CI +on: + push: + branches: [main, master, develop] + pull_request: + branches: [main, master, develop] + +jobs: + test-and-build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Backend install + compile + working-directory: backend + run: npm ci && npm run build + + - name: Set image tag + id: meta + run: | + SHA="${GITHUB_SHA:-}" + if [ -z "$SHA" ]; then SHA="$(git rev-parse HEAD)"; fi + echo "sha=${SHA:0:12}" >> "$GITHUB_OUTPUT" + echo "full=$SHA" >> "$GITHUB_OUTPUT" + + - name: Build backend image + run: | + docker build -t 127.0.0.1:5000/tloto-backend:${{ steps.meta.outputs.sha }} ./backend + docker tag 127.0.0.1:5000/tloto-backend:${{ steps.meta.outputs.sha }} 127.0.0.1:5000/tloto-backend:sha-${{ steps.meta.outputs.sha }} + + - name: Build web image + run: | + docker build \ + --build-arg VITE_API_BASE_URL=http://127.0.0.1:9080 \ + --build-arg VITE_WS_URL=ws://127.0.0.1:9080/ws/v1/games/candle-predict \ + --build-arg VITE_WS_ENABLED=true \ + -t 127.0.0.1:5000/tloto-web:${{ steps.meta.outputs.sha }} \ + ./prediqo_web + + - name: Push images to local registry + run: | + # Host registry published on 127.0.0.1:5000; from job container use gateway. + # act_runner with docker.sock builds on host daemon — 127.0.0.1:5000 works. + docker push 127.0.0.1:5000/tloto-backend:${{ steps.meta.outputs.sha }} + docker push 127.0.0.1:5000/tloto-web:${{ steps.meta.outputs.sha }} + + - name: Record artifact markers + run: | + mkdir -p .ci-out + echo "${{ steps.meta.outputs.full }}" > .ci-out/sha.txt + echo "CI_OK ${{ steps.meta.outputs.sha }}" diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 00000000..ce1478f3 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,48 @@ +# Manual production deploy — same host mechanism as SSH (`tloto-deploy`). +name: Deploy +on: + workflow_dispatch: + inputs: + ref: + description: "Git SHA, tag, or branch to deploy" + required: true + type: string + mode: + description: "http or https" + required: true + default: http + type: choice + options: + - http + - https + allow_destructive_migrate: + description: "Allow destructive schema heuristic" + required: false + default: false + type: boolean + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Deploy on host via SSH (restricted key) + env: + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} + DEPLOY_SSH_HOST: ${{ secrets.DEPLOY_SSH_HOST }} + run: | + set -euo pipefail + if [ -z "${DEPLOY_SSH_KEY:-}" ]; then + echo "Missing secret DEPLOY_SSH_KEY. Add the private key from ~/gitea-deploy-ssh/id_ed25519 on the VPS." + exit 1 + fi + HOST="${DEPLOY_SSH_HOST:-172.16.0.1}" + mkdir -p ~/.ssh + printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519 + chmod 600 ~/.ssh/id_ed25519 + EXTRA="" + if [ "${{ inputs.allow_destructive_migrate }}" = "true" ]; then + EXTRA="--allow-destructive-migrate" + fi + ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new \ + -i ~/.ssh/id_ed25519 "deploy@${HOST}" \ + "/opt/tloto/bin/tloto-deploy --ref '${{ inputs.ref }}' --mode '${{ inputs.mode }}' ${EXTRA}" diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 0170e57f..6b72bad8 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -305,6 +305,39 @@ ADD COLUMN IF NOT EXISTS from_address VARCHAR(255); ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS to_address VARCHAR(255); +-- Wallet types must exist before approval_policies / user_wallets FKs +CREATE TABLE IF NOT EXISTS wallet_types ( + id SERIAL PRIMARY KEY, + code VARCHAR(32) UNIQUE NOT NULL, + name VARCHAR(100) NOT NULL, + network VARCHAR(50) NOT NULL, + decimals INTEGER NOT NULL DEFAULT 6, + contract_address VARCHAR(255) +); + +INSERT INTO + wallet_types ( + code, + name, + network, + decimals, + contract_address + ) +VALUES ( + 'USDT_TRC20', + 'USDT (TRC20)', + 'TRON', + 6, + 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' + ), + ( + 'USDT_BEP20', + 'USDT (BEP20)', + 'BSC', + 18, + '0x55d398326f99059fF775485246999027B3197955' + ) ON CONFLICT (code) DO NOTHING; + -- Configurable approval policies (N-of-M) CREATE TABLE IF NOT EXISTS approval_policies ( id UUID PRIMARY KEY DEFAULT gen_random_uuid (), @@ -405,39 +438,6 @@ CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens (user_id); CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires ON refresh_tokens (expires_at); --- Wallet types (USDT on TRON TRC20 + BSC BEP20) -CREATE TABLE IF NOT EXISTS wallet_types ( - id SERIAL PRIMARY KEY, - code VARCHAR(32) UNIQUE NOT NULL, - name VARCHAR(100) NOT NULL, - network VARCHAR(50) NOT NULL, - decimals INTEGER NOT NULL DEFAULT 6, - contract_address VARCHAR(255) -); - -INSERT INTO - wallet_types ( - code, - name, - network, - decimals, - contract_address - ) -VALUES ( - 'USDT_TRC20', - 'USDT (TRC20)', - 'TRON', - 6, - 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' - ), - ( - 'USDT_BEP20', - 'USDT (BEP20)', - 'BSC', - 18, - '0x55d398326f99059fF775485246999027B3197955' - ) ON CONFLICT (code) DO NOTHING; - -- User deposit addresses (derived from HD wallet; only public address stored) CREATE TABLE IF NOT EXISTS user_wallets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid (), @@ -1202,12 +1202,46 @@ BEGIN IF NOT EXISTS (SELECT 1 FROM candle_predict_intervals LIMIT 1) THEN FOR mins IN SELECT unnest(ARRAY[1, 3, 5, 10, 15]) AS m LOOP ord := ord + 1; - INSERT INTO candle_predict_intervals (interval_minutes, label, sort_order, is_default, is_active) - VALUES (mins, mins || ' min', ord, mins = 1, TRUE) + -- Explicit overrides (same as global defaults) so admin UI shows filled values. + INSERT INTO candle_predict_intervals ( + interval_minutes, + label, + sort_order, + is_default, + is_active, + tie_tolerance_percent, + tie_tolerance_max_percent, + pool_multiplier, + payout_multiplier + ) + VALUES ( + mins, + mins || ' min', + ord, + mins = 1, + TRUE, + 2.00, + 95.00, + 1.900, + 1.900 + ) ON CONFLICT (interval_minutes) DO NOTHING; END LOOP; END IF; + -- Backfill empty interval overrides to match global defaults (idempotent). + UPDATE candle_predict_intervals + SET + tie_tolerance_percent = COALESCE(tie_tolerance_percent, 2.00), + tie_tolerance_max_percent = COALESCE(tie_tolerance_max_percent, 95.00), + pool_multiplier = COALESCE(pool_multiplier, 1.900), + payout_multiplier = COALESCE(payout_multiplier, 1.900), + updated_at = NOW() + WHERE tie_tolerance_percent IS NULL + OR tie_tolerance_max_percent IS NULL + OR pool_multiplier IS NULL + OR payout_multiplier IS NULL; + IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_name = 'candle_predict_candles' AND column_name = 'interval_minutes' diff --git a/deploy/edge/certs/.gitkeep b/deploy/edge/certs/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/deploy/edge/docker-compose.yml b/deploy/edge/docker-compose.yml new file mode 100644 index 00000000..3ae81a82 --- /dev/null +++ b/deploy/edge/docker-compose.yml @@ -0,0 +1,29 @@ +# Lightweight edge reverse proxy for git.tloto.net (and later tloto.net). +# Until DNS points here, Gitea remains reachable on :3000 directly. +services: + edge: + image: nginx:1.27-alpine + container_name: tloto_edge + restart: unless-stopped + ports: + - "80:80" + - "443:443" + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf:ro + - ./certs:/etc/nginx/certs:ro + - certbot-www:/var/www/certbot:ro + networks: + - edge-net + - gitea-net + profiles: + - edge + +networks: + edge-net: + name: tloto-edge-net + gitea-net: + external: true + name: tloto-gitea-net + +volumes: + certbot-www: diff --git a/deploy/edge/nginx.conf b/deploy/edge/nginx.conf new file mode 100644 index 00000000..f6543762 --- /dev/null +++ b/deploy/edge/nginx.conf @@ -0,0 +1,57 @@ +worker_processes auto; +events { worker_connections 1024; } + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + sendfile on; + server_tokens off; + + # HTTP — ACME + redirect (when certs exist) or proxy to Gitea by Host + server { + listen 80 default_server; + server_name _; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + return 404; + } + } + + server { + listen 80; + server_name git.tloto.net; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + proxy_pass http://tloto_gitea:3000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + } + + # HTTPS for git.tloto.net — enable after placing fullchain.pem + privkey.pem in ./certs/ + # Uncomment when certificates are present: + # + # server { + # listen 443 ssl http2; + # server_name git.tloto.net; + # ssl_certificate /etc/nginx/certs/fullchain.pem; + # ssl_certificate_key /etc/nginx/certs/privkey.pem; + # location / { + # proxy_pass http://tloto_gitea:3000; + # proxy_set_header Host $host; + # proxy_set_header X-Real-IP $remote_addr; + # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + # proxy_set_header X-Forwarded-Proto https; + # } + # } +} diff --git a/deploy/gitea-stack/.env.example b/deploy/gitea-stack/.env.example new file mode 100644 index 00000000..a70609d5 --- /dev/null +++ b/deploy/gitea-stack/.env.example @@ -0,0 +1,22 @@ +# Copy to .env on the VPS (chmod 600). Never commit real values. + +GITEA_DOMAIN=191.215.41.53 +GITEA_ROOT_URL=http://191.215.41.53:3000/ +GITEA_HTTP_PORT=3000 +GITEA_HTTP_BIND=0.0.0.0 +GITEA_SSH_PORT=2222 +GITEA_SSH_BIND=0.0.0.0 + +GITEA_DB_PASSWORD=change-me-gitea-db +GITEA_SECRET_KEY=change-me-64-hex +GITEA_INTERNAL_TOKEN=change-me-internal-token + +# Filled by register-runner.sh after first admin bootstrap +GITEA_RUNNER_REGISTRATION_TOKEN= +GITEA_RUNNER_NAME=tloto-vps-runner +GITEA_RUNNER_LABELS=ubuntu-latest:docker://node:20-bookworm,ubuntu-22.04:docker://node:20-bookworm + +# Admin account created by bootstrap-gitea-admin.sh +GITEA_ADMIN_USER=tloto-admin +GITEA_ADMIN_PASSWORD= +GITEA_ADMIN_EMAIL=admin@tloto.net diff --git a/deploy/gitea-stack/.gitignore b/deploy/gitea-stack/.gitignore new file mode 100644 index 00000000..cdc99a42 --- /dev/null +++ b/deploy/gitea-stack/.gitignore @@ -0,0 +1,2 @@ +.env +*.pem diff --git a/deploy/gitea-stack/bootstrap-env.sh b/deploy/gitea-stack/bootstrap-env.sh new file mode 100644 index 00000000..e7b5a1f0 --- /dev/null +++ b/deploy/gitea-stack/bootstrap-env.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Generate .env with strong secrets if missing. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")" && pwd)" +cd "$ROOT" + +if [[ -f .env ]]; then + echo ".env already exists — skip generation" + exit 0 +fi + +DB_PASS="$(openssl rand -hex 24)" +SECRET_KEY="$(openssl rand -hex 32)" +# Gitea internal token format: long base64-ish string +INTERNAL_TOKEN="$(openssl rand -base64 48 | tr -d '\n')" +ADMIN_PASS="$(openssl rand -base64 24 | tr -d '\n=/+' | head -c 24)" + +cat > .env < "$CRED" </dev/null 2>&1; then + break + fi + sleep 2 +done + +# Create admin if missing (must run as user git — not root) +GITEA_CLI=(sudo docker exec -u git tloto_gitea gitea) +if "${GITEA_CLI[@]}" admin user list 2>/dev/null | grep -q "${GITEA_ADMIN_USER}"; then + echo "Admin ${GITEA_ADMIN_USER} already exists" +else + "${GITEA_CLI[@]}" admin user create \ + --admin \ + --username "${GITEA_ADMIN_USER}" \ + --password "${GITEA_ADMIN_PASSWORD}" \ + --email "${GITEA_ADMIN_EMAIL}" \ + --must-change-password=false + echo "Created admin ${GITEA_ADMIN_USER}" +fi + +echo "ADMIN_BOOTSTRAP_OK" diff --git a/deploy/gitea-stack/bootstrap-host.sh b/deploy/gitea-stack/bootstrap-host.sh new file mode 100644 index 00000000..ad19ae87 --- /dev/null +++ b/deploy/gitea-stack/bootstrap-host.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Prepare host Postgres DB/user for Gitea + UFW ports. Does not touch Tloto app DB. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")" && pwd)" +cd "$ROOT" + +if [[ ! -f .env ]]; then + echo "Missing .env — copy .env.example and set secrets first." >&2 + exit 1 +fi +# shellcheck disable=SC1091 +set -a; source .env; set +a + +if [[ -z "${GITEA_DB_PASSWORD:-}" ]]; then + echo "GITEA_DB_PASSWORD required" >&2 + exit 1 +fi + +echo "== Create Postgres role/db gitea (idempotent) ==" +sudo -u postgres psql -v ON_ERROR_STOP=1 </dev/null; then + echo "REPO_EXISTS" +else + echo "HTTP $code"; cat /tmp/gitea-repo.json; exit 1 +fi + +# Create access token for git push (stored once) +TOKEN_NAME="windows-push-$(date +%Y%m%d)" +TOKEN="$(curl -fsS -u "${USER}:${PASS}" -H 'Content-Type: application/json' \ + -d "{\"name\":\"${TOKEN_NAME}\",\"scopes\":[\"write:repository\",\"write:issue\",\"write:package\",\"read:user\"]}" \ + "${BASE}/api/v1/users/${USER}/tokens" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("sha1",""))')" + +OUT="$HOME/gitea-push-credentials.txt" +cat > "$OUT" <\$null + git remote add gitea http://tloto-admin:${TOKEN}@191.215.41.53:3000/${USER}/${REPO}.git + git push -u gitea HEAD:main + +Then remove the token from the remote URL and use a credential helper: + git remote set-url gitea http://191.215.41.53:3000/${USER}/${REPO}.git +EOF +chmod 600 "$OUT" +echo "Wrote $OUT" diff --git a/deploy/gitea-stack/docker-compose.yml b/deploy/gitea-stack/docker-compose.yml new file mode 100644 index 00000000..e62bf6b4 --- /dev/null +++ b/deploy/gitea-stack/docker-compose.yml @@ -0,0 +1,111 @@ +# Gitea + local registry + act_runner — isolated from Tloto compose. +# Postgres for Gitea uses the host Postgres (DB name: gitea), not games_platform_db. +# +# First boot (HTTP on :3000 until DNS/edge HTTPS): +# cp .env.example .env && edit secrets +# ./bootstrap-host.sh # creates DB/user + UFW +# docker compose up -d gitea registry +# ./bootstrap-gitea-admin.sh +# ./register-runner.sh && docker compose up -d runner + +services: + gitea: + image: gitea/gitea:1.22.6 + container_name: tloto_gitea + restart: unless-stopped + environment: + USER_UID: "1000" + USER_GID: "1000" + GITEA__database__DB_TYPE: postgres + GITEA__database__HOST: host.docker.internal:5432 + GITEA__database__NAME: gitea + GITEA__database__USER: gitea + GITEA__database__PASSWD: ${GITEA_DB_PASSWORD} + GITEA__server__DOMAIN: ${GITEA_DOMAIN:-191.215.41.53} + GITEA__server__ROOT_URL: ${GITEA_ROOT_URL:-http://191.215.41.53:3000/} + GITEA__server__HTTP_PORT: "3000" + GITEA__server__SSH_DOMAIN: ${GITEA_DOMAIN:-191.215.41.53} + # Published host port for git-ssh (container listens on 22 via image sshd) + GITEA__server__SSH_PORT: ${GITEA_SSH_PORT:-2222} + GITEA__server__SSH_LISTEN_PORT: "22" + # false = use image OpenSSH on :22 (avoid clash with Gitea built-in SSH) + GITEA__server__START_SSH_SERVER: "false" + GITEA__server__DISABLE_SSH: "false" + GITEA__service__DISABLE_REGISTRATION: "true" + GITEA__service__REQUIRE_SIGNIN_VIEW: "false" + GITEA__security__INSTALL_LOCK: "true" + GITEA__security__SECRET_KEY: ${GITEA_SECRET_KEY} + GITEA__security__INTERNAL_TOKEN: ${GITEA_INTERNAL_TOKEN} + GITEA__session__PROVIDER: memory + GITEA__actions__ENABLED: "true" + GITEA__actions__DEFAULT_ACTIONS_URL: self + GITEA__openid__ENABLE_OPENID_SIGNIN: "false" + GITEA__openid__ENABLE_OPENID_SIGNUP: "false" + GITEA__mailer__ENABLED: "false" + extra_hosts: + - "host.docker.internal:host-gateway" + volumes: + - gitea-data:/data + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + ports: + - "${GITEA_HTTP_BIND:-0.0.0.0}:${GITEA_HTTP_PORT:-3000}:3000" + - "${GITEA_SSH_BIND:-0.0.0.0}:${GITEA_SSH_PORT:-2222}:22" + networks: + - gitea-net + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:3000/"] + interval: 15s + timeout: 5s + retries: 10 + start_period: 40s + + registry: + image: registry:2.8.3 + container_name: tloto_registry + restart: unless-stopped + environment: + REGISTRY_STORAGE_DELETE_ENABLED: "true" + volumes: + - registry-data:/var/lib/registry + # Localhost only — CI runner reaches it via Docker network; host builds via 127.0.0.1 + ports: + - "127.0.0.1:5000:5000" + networks: + - gitea-net + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:5000/v2/"] + interval: 20s + timeout: 5s + retries: 5 + + runner: + image: gitea/act_runner:0.2.11 + container_name: tloto_act_runner + restart: unless-stopped + depends_on: + gitea: + condition: service_healthy + environment: + CONFIG_FILE: /config.yaml + GITEA_INSTANCE_URL: http://gitea:3000 + GITEA_RUNNER_REGISTRATION_TOKEN: ${GITEA_RUNNER_REGISTRATION_TOKEN:-} + GITEA_RUNNER_NAME: ${GITEA_RUNNER_NAME:-tloto-vps-runner} + GITEA_RUNNER_LABELS: ${GITEA_RUNNER_LABELS:-ubuntu-latest:docker://node:20-bookworm,ubuntu-22.04:docker://node:20-bookworm} + volumes: + - ./runner/config.yaml:/config.yaml:ro + - runner-data:/data + - /var/run/docker.sock:/var/run/docker.sock + networks: + - gitea-net + profiles: + - runner + +networks: + gitea-net: + name: tloto-gitea-net + +volumes: + gitea-data: + registry-data: + runner-data: diff --git a/deploy/gitea-stack/install-all.sh b/deploy/gitea-stack/install-all.sh new file mode 100644 index 00000000..03eddc1b --- /dev/null +++ b/deploy/gitea-stack/install-all.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Full Gitea stack install on VPS — does not modify Tloto games_app compose. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")" && pwd)" +cd "$ROOT" + +bash ./bootstrap-env.sh +bash ./bootstrap-host.sh + +echo "== Pull + start Gitea + registry ==" +sudo docker compose pull gitea registry +sudo docker compose up -d gitea registry + +bash ./bootstrap-gitea-admin.sh +bash ./register-runner.sh + +echo "== Smoke ==" +curl -fsS -m 10 "http://127.0.0.1:${GITEA_HTTP_PORT:-3000}/" -o /dev/null && echo "GITEA_HTTP_OK" +curl -fsS -m 5 "http://127.0.0.1:5000/v2/" && echo "REGISTRY_OK" +# Tloto must still be up +curl -fsS -m 5 http://127.0.0.1:9080/health | head -c 60; echo + +echo "INSTALL_ALL_OK" +echo "Admin credentials: ~/gitea-admin-credentials.txt" +echo "URL: http://191.215.41.53:3000/" diff --git a/deploy/gitea-stack/register-runner.sh b/deploy/gitea-stack/register-runner.sh new file mode 100644 index 00000000..96db007c --- /dev/null +++ b/deploy/gitea-stack/register-runner.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Generate Actions runner registration token and write it into .env, then start runner profile. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")" && pwd)" +cd "$ROOT" +set -a; source .env; set +a + +TOKEN="$(sudo docker exec -u git tloto_gitea gitea actions generate-runner-token)" +if [[ -z "$TOKEN" ]]; then + echo "Failed to generate runner token" >&2 + exit 1 +fi + +# Update .env token line +if grep -q '^GITEA_RUNNER_REGISTRATION_TOKEN=' .env; then + sed -i "s|^GITEA_RUNNER_REGISTRATION_TOKEN=.*|GITEA_RUNNER_REGISTRATION_TOKEN=${TOKEN}|" .env +else + echo "GITEA_RUNNER_REGISTRATION_TOKEN=${TOKEN}" >> .env +fi + +# Clear previous runner registration so token re-registers cleanly +sudo docker compose --profile runner stop runner 2>/dev/null || true +sudo docker compose --profile runner rm -f runner 2>/dev/null || true +# volume name may be prefixed by directory name (ignore if none) +while read -r v; do + [[ -n "$v" ]] || continue + sudo docker volume rm "$v" 2>/dev/null || true +done < <(sudo docker volume ls -q | grep -E 'runner-data$' || true) + +sudo docker compose --profile runner pull runner +sudo docker compose --profile runner up -d runner +sleep 8 +sudo docker compose --profile runner ps +sudo docker logs tloto_act_runner --tail 40 || true +echo "RUNNER_REGISTER_OK" diff --git a/deploy/gitea-stack/runner/config.yaml b/deploy/gitea-stack/runner/config.yaml new file mode 100644 index 00000000..7c35d0a7 --- /dev/null +++ b/deploy/gitea-stack/runner/config.yaml @@ -0,0 +1,23 @@ +# act_runner config — runner has docker.sock for CI builds only. +# It must NOT execute production deploy; that goes through tloto-deploy via SSH ForceCommand / sudoers. +log: + level: info + +runner: + capacity: 1 + timeout: 3h + insecure: false + fetch_timeout: 5s + fetch_interval: 2s + +cache: + enabled: true + +container: + # Jobs run in sibling containers; host docker.sock required for docker build in CI. + privileged: false + network: tloto-gitea-net + options: null + valid_volumes: [] + docker_host: "" + force_pull: false diff --git a/deploy/release/install-deploy-tool.sh b/deploy/release/install-deploy-tool.sh new file mode 100644 index 00000000..0fb71561 --- /dev/null +++ b/deploy/release/install-deploy-tool.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Install tloto-deploy into /opt/tloto/bin and wire CI deploy SSH key. +set -euo pipefail +APP_DIR="${TLOTO_APP_DIR:-/home/deploy/games_app}" +SRC="$APP_DIR/deploy/release/tloto-deploy.sh" + +sudo mkdir -p /opt/tloto/bin /var/lib/tloto/releases /var/lib/tloto/backups +sudo cp "$SRC" /opt/tloto/bin/tloto-deploy +sudo chmod 755 /opt/tloto/bin/tloto-deploy +sudo chown deploy:deploy /opt/tloto/bin/tloto-deploy +sudo chown -R deploy:deploy /var/lib/tloto + +# Restricted CI deploy key (Actions → SSH → tloto-deploy only) +KEY_DIR="/home/deploy/gitea-deploy-ssh" +mkdir -p "$KEY_DIR" +chmod 700 "$KEY_DIR" +if [[ ! -f "$KEY_DIR/id_ed25519" ]]; then + ssh-keygen -t ed25519 -N "" -f "$KEY_DIR/id_ed25519" -C "gitea-actions-deploy" +fi +chmod 600 "$KEY_DIR/id_ed25519" +AUTH="/home/deploy/.ssh/authorized_keys" +mkdir -p /home/deploy/.ssh +chmod 700 /home/deploy/.ssh +MARKER="gitea-actions-deploy" +if ! grep -q "$MARKER" "$AUTH" 2>/dev/null; then + # ForceCommand limits this key to tloto-deploy (args passed after --) + PUB="$(cat "$KEY_DIR/id_ed25519.pub")" + echo "command=\"/opt/tloto/bin/tloto-deploy-ssh-wrapper\",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty $PUB" >> "$AUTH" +fi +chmod 600 "$AUTH" + +cat > /opt/tloto/bin/tloto-deploy-ssh-wrapper <<'WRAP' +#!/usr/bin/env bash +set -euo pipefail +# SSH forced command: only allow tloto-deploy with safe args from SSH_ORIGINAL_COMMAND +cmd="${SSH_ORIGINAL_COMMAND:-}" +if [[ -z "$cmd" ]]; then + echo "tloto-deploy-ssh-wrapper: missing SSH_ORIGINAL_COMMAND" >&2 + exit 1 +fi +# Must start with absolute path to tloto-deploy +if [[ ! "$cmd" =~ ^/opt/tloto/bin/tloto-deploy([[:space:]]|$) ]]; then + echo "refusing command: $cmd" >&2 + exit 1 +fi +# Disallow shell metacharacters +if [[ "$cmd" =~ [;&|<>`$()] ]]; then + echo "refusing unsafe characters" >&2 + exit 1 +fi +exec bash -lc "$cmd" +WRAP +sudo chmod 755 /opt/tloto/bin/tloto-deploy-ssh-wrapper + +echo "Installed /opt/tloto/bin/tloto-deploy" +echo "CI private key: $KEY_DIR/id_ed25519 (add as Gitea secret DEPLOY_SSH_KEY)" +echo "Suggested DEPLOY_SSH_HOST=172.16.0.1 (docker0) or 127.0.0.1 from host-network jobs" diff --git a/deploy/release/setup-pgadmin-role.sh b/deploy/release/setup-pgadmin-role.sh new file mode 100644 index 00000000..72b9a307 --- /dev/null +++ b/deploy/release/setup-pgadmin-role.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Create limited Postgres role for pgAdmin over SSH tunnel (no public 5432). +set -euo pipefail +PASS_FILE="${HOME}/pgadmin-db-credentials.txt" + +if [[ -f "$PASS_FILE" ]]; then + echo "Credentials file already exists: $PASS_FILE" + # still ensure role exists / password rotated only if FORCE=1 + if [[ "${FORCE:-0}" != "1" ]]; then + exit 0 + fi +fi + +PASS="$(openssl rand -base64 24 | tr -d '\n=/+' | head -c 28)" +sudo -u postgres psql -v ON_ERROR_STOP=1 < "$PASS_FILE" < [options] + tloto-deploy --rollback + +Options: + --ref Git ref to deploy (required unless --rollback) + --mode http|https Compose profile path (default: http until DNS cutover) + --health-url Health check URL + --allow-destructive-migrate Allow DROP/TRUNCATE-like schema changes without abort + --skip-migrate Skip npm run db:migrate + --rollback Redeploy previous successful release (app only) + -h, --help Show help +EOF +} + +log() { printf '[tloto-deploy] %s\n' "$*"; } +die() { printf '[tloto-deploy] ERROR: %s\n' "$*" >&2; exit 1; } + +while [[ $# -gt 0 ]]; do + case "$1" in + --ref) REF="${2:-}"; shift 2 ;; + --mode) MODE="${2:-}"; shift 2 ;; + --health-url) HEALTH_URL="${2:-}"; shift 2 ;; + --allow-destructive-migrate) ALLOW_DESTRUCTIVE=1; shift ;; + --skip-migrate) SKIP_MIGRATE=1; shift ;; + --rollback) ROLLBACK_ONLY=1; shift ;; + -h|--help) usage; exit 0 ;; + *) die "unknown arg: $1" ;; + esac +done + +mkdir -p "$RELEASES_DIR" "$BACKUPS_DIR" +cd "$APP_DIR" + +if [[ ! -f .env ]]; then + die "missing $APP_DIR/.env" +fi + +exec 9>"$LOCK_FILE" +if ! flock -n 9; then + die "another deploy is in progress (lock $LOCK_FILE)" +fi + +ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } +release_id() { date -u +%Y%m%dT%H%M%SZ; } + +read_prev_sha() { + if [[ -f "$CURRENT_FILE" ]]; then + python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("sha",""))' "$CURRENT_FILE" 2>/dev/null || true + fi +} + +write_release() { + local id="$1" sha="$2" prev="$3" status="$4" detail="${5:-}" + local path="$RELEASES_DIR/${id}.json" + python3 - </dev/null 2>&1 \ + && sudo docker image inspect "${REGISTRY}/tloto-web:${sha_tag}" >/dev/null 2>&1; then + log "using registry images tag=$sha_tag" + if [[ "$MODE" == "https" ]]; then + sudo -E docker compose --profile https-dns --profile clamav up -d + sudo docker restart vps_gateway_nginx >/dev/null 2>&1 || true + else + sudo -E docker compose --profile http --profile clamav up -d + sudo docker restart vps_gateway_nginx >/dev/null 2>&1 || true + fi + else + log "building via npm phase-b:up* (tag=$sha_tag)" + if [[ "$MODE" == "https" ]]; then + sudo -E npm run phase-b:up:https + else + sudo -E npm run phase-b:up + fi + # Record tags for future rollback + sudo docker tag "games_app-backend:latest" "${REGISTRY}/tloto-backend:${sha_tag}" 2>/dev/null || true + sudo docker tag "games_app-prediqo-web:latest" "${REGISTRY}/tloto-web:${sha_tag}" 2>/dev/null || true + sudo docker push "${REGISTRY}/tloto-backend:${sha_tag}" 2>/dev/null || true + sudo docker push "${REGISTRY}/tloto-web:${sha_tag}" 2>/dev/null || true + fi +} + +health_check() { + local i code + for i in $(seq 1 40); do + code="$(curl -s -o /tmp/tloto-health.body -w '%{http_code}' -m 5 "$HEALTH_URL" || echo 000)" + if [[ "$code" == "200" ]]; then + log "health OK ($code)" + return 0 + fi + log "health wait $i code=$code" + sleep 3 + done + return 1 +} + +schema_looks_destructive() { + # Heuristic on schema.sql diff vs previous working tree / release marker + local schema="$APP_DIR/backend/src/db/schema.sql" + local marker="$STATE_DIR/last-schema.sha256" + [[ -f "$schema" ]] || return 1 + local now + now="$(sha256sum "$schema" | awk '{print $1}')" + if [[ -f "$marker" ]]; then + local old + old="$(cat "$marker")" + if [[ "$old" == "$now" ]]; then + return 1 + fi + fi + if grep -Eiq 'DROP[[:space:]]+(TABLE|COLUMN|SCHEMA)|TRUNCATE[[:space:]]' "$schema"; then + return 0 + fi + return 1 +} + +backup_db() { + local out="$BACKUPS_DIR/games_platform_db_$(date -u +%Y%m%dT%H%M%SZ).dump" + log "pg_dump → $out" + # Use peer/local via sudo -u postgres + sudo -u postgres pg_dump -Fc -d games_platform_db -f "$out" + echo "$out" +} + +checkout_ref() { + local ref="$1" + if [[ ! -d .git ]]; then + die "$APP_DIR is not a git checkout — clone from Gitea first" + fi + git fetch --all --tags --prune + git checkout --force "$ref" + git reset --hard "$ref" + git rev-parse HEAD +} + +export_image_tags() { + local sha="$1" + # Optional override for compose image tags (compose-image-tags support) + export TLOTO_IMAGE_TAG="$sha" + export COMPOSE_DOCKER_CLI_BUILD=1 +} + +deploy_sha() { + local sha="$1" + local prev id + prev="$(read_prev_sha)" + id="$(release_id)" + STARTED_AT="$(ts)" + log "deploy start id=$id sha=$sha prev=${prev:-none} mode=$MODE" + + export_image_tags "$sha" + + if [[ "$SKIP_MIGRATE" -eq 0 ]]; then + if schema_looks_destructive && [[ "$ALLOW_DESTRUCTIVE" -eq 0 ]]; then + write_release "$id" "$sha" "$prev" "aborted" "destructive schema heuristic; pass --allow-destructive-migrate" + die "schema.sql looks destructive — aborting (no migrate/up). Use --allow-destructive-migrate after review." + fi + local marker="$STATE_DIR/last-schema.sha256" + local now + now="$(sha256sum backend/src/db/schema.sql | awk '{print $1}')" + if [[ ! -f "$marker" ]] || [[ "$(cat "$marker")" != "$now" ]]; then + backup_db >/dev/null + fi + log "npm run db:migrate" + sudo npm run db:migrate + echo "$now" > "$marker" + else + log "skip migrate" + fi + + log "compose up ($MODE)" + compose_up + + if ! health_check; then + write_release "$id" "$sha" "$prev" "failed" "health check failed" + if [[ -n "${prev:-}" ]]; then + log "rolling back app to $prev" + checkout_ref "$prev" >/dev/null + export_image_tags "$prev" + compose_up || true + health_check || log "rollback health still failing — manual intervention required" + write_release "$(release_id)" "$prev" "$sha" "rollback" "auto after failed $sha" + fi + die "deploy failed health check" + fi + + write_release "$id" "$sha" "$prev" "success" "ok" + log "deploy success sha=$sha" +} + +STARTED_AT="$(ts)" + +if [[ "$ROLLBACK_ONLY" -eq 1 ]]; then + prev="$(read_prev_sha)" + [[ -n "$prev" ]] || die "no current release to infer previous from; set --ref explicitly" + # Prefer prev_sha inside current.json + target="$(python3 -c 'import json;print(json.load(open("'"$CURRENT_FILE"'")).get("prev_sha",""))' 2>/dev/null || true)" + [[ -n "$target" ]] || die "no prev_sha recorded" + sha="$(checkout_ref "$target")" + deploy_sha "$sha" + exit 0 +fi + +[[ -n "$REF" ]] || die "--ref required" +sha="$(checkout_ref "$REF")" +deploy_sha "$sha" diff --git a/deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md b/deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md new file mode 100644 index 00000000..a2733486 --- /dev/null +++ b/deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md @@ -0,0 +1,237 @@ +# Migration Tloto → nouveau VPS (fresh install) + +**Cible :** `deploy@191.215.41.53` (hôte déjà durci) +**Stratégie :** réinstallation propre (DB + secrets **nouveaux**), car les comptes DB sont des tests et les fonds utiles sont sur MetaMask (cold). + +> Ne **pas** restaurer le dump de l’ancien VPS. +> Ne **pas** réutiliser `ENCRYPTION_KEY` / `PLATFORM_MNEMONIC` de l’ancien serveur. + +Garde l’**ancien** VPS en ligne jusqu’au cutover DNS validé. + +--- + +## Vue d’ensemble + +| Phase | Quoi | Ancien VPS | Nouveau VPS | +|-------|------|------------|-------------| +| A | Préparer code + `.env` + Postgres | Prod inchangée | Clone + secrets frais | +| B | Stack HTTP smoke test | Prod inchangée | `:9080` sur l’IP | +| C | Admin setup + hot wallets | — | `/setup`, seed hots | +| D | HTTPS + DNS `tloto.net` | Puis arrêter | `:9443` / gateway | +| E | Fermer l’ancien | Stop stack | Prod unique | + +--- + +## Phase A — Clone, secrets, base vide + +Sur ton PC (PowerShell) : + +```powershell +ssh deploy@191.215.41.53 +``` + +Sur le VPS : + +```bash +sudo apt-get update -y +# Node optionnel (pour npm run phase-b:*) — sinon docker compose seul +curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - +sudo apt-get install -y nodejs + +cd ~ +git clone https://github.com/japhni/games-project.git games_app +cd games_app +git checkout master +git pull + +cp .env.example .env +chmod 600 .env +``` + +### Générer les secrets (sur le VPS) — sauvegarde offline + +```bash +echo "ENCRYPTION_KEY=$(openssl rand -hex 32)" +echo "JWT_SECRET=$(openssl rand -base64 48 | tr -d '\n=/+' | head -c 48)" +echo "REDIS_PASSWORD=$(openssl rand -hex 32)" +echo "INITIAL_SETUP_TOKEN=$(openssl rand -hex 24)" +echo "BREAK_GLASS_TOKEN=$(openssl rand -hex 32)" +echo "POSTGRES_PASSWORD=$(openssl rand -hex 24)" +# Mnemonic 24 mots — générer hors ligne (MetaMask / outil BIP39) puis coller dans .env +``` + +Édite `.env` (`nano .env`) — points critiques : + +```env +POSTGRES_USER=postgres +POSTGRES_PASSWORD= +POSTGRES_DB=games_platform_db +DATABASE_URL=postgresql://postgres:@host.docker.internal:5432/games_platform_db +DATABASE_PASSWORD= + +REDIS_PASSWORD= +JWT_SECRET= +ENCRYPTION_KEY=<64 hex> +PLATFORM_MNEMONIC=<24 mots BIP39 nouveaux> +INITIAL_SETUP_TOKEN= +BREAK_GLASS_TOKEN= + +# Phase B smoke (IP) — avant DNS +APP_PUBLIC_URL=http://191.215.41.53:9080 +CORS_ORIGINS=http://191.215.41.53:9080 +VITE_API_BASE_URL=http://191.215.41.53:9080 +VITE_WS_ENABLED=true +VITE_WS_URL=ws://191.215.41.53:9080/ws/v1/games/candle-predict + +# Mainnet (prod) +TRON_NODE_URL=https://api.trongrid.io +TRON_CONFIRMATIONS=20 +BSC_RPC_URL=https://bsc-dataseed.binance.org +BSC_CONFIRMATIONS=15 +ALLOW_WITHDRAWALS=false +SWEEP_ENABLED=false + +# Optionnel : reprendre Turnstile / SMTP depuis l’ancien .env (pas les clés crypto) +# TURNSTILE_SITE_KEY=... +# TURNSTILE_SECRET_KEY=... +# SMTP_*=... +# EMAIL_FROM=... + +RUN_MIGRATE_ON_START=0 +CERTBOT_EMAIL=ton@email.com +CERTBOT_DOMAIN1=tloto.net +CERTBOT_DOMAIN2=www.tloto.net +``` + +### Postgres hôte — user + DB + +```bash +# Définir le mot de passe postgres OS si besoin, puis : +sudo -u postgres psql -c "ALTER USER postgres PASSWORD '';" +sudo -u postgres psql -c "SELECT 1 FROM pg_database WHERE datname='games_platform_db'" | grep -q 1 \ + || sudo -u postgres createdb -O postgres games_platform_db + +# listen localhost déjà posé par harden-vps.sh +sudo ss -tlnp | grep 5432 +``` + +--- + +## Phase B — Premier démarrage HTTP + +```bash +cd ~/games_app +# Si npm disponible : +sudo npm run phase-b:init + +# Sinon Docker seul : +sudo docker compose run --rm --no-deps --build backend node dist/db/migrate.js +sudo docker compose --profile http --profile clamav up -d --build +``` + +Vérifs : + +```bash +sudo docker compose ps +curl -fsS http://127.0.0.1:9080/health +curl -fsS http://191.215.41.53:9080/setup/status +``` + +Navigateur : `http://191.215.41.53:9080/setup` avec `INITIAL_SETUP_TOKEN`. + +--- + +## Phase C — Post-setup + +1. Créer Super Admin + activer **2FA** + sauver recovery codes offline. +2. (Recommandé) 2ᵉ admin. +3. Seed hot wallets **une seule fois** : + +```bash +cd ~/games_app +sudo docker compose run --rm --no-deps --build backend node dist/scripts/seedHotWallets.js +sudo npm run phase-b:verify-deposit-addresses +# ou : sudo docker compose run --rm --no-deps backend node dist/scripts/verifyDepositAddresses.js +``` + +4. Noter les **nouvelles** adresses hot TRON + BSC (différentes de l’ancien mnémonique). +5. Configurer cold MetaMask dans Treasury + `SWEEP_COLD_ALLOWLIST` si besoin. +6. SQL recommandé : + +```sql +INSERT INTO system_settings (key, value, updated_at) +VALUES ('encryption_key_rotated_at', NOW()::text, NOW()) +ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW(); +``` + +7. Intervalles Candle Predict : le seed applique Min tie **2** / Max **95** / Pool **1.9** / Payout **1.9**. + +--- + +## Phase D — Cutover DNS + HTTPS + +1. TTL DNS bas (si possible) sur `tloto.net` / `www`. +2. Mettre à jour `.env` **avant** rebuild web : + +```env +APP_PUBLIC_URL=https://tloto.net:9443 +CORS_ORIGINS=https://tloto.net:9443,https://www.tloto.net:9443 +VITE_API_BASE_URL=https://tloto.net:9443 +VITE_WS_URL=wss://tloto.net:9443/ws/v1/games/candle-predict +``` + +(Adapte si le gateway sert l’apex en `:443` sans port — voir `docs/DEPLOY-VPS.md`.) + +3. Enregistrements **A** → `191.215.41.53`. +4. Certificat : + +```bash +cd ~/games_app +sudo npm run ssl:dns-init # ou parcours documenté dans DEPLOY-VPS +sudo npm run phase-b:up:https +``` + +5. Smoke : + +```bash +curl -fsS https://tloto.net:9443/health +# login admin, dépôt test BEP20, retraits toujours OFF +``` + +6. App mobile : rebuild avec `API_BASE_URL` / prod si hardcodé autrement. + +--- + +## Phase E — Ancien VPS + +Après validation (24–48 h recommandées) : + +```bash +# Sur l’ANCIEN serveur uniquement +cd ~/…/games_app # chemin réel +sudo npm run phase-b:down +# optionnel : snapshot / pg_dump archive offline avant DROP +``` + +Ne supprime l’ancien dump/host qu’après confirmation MetaMask + nouvelle prod OK. + +--- + +## Rollback rapide + +Si le nouveau VPS échoue après DNS : remettre les **A** vers l’**ancienne** IP, remonter l’ancienne stack. Les nouveaux hot du VPS B restent orphelins jusqu’à réutilisation éventuelle de leur mnémonique (gardé offline). + +--- + +## Checklist express + +- [ ] Fonds cold MetaMask OK ; hot ancien vidé (dust OK) +- [ ] `ssh deploy@191.215.41.53` OK +- [ ] Clone `games_app` + `.env` **nouveaux** secrets +- [ ] DB `games_platform_db` créée +- [ ] `phase-b:init` HTTP + `/setup` +- [ ] Hot wallets seed + verify +- [ ] DNS → nouvelle IP + HTTPS +- [ ] Ancien VPS arrêté + +Références : [PREDEPLOY-CHECKLIST.md](./PREDEPLOY-CHECKLIST.md), [docs/DEPLOY-VPS.md](../../docs/DEPLOY-VPS.md). diff --git a/deploy/vps-hardening/PREDEPLOY-CHECKLIST.md b/deploy/vps-hardening/PREDEPLOY-CHECKLIST.md new file mode 100644 index 00000000..a28e58f8 --- /dev/null +++ b/deploy/vps-hardening/PREDEPLOY-CHECKLIST.md @@ -0,0 +1,65 @@ +# Checklist pre-deploy Tloto (après harden-vps.sh) + +À cocher **avant** `npm run phase-b:init` ou `phase-b:init:https` sur le VPS durci. + +## Accès & OS + +- [ ] `ssh deploy@` fonctionne **sans** mot de passe +- [ ] `sudo -n true` OK pour `deploy` +- [ ] `PermitRootLogin no` / `PasswordAuthentication no` (fichier `/etc/ssh/sshd_config.d/99-tloto.conf`) +- [ ] `sudo ufw status` : allow seulement `22/tcp` (OpenSSH), `9080/tcp`, `9443/tcp` +- [ ] `fail2ban-client status sshd` actif +- [ ] `docker --version` et `docker compose version` OK +- [ ] Postgres écoute localhost : `ss -tlnp | grep 5432` → `127.0.0.1` / `::1` seulement + +## Secrets (générer une fois, backup offline, jamais git) + +```bash +# Sur le VPS ou en local, coller uniquement dans .env (chmod 600) +openssl rand -hex 32 # ENCRYPTION_KEY +openssl rand -base64 48 # JWT_SECRET / REDIS_PASSWORD / tokens +# PLATFORM_MNEMONIC : 24 mots BIP39 (outil dédié / procédure DEPLOY-VPS) +``` + +- [ ] `.env` à la racine du clone, `chmod 600` +- [ ] `ENCRYPTION_KEY`, `JWT_SECRET`, `REDIS_PASSWORD`, `INITIAL_SETUP_TOKEN`, `BREAK_GLASS_TOKEN`, `PLATFORM_MNEMONIC` +- [ ] `POSTGRES_*` / `DATABASE_URL` cohérents avec Postgres hôte +- [ ] Après première mise en service : enregistrer `encryption_key_rotated_at` (évite spam admin « Encryption key rotation due ») + +## URLs & CORS (prod HTTPS) + +- [ ] DNS **A** du domaine → IP du VPS (ex. `191.215.41.53`) +- [ ] `APP_PUBLIC_URL=https://:9443` (ou 443 via gateway) +- [ ] `CORS_ORIGINS` = **même origine** que le front (liste blanche stricte) +- [ ] `VITE_API_BASE_URL` aligné sur `APP_PUBLIC_URL` (rebuild web après changement) +- [ ] `VITE_WS_URL=wss://…/ws/v1/games/candle-predict` +- [ ] `CERTBOT_EMAIL` / `CERTBOT_DOMAIN1` pour Let’s Encrypt + +## Sécurité produit (flags initiaux) + +- [ ] `ALLOW_WITHDRAWALS=false` jusqu’à validation dépôts +- [ ] `SWEEP_ENABLED=false` jusqu’au test cold +- [ ] Turnstile : `TURNSTILE_SITE_KEY` + `TURNSTILE_SECRET_KEY` (web) ; mobile = math via `X-Tloto-Platform` +- [ ] SMTP vérifié : `npm run phase-b:verify-smtp` (après clone) + +## Première mise en route + +```bash +cd ~/games_app # ou chemin du clone +sudo npm run phase-b:init:https # ou phase-b:init en HTTP test +curl -fsS https://:9443/health +# puis /setup avec INITIAL_SETUP_TOKEN +``` + +- [ ] Super Admin créé + 2FA + recovery codes offline +- [ ] 2ᵉ admin recommandé +- [ ] Hot wallets seed **une fois** ; ne plus changer `ENCRYPTION_KEY` / `PLATFORM_MNEMONIC` sans runbook rotation +- [ ] Backup Postgres chiffré **hors VPS** avant argent réel + +## Références + +- **Cutover fresh-install vers nouveau VPS :** [MIGRATE-TO-NEW-VPS.md](./MIGRATE-TO-NEW-VPS.md) +- [docs/DEPLOY-VPS.md](../../docs/DEPLOY-VPS.md) +- [deploy/ENCRYPTION_KEY_ROTATION.md](../ENCRYPTION_KEY_ROTATION.md) +- [deploy/PRODUCTION_SENTRY_CLAMAV.md](../PRODUCTION_SENTRY_CLAMAV.md) +- [deploy/SECURITY_CSRF.md](../SECURITY_CSRF.md) diff --git a/deploy/vps-hardening/README.md b/deploy/vps-hardening/README.md new file mode 100644 index 00000000..84994c2e --- /dev/null +++ b/deploy/vps-hardening/README.md @@ -0,0 +1,100 @@ +# Durcissement VPS Tloto (Phase B host) + +Runbook pour préparer un VPS **avant** `phase-b:init` / `phase-b:init:https`. +Cible documentée : [docs/DEPLOY-VPS.md](../../docs/DEPLOY-VPS.md). + +**Hôte d’exemple :** `191.215.41.53` + +## Ordre critique (ne pas inverser) + +1. Garder une session `root` ouverte jusqu’à la fin. +2. Installer ta **clé SSH** pour l’utilisateur `deploy`. +3. Tester `ssh deploy@…` dans une **deuxième** fenêtre. +4. Relancer le script (ou laisser le script verrouiller) pour couper root/password. +5. Seulement ensuite : UFW / Docker / Postgres sont déjà appliqués par le script. + +## Prérequis sur ton PC + +```powershell +# Vérifier la clé publique locale +Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub +``` + +## Exécution (depuis ton PC, Windows) + +### A. Copier le script + ta clé publique + +```powershell +cd d:\Projects_Workplace\Own_Projects\games_app + +scp deploy\vps-hardening\harden-vps.sh root@191.215.41.53:/root/ +scp $env:USERPROFILE\.ssh\id_ed25519.pub root@191.215.41.53:/root/tloto_deploy.pub +``` + +*(Premier login : mot de passe root. Après le lock, uniquement `deploy` + clé.)* + +### B. Lancer le durcissement + +```bash +ssh root@191.215.41.53 +bash /root/harden-vps.sh +``` + +Le script : + +- crée `deploy` (sudo + docker) +- lit `/root/tloto_deploy.pub` ou `DEPLOY_SSH_PUBKEY` +- UFW : SSH + 9080 + 9443 seulement +- fail2ban (sshd) +- unattended-upgrades +- sysctl réseau +- Docker Engine + Compose +- PostgreSQL `listen_addresses = localhost` +- **verrouille SSH** si une clé `deploy` est présente (`PermitRootLogin no`, `PasswordAuthentication no`, `AllowUsers deploy`) + +Sans clé : mode soft (passwords encore autorisés) — relancer après `ssh-copy-id`. + +### C. Vérifier avant de fermer root + +```powershell +ssh deploy@191.215.41.53 "whoami; sudo -n true; docker --version; sudo ufw status" +``` + +Si ça marche, tu peux fermer la session root. + +### D. Forcer un verrouillage plus tard + +```bash +# en root (si encore possible) ou : sudo -i en tant que deploy +export DEPLOY_SSH_PUBKEY="$(cat /root/tloto_deploy.pub)" +bash /root/harden-vps.sh +``` + +## Variables optionnelles + +| Variable | Effet | +|----------|--------| +| `DEPLOY_USER` | Nom du user (défaut `deploy`) | +| `DEPLOY_SSH_PUBKEY` | Une ligne de clé publique | +| `SKIP_SSH_LOCK=1` | Ne coupe pas password/root | +| `SKIP_DOCKER=1` | Pas d’install Docker | +| `SKIP_POSTGRES=1` | Pas de durcissement Postgres | + +## Ce que le script n’ouvre jamais + +- `5432` Postgres +- `6379` Redis +- `4000` / `4001` API/WS directs + +Redis reste **interne Docker** (mot de passe `.env`) au moment du déploiement app. + +## Suite déploiement app + +Voir [PREDEPLOY-CHECKLIST.md](./PREDEPLOY-CHECKLIST.md) puis [docs/DEPLOY-VPS.md](../../docs/DEPLOY-VPS.md). + +## Hors scope de ce runbook + +- Cutover DNS `tloto.net` +- Migration DB depuis l’ancien VPS +- Phase C (K8s / Kafka) +- Cloudflare proxy (recommandé après DNS) diff --git a/deploy/vps-hardening/allow-docker-pg.sh b/deploy/vps-hardening/allow-docker-pg.sh new file mode 100644 index 00000000..87451709 --- /dev/null +++ b/deploy/vps-hardening/allow-docker-pg.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# UFW: allow Docker bridges → host Postgres only (not public internet). +set -euo pipefail +cd ~/games_app + +sudo ufw allow from 172.16.0.0/12 to any port 5432 proto tcp comment 'Docker to Postgres' +sudo ufw allow from 192.168.0.0/16 to any port 5432 proto tcp comment 'Docker bridge alt' +# Also accept on docker bridges by interface (covers hairpin edge cases) +sudo ufw allow in on docker0 to any port 5432 proto tcp comment 'docker0 to PG' || true +sudo ufw status numbered | head -40 + +PGPASS=$(python3 - <<'PY' +import re +from pathlib import Path +m=re.search(r'^POSTGRES_PASSWORD=(.*)$', Path('.env').read_text(), re.M) +print(m.group(1).strip() if m else '') +PY +) +export PGPASSWORD="$PGPASS" + +echo "Docker→PG test:" +sudo docker run --rm --add-host=host.docker.internal:host-gateway \ + -e PGPASSWORD="$PGPASS" postgres:16-alpine \ + psql -h host.docker.internal -U postgres -d games_platform_db -c 'SELECT 1 AS docker_ok;' + +echo "DOCKER_PG_OK" diff --git a/deploy/vps-hardening/backup-ssh-key.ps1 b/deploy/vps-hardening/backup-ssh-key.ps1 new file mode 100644 index 00000000..cd834935 --- /dev/null +++ b/deploy/vps-hardening/backup-ssh-key.ps1 @@ -0,0 +1,83 @@ +# Backup offline de la clé SSH Tloto (Windows). +# N'affiche jamais le contenu de la clé privée. +# Usage: +# powershell -ExecutionPolicy Bypass -File deploy\vps-hardening\backup-ssh-key.ps1 +# # ou avec chemin USB : +# powershell -ExecutionPolicy Bypass -File deploy\vps-hardening\backup-ssh-key.ps1 -Dest E:\TlotoSSH-Backup + +param( + [string]$Dest = "" +) + +$ErrorActionPreference = "Stop" +$sshDir = Join-Path $env:USERPROFILE ".ssh" +$priv = Join-Path $sshDir "id_ed25519" +$pub = Join-Path $sshDir "id_ed25519.pub" + +if (-not (Test-Path $priv)) { throw "Private key not found: $priv" } +if (-not (Test-Path $pub)) { throw "Public key not found: $pub" } + +Write-Host "" +Write-Host "Fingerprint (public):" +ssh-keygen -l -f $pub +Write-Host "" + +if ([string]::IsNullOrWhiteSpace($Dest)) { + Write-Host "Drives available:" + Get-PSDrive -PSProvider FileSystem | + Where-Object { $_.Used -ne $null } | + ForEach-Object { + "{0}: {1} free {2:N1} GB" -f $_.Name, $_.Root, ($_.Free / 1GB) + } + Write-Host "" + Write-Host "Branch un USB, puis indique la lettre (ex: E) ou un chemin complet." + $Dest = Read-Host "Backup destination (ex: E:\TlotoSSH-Backup)" +} + +if ($Dest.Length -eq 1) { + $Dest = "${Dest}:\TlotoSSH-Backup" +} elseif ($Dest -match '^[A-Za-z]:\\?$') { + $Dest = Join-Path $Dest.TrimEnd('\') "TlotoSSH-Backup" +} + +New-Item -ItemType Directory -Force -Path $Dest | Out-Null +$stamp = Get-Date -Format "yyyyMMdd-HHmmss" +$target = Join-Path $Dest "id_ed25519-backup-$stamp" +New-Item -ItemType Directory -Force -Path $target | Out-Null + +Copy-Item -LiteralPath $priv -Destination (Join-Path $target "id_ed25519") -Force +Copy-Item -LiteralPath $pub -Destination (Join-Path $target "id_ed25519.pub") -Force + +@" +Tloto SSH key backup +Created: $(Get-Date -Format o) +PC user: $env:USERNAME +Host fingerprint (pub): +$(ssh-keygen -l -f $pub) + +RESTORE (new PC): +1. mkdir `$env:USERPROFILE\.ssh +2. Copy id_ed25519 + id_ed25519.pub into that folder +3. icacls `$env:USERPROFILE\.ssh\id_ed25519 /inheritance:r /grant:r "$env:USERNAME:(R)" +4. ssh deploy@YOUR_VPS_IP + +SECURITY: +- Keep this USB offline / encrypted (BitLocker To Go recommended) +- Never commit these files to git / cloud sync +- After theft: revoke key on VPS (replace authorized_keys) via hoster console +"@ | Set-Content -Encoding utf8 (Join-Path $target "README.txt") + +# Restrict NTFS ACL on private key copy when on NTFS +try { + $bakPriv = Join-Path $target "id_ed25519" + icacls $bakPriv /inheritance:r | Out-Null + icacls $bakPriv /grant:r "${env:USERNAME}:(R)" | Out-Null +} catch { + Write-Host "Note: could not tighten ACL on backup (non-NTFS USB?). Protect the media." +} + +Write-Host "" +Write-Host "OK — backup written to:" +Write-Host " $target" +Write-Host "Files: id_ed25519, id_ed25519.pub, README.txt" +Write-Host "Store the USB in a safe place. Do not leave it plugged in daily." diff --git a/deploy/vps-hardening/diag-pg-docker2.sh b/deploy/vps-hardening/diag-pg-docker2.sh new file mode 100644 index 00000000..8fa077b8 --- /dev/null +++ b/deploy/vps-hardening/diag-pg-docker2.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail +cd ~/games_app + +echo "== docker0 / bridges ==" +ip -4 addr show | grep -E 'inet |^[0-9]+:' || true + +echo "== host-gateway resolve ==" +sudo docker run --rm --add-host=host.docker.internal:host-gateway alpine \ + getent hosts host.docker.internal || true + +echo "== ufw ==" +sudo ufw status verbose || true + +echo "== iptables 5432 ==" +sudo iptables -L INPUT -n -v | head -40 +sudo iptables -L DOCKER-USER -n -v 2>/dev/null || true +sudo iptables -L FORWARD -n -v | head -20 + +echo "== pg_hba docker lines ==" +sudo grep -E '172\.|192\.168|tloto' /etc/postgresql/*/main/pg_hba.conf || true + +echo "== try connect to docker0 IP if any ==" +DOCKER0=$(ip -4 -o addr show docker0 2>/dev/null | awk '{print $4}' | cut -d/ -f1 || true) +echo "docker0=$DOCKER0" +PGPASS=$(python3 - <<'PY' +import re +from pathlib import Path +m=re.search(r'^POSTGRES_PASSWORD=(.*)$', Path('.env').read_text(), re.M) +print(m.group(1).strip() if m else '') +PY +) +export PGPASSWORD="$PGPASS" +if [[ -n "${DOCKER0:-}" ]]; then + timeout 5 psql -h "$DOCKER0" -U postgres -d games_platform_db -c 'SELECT 1 AS via_docker0;' || echo "via_docker0 FAIL" +fi +timeout 5 psql -h 172.16.0.1 -U postgres -d games_platform_db -c 'SELECT 1 AS via_172_16;' || echo "via_172.16.0.1 FAIL" + +echo "DIAG_DONE" diff --git a/deploy/vps-hardening/fix-pg-docker.sh b/deploy/vps-hardening/fix-pg-docker.sh new file mode 100644 index 00000000..7752b5c5 --- /dev/null +++ b/deploy/vps-hardening/fix-pg-docker.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail +cd ~/games_app +echo "== hosts ==" +getent hosts host.docker.internal || true +ip -4 addr show docker0 2>/dev/null || true +echo "== pg listen ==" +sudo ss -tlnp | grep 5432 || true +PG_CONF=$(ls /etc/postgresql/*/main/postgresql.conf | head -1) +sudo grep -E '^listen_addresses' "$PG_CONF" || sudo grep -E 'listen_addresses' "$PG_CONF" | head -3 +echo "== local auth ==" +PGPASS=$(python3 - <<'PY' +import re +from pathlib import Path +m=re.search(r'^POSTGRES_PASSWORD=(.*)$', Path('.env').read_text(), re.M) +print(m.group(1).strip() if m else '') +PY +) +export PGPASSWORD="$PGPASS" +psql -h 127.0.0.1 -U postgres -d games_platform_db -c 'SELECT 1 AS local_ok;' +echo "== docker via host-gateway ==" +sudo docker run --rm --add-host=host.docker.internal:host-gateway \ + -e PGPASSWORD="$PGPASS" postgres:16-alpine \ + psql -h host.docker.internal -U postgres -d games_platform_db -c 'SELECT 1 AS docker_ok;' diff --git a/deploy/vps-hardening/fix-pg-for-docker.sh b/deploy/vps-hardening/fix-pg-for-docker.sh new file mode 100644 index 00000000..78737def --- /dev/null +++ b/deploy/vps-hardening/fix-pg-for-docker.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Allow Docker containers to reach host Postgres via host.docker.internal. +set -euo pipefail +cd ~/games_app + +PG_CONF=$(ls /etc/postgresql/*/main/postgresql.conf | head -1) +PG_HBA=$(ls /etc/postgresql/*/main/pg_hba.conf | head -1) + +echo "Using $PG_CONF" +if sudo grep -qE '^\s*listen_addresses\s*=' "$PG_CONF"; then + sudo sed -i -E "s/^\s*listen_addresses\s*=.*/listen_addresses = '*'/" "$PG_CONF" +else + echo "listen_addresses = '*'" | sudo tee -a "$PG_CONF" >/dev/null +fi + +if ! sudo grep -q 'tloto-docker-bridge' "$PG_HBA"; then + sudo tee -a "$PG_HBA" >/dev/null <<'HBA' + +# tloto-docker-bridge — Docker → host Postgres (UFW still blocks public :5432) +host all all 172.16.0.0/12 scram-sha-256 +host all all 192.168.0.0/16 scram-sha-256 +HBA +fi + +sudo systemctl restart postgresql +sleep 2 +sudo ss -tlnp | grep 5432 + +PGPASS=$(python3 - <<'PY' +import re +from pathlib import Path +m=re.search(r'^POSTGRES_PASSWORD=(.*)$', Path('.env').read_text(), re.M) +print(m.group(1).strip() if m else '') +PY +) +export PGPASSWORD="$PGPASS" + +echo "Local check:" +psql -h 127.0.0.1 -U postgres -d games_platform_db -c 'SELECT 1 AS local_ok;' + +echo "Docker check:" +sudo docker run --rm --add-host=host.docker.internal:host-gateway \ + -e PGPASSWORD="$PGPASS" postgres:16-alpine \ + psql -h host.docker.internal -U postgres -d games_platform_db -c 'SELECT 1 AS docker_ok;' + +echo "PG_DOCKER_OK" diff --git a/deploy/vps-hardening/harden-vps.sh b/deploy/vps-hardening/harden-vps.sh new file mode 100644 index 00000000..de339479 --- /dev/null +++ b/deploy/vps-hardening/harden-vps.sh @@ -0,0 +1,298 @@ +#!/usr/bin/env bash +# Tloto VPS hardening bootstrap (Phase B host). +# Run as root on a fresh Ubuntu/Debian VPS BEFORE cutting password/root SSH. +# +# Usage: +# export DEPLOY_SSH_PUBKEY='ssh-ed25519 AAAA... comment' +# # optional: SKIP_SSH_LOCK=1 → configure user/firewall/docker but keep password SSH +# # optional: SKIP_DOCKER=1 / SKIP_POSTGRES=1 +# bash harden-vps.sh +# +# Safety: refuses to disable PasswordAuthentication / PermitRootLogin until +# ~deploy/.ssh/authorized_keys contains a valid pubkey. + +set -euo pipefail + +DEPLOY_USER="${DEPLOY_USER:-deploy}" +SSH_DROPIN="/etc/ssh/sshd_config.d/99-tloto.conf" +SYSCTL_DROPIN="/etc/sysctl.d/99-tloto-harden.conf" +MARKER_DIR="/var/lib/tloto-harden" +mkdir -p "$MARKER_DIR" + +log() { printf '\n==> %s\n' "$*"; } +die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; } + +[[ "$(id -u)" -eq 0 ]] || die "Run as root." + +if [[ -r /etc/os-release ]]; then + # shellcheck source=/dev/null + . /etc/os-release + case "${ID:-}" in + ubuntu|debian) ;; + *) die "Unsupported OS (${ID:-unknown}). Use Ubuntu 22.04/24.04 or Debian 12." ;; + esac +else + die "Cannot read /etc/os-release" +fi + +export DEBIAN_FRONTEND=noninteractive + +# --------------------------------------------------------------------------- +# 0) Packages +# --------------------------------------------------------------------------- +log "Installing base packages" +apt-get update -y +apt-get install -y \ + ca-certificates curl gnupg git ufw fail2ban \ + unattended-upgrades apt-listchanges \ + postgresql postgresql-contrib \ + software-properties-common + +# --------------------------------------------------------------------------- +# 1) deploy user + SSH key (MUST succeed before SSH lock) +# --------------------------------------------------------------------------- +log "Ensuring user ${DEPLOY_USER}" +if ! id -u "$DEPLOY_USER" >/dev/null 2>&1; then + adduser --disabled-password --gecos "Tloto deploy" "$DEPLOY_USER" +fi +usermod -aG sudo "$DEPLOY_USER" + +install -d -m 700 -o "$DEPLOY_USER" -g "$DEPLOY_USER" "/home/${DEPLOY_USER}/.ssh" +AUTH_KEYS="/home/${DEPLOY_USER}/.ssh/authorized_keys" +touch "$AUTH_KEYS" +chown "$DEPLOY_USER:$DEPLOY_USER" "$AUTH_KEYS" +chmod 600 "$AUTH_KEYS" + +PUBKEY="${DEPLOY_SSH_PUBKEY:-}" +if [[ -z "$PUBKEY" && -f /root/.ssh/authorized_keys ]]; then + # Prefer first non-comment line from root keys if present + PUBKEY="$(grep -E '^(ssh-(ed25519|rsa)|ecdsa-sha2)' /root/.ssh/authorized_keys | head -n1 || true)" +fi +if [[ -z "$PUBKEY" && -f /root/tloto_deploy.pub ]]; then + PUBKEY="$(tr -d '\r' /dev/null; then + echo "$PUBKEY" >>"$AUTH_KEYS" + log "Installed deploy SSH public key" + else + log "Deploy SSH public key already present" + fi +else + log "WARNING: No DEPLOY_SSH_PUBKEY / root authorized_keys / /root/tloto_deploy.pub" + log "Add a key before SSH lock, e.g.:" + log " echo 'ssh-ed25519 AAAA... you@pc' >> ${AUTH_KEYS}" +fi + +chown "$DEPLOY_USER:$DEPLOY_USER" "$AUTH_KEYS" +chmod 600 "$AUTH_KEYS" +chmod 700 "/home/${DEPLOY_USER}/.ssh" + +# passwordless sudo for deploy (ops convenience on single-admin VPS) +SUDOERS_FILE="/etc/sudoers.d/99-${DEPLOY_USER}-tloto" +cat >"$SUDOERS_FILE" </dev/null +ufw default deny incoming +ufw default allow outgoing +ufw allow OpenSSH +ufw allow 9080/tcp comment 'Tloto HTTP' +ufw allow 9443/tcp comment 'Tloto HTTPS' +# Docker → host Postgres via host.docker.internal (never open 5432 to Anywhere) +ufw allow from 172.16.0.0/12 to any port 5432 proto tcp comment 'Docker to Postgres' +ufw allow in on docker0 to any port 5432 proto tcp comment 'docker0 to PG' || true +# Explicitly never needed publicly (deny is default; document intent): +# 5432 Postgres, 6379 Redis, 4000/4001 app ports +ufw --force enable +ufw status verbose + +# --------------------------------------------------------------------------- +# 3) fail2ban +# --------------------------------------------------------------------------- +log "Configuring fail2ban (sshd)" +cat >/etc/fail2ban/jail.d/sshd-tloto.local <<'EOF' +[sshd] +enabled = true +port = ssh +filter = sshd +backend = systemd +maxretry = 4 +findtime = 10m +bantime = 1h +EOF +systemctl enable --now fail2ban +systemctl restart fail2ban + +# --------------------------------------------------------------------------- +# 4) unattended-upgrades +# --------------------------------------------------------------------------- +log "Enabling unattended security upgrades" +apt-get install -y unattended-upgrades +cat >/etc/apt/apt.conf.d/20auto-upgrades <<'EOF' +APT::Periodic::Update-Package-Lists "1"; +APT::Periodic::Unattended-Upgrade "1"; +APT::Periodic::Download-Upgradeable-Packages "1"; +APT::Periodic::AutocleanInterval "7"; +EOF +# Keep defaults from 50unattended-upgrades (security pocket) +dpkg-reconfigure -f noninteractive unattended-upgrades || true + +# --------------------------------------------------------------------------- +# 5) sysctl harden +# --------------------------------------------------------------------------- +log "Applying sysctl hardening" +cat >"$SYSCTL_DROPIN" <<'EOF' +# Tloto host network hardening +net.ipv4.conf.all.rp_filter = 1 +net.ipv4.conf.default.rp_filter = 1 +net.ipv4.icmp_echo_ignore_broadcasts = 1 +net.ipv4.conf.all.accept_source_route = 0 +net.ipv4.conf.default.accept_source_route = 0 +net.ipv4.conf.all.accept_redirects = 0 +net.ipv4.conf.default.accept_redirects = 0 +net.ipv4.conf.all.send_redirects = 0 +net.ipv4.conf.default.send_redirects = 0 +net.ipv4.tcp_syncookies = 1 +net.ipv6.conf.all.accept_redirects = 0 +net.ipv6.conf.default.accept_redirects = 0 +EOF +sysctl --system >/dev/null + +# --------------------------------------------------------------------------- +# 6) Docker +# --------------------------------------------------------------------------- +if [[ "${SKIP_DOCKER:-0}" != "1" ]]; then + log "Installing Docker Engine + Compose plugin" + if ! command -v docker >/dev/null 2>&1; then + curl -fsSL https://get.docker.com | sh + fi + usermod -aG docker "$DEPLOY_USER" + systemctl enable --now docker + docker --version + docker compose version || true +else + log "SKIP_DOCKER=1 — skipping Docker install" +fi + +# --------------------------------------------------------------------------- +# 7) PostgreSQL localhost-only +# --------------------------------------------------------------------------- +if [[ "${SKIP_POSTGRES:-0}" != "1" ]]; then + log "Hardening PostgreSQL (listen localhost only)" + systemctl enable --now postgresql + + PG_CONF="$(ls /etc/postgresql/*/main/postgresql.conf 2>/dev/null | head -n1 || true)" + PG_HBA="$(ls /etc/postgresql/*/main/pg_hba.conf 2>/dev/null | head -n1 || true)" + [[ -n "$PG_CONF" && -n "$PG_HBA" ]] || die "PostgreSQL config not found" + + if grep -qE '^\s*listen_addresses\s*=' "$PG_CONF"; then + sed -i -E "s/^\s*listen_addresses\s*=.*/listen_addresses = 'localhost'/" "$PG_CONF" + else + echo "listen_addresses = 'localhost'" >>"$PG_CONF" + fi + + # Prefer scram for local/md5 connections where password auth is used + if ! grep -q 'scram-sha-256' "$PG_HBA"; then + sed -i -E 's/^(local\s+all\s+all\s+)peer/\1peer/' "$PG_HBA" || true + # Do not rewrite entire hba; ensure no 0.0.0.0 host lines without comment + fi + + systemctl restart postgresql + # Verify not listening publicly (best-effort) + if command -v ss >/dev/null 2>&1; then + if ss -tlnp | grep -E ':5432\b' | grep -v '127.0.0.1' | grep -vq '::1'; then + log "WARNING: Postgres may be listening on a non-loopback address — check ss -tlnp | grep 5432" + else + log "Postgres appears bound to localhost only" + fi + fi +else + log "SKIP_POSTGRES=1 — skipping Postgres harden" +fi + +# --------------------------------------------------------------------------- +# 8) SSH lock (gated) +# --------------------------------------------------------------------------- +write_sshd_dropin() { + local lock="$1" # 0 = keys preferred but password still on; 1 = full lock + if [[ "$lock" == "1" ]]; then + cat >"$SSH_DROPIN" <"$SSH_DROPIN" </dev/null 2>&1; then + sshd -t || die "sshd config invalid" + fi + systemctl reload ssh 2>/dev/null || systemctl reload sshd 2>/dev/null || systemctl reload ssh.service +} + +if [[ "${SKIP_SSH_LOCK:-0}" == "1" ]]; then + log "SKIP_SSH_LOCK=1 — writing soft SSH drop-in (passwords still allowed)" + write_sshd_dropin 0 + echo soft >"$MARKER_DIR/ssh_mode" +elif has_deploy_key; then + log "Deploy key present — applying FULL SSH lock (root/password disabled)" + log "IMPORTANT: Keep this root session open. In a NEW terminal verify:" + log " ssh ${DEPLOY_USER}@" + write_sshd_dropin 1 + echo locked >"$MARKER_DIR/ssh_mode" +else + log "NO deploy key — refusing full SSH lock (would lock you out)" + write_sshd_dropin 0 + echo soft >"$MARKER_DIR/ssh_mode" + log "Next:" + log " 1) From your PC: ssh-copy-id -i ~/.ssh/id_ed25519.pub ${DEPLOY_USER}@" + log " or: export DEPLOY_SSH_PUBKEY='...' && re-run this script" + log " 2) Test: ssh ${DEPLOY_USER}@" + log " 3) Re-run: bash harden-vps.sh # will then lock SSH" +fi + +# --------------------------------------------------------------------------- +# Summary +# --------------------------------------------------------------------------- +log "Hardening complete (summary)" +echo "User: ${DEPLOY_USER}" +echo "SSH mode: $(cat "$MARKER_DIR/ssh_mode" 2>/dev/null || echo unknown)" +echo "UFW: active (22, 9080, 9443)" +echo "fail2ban: sshd jail" +echo "Docker: $(command -v docker >/dev/null && docker --version | head -1 || echo skipped/missing)" +echo "Postgres: localhost listen (unless SKIP_POSTGRES)" +echo +echo "Pre-deploy checklist: deploy/vps-hardening/PREDEPLOY-CHECKLIST.md" +echo "Do NOT publish 5432/6379/4000/4001 on the host firewall." +echo "Log out of root SSH only after deploy-key login works." diff --git a/deploy/vps-hardening/remote-bootstrap-env-db.sh b/deploy/vps-hardening/remote-bootstrap-env-db.sh new file mode 100644 index 00000000..fb3e2ae6 --- /dev/null +++ b/deploy/vps-hardening/remote-bootstrap-env-db.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +# Create fresh .env + Postgres DB for Tloto on new VPS (repo already synced). +set -euo pipefail +cd "${HOME}/games_app" + +log() { printf '\n==> %s\n' "$*"; } + +command -v python3 >/dev/null || sudo apt-get install -y python3 +command -v openssl >/dev/null + +if [[ -f .env ]]; then + log "Removing previous incomplete .env for clean regenerate" + rm -f .env +fi + +log "Generating BIP39 mnemonic inside Docker" +MNEMO="$(sudo docker run --rm -w /tmp node:20-alpine sh -c \ + 'npm init -y >/dev/null 2>&1 && npm install bip39@3.1.0 >/dev/null 2>&1 && node -e "process.stdout.write(require(\"bip39\").generateMnemonic(256))"')" +WORD_COUNT="$(echo "$MNEMO" | wc -w | tr -d ' ')" +[[ "$WORD_COUNT" == "24" ]] || { echo "Mnemonic word count=$WORD_COUNT expected 24"; exit 1; } + +ENC="$(openssl rand -hex 32)" +JWT="$(openssl rand -base64 48 | tr -d '\n=/+' | head -c 48)" +REDIS="$(openssl rand -hex 32)" +SETUP="$(openssl rand -hex 24)" +BREAK="$(openssl rand -hex 32)" +PGPASS="$(openssl rand -hex 24)" + +cp .env.example .env +chmod 600 .env + +export ENC JWT REDIS SETUP BREAK PGPASS MNEMO +python3 - <<'PY' +import os, re, pathlib +path = pathlib.Path(".env") +text = path.read_text(encoding="utf-8") + +def set_kv(text, key, value): + line = f"{key}={value}" + pat = re.compile(rf"^{re.escape(key)}=.*$", re.M) + if pat.search(text): + return pat.sub(lambda m: line, text) + return text.rstrip() + "\n" + line + "\n" + +pairs = { + "POSTGRES_USER": "postgres", + "POSTGRES_PASSWORD": os.environ["PGPASS"], + "POSTGRES_DB": "games_platform_db", + "DATABASE_PASSWORD": os.environ["PGPASS"], + "DATABASE_URL": f"postgresql://postgres:{os.environ['PGPASS']}@host.docker.internal:5432/games_platform_db", + "REDIS_PASSWORD": os.environ["REDIS"], + "JWT_SECRET": os.environ["JWT"], + "ENCRYPTION_KEY": os.environ["ENC"], + "PLATFORM_MNEMONIC": os.environ["MNEMO"], + "INITIAL_SETUP_TOKEN": os.environ["SETUP"], + "BREAK_GLASS_TOKEN": os.environ["BREAK"], + "APP_PUBLIC_URL": "http://191.215.41.53:9080", + "CORS_ORIGINS": "http://191.215.41.53:9080", + "VITE_API_BASE_URL": "http://191.215.41.53:9080", + "VITE_WS_ENABLED": "true", + "VITE_WS_URL": "ws://191.215.41.53:9080/ws/v1/games/candle-predict", + "TRON_NODE_URL": "https://api.trongrid.io", + "TRON_CONFIRMATIONS": "20", + "BSC_RPC_URL": "https://bsc-dataseed.binance.org", + "BSC_CONFIRMATIONS": "15", + "ALLOW_WITHDRAWALS": "false", + "SWEEP_ENABLED": "false", + "RUN_MIGRATE_ON_START": "0", + "CERTBOT_DOMAIN1": "tloto.net", + "CERTBOT_DOMAIN2": "www.tloto.net", +} +for k, v in pairs.items(): + text = set_kv(text, k, v) +path.write_text(text, encoding="utf-8") +print("Wrote .env") +PY + +grep '^INITIAL_SETUP_TOKEN=' .env | tee "${HOME}/tloto-initial-setup-token.txt" >/dev/null +chmod 600 "${HOME}/tloto-initial-setup-token.txt" +echo "SETUP_TOKEN_SAVED=~/tloto-initial-setup-token.txt" + +log "Postgres password + database" +# Use file-based psql to avoid shell escaping issues +umask 077 +PASSFILE="$(mktemp)" +printf '%s\n' "$PGPASS" >"$PASSFILE" +sudo -u postgres psql -v ON_ERROR_STOP=1 -c "ALTER USER postgres PASSWORD '$(cat "$PASSFILE")';" +rm -f "$PASSFILE" + +if ! sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='games_platform_db'" | grep -q 1; then + sudo -u postgres createdb -O postgres games_platform_db + log "Created games_platform_db" +else + log "games_platform_db already exists" +fi + +PG_HBA="$(ls /etc/postgresql/*/main/pg_hba.conf | head -n1)" +if [[ -n "$PG_HBA" ]] && ! sudo grep -q 'tloto-docker-local' "$PG_HBA"; then + sudo tee -a "$PG_HBA" >/dev/null <<'HBA' + +# tloto-docker-local +host all all 127.0.0.1/32 scram-sha-256 +host all all ::1/128 scram-sha-256 +HBA + sudo systemctl reload postgresql + log "pg_hba.conf updated for localhost scram" +fi + +log "Env + DB ready" +echo "Setup URL: http://191.215.41.53:9080/setup" +echo "Token: $(cat "${HOME}/tloto-initial-setup-token.txt")" diff --git a/deploy/vps-hardening/remote-bootstrap-phase-a.sh b/deploy/vps-hardening/remote-bootstrap-phase-a.sh new file mode 100644 index 00000000..f5263441 --- /dev/null +++ b/deploy/vps-hardening/remote-bootstrap-phase-a.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# Phase A bootstrap on new VPS — run as deploy with sudo. +set -euo pipefail + +APP_DIR="${HOME}/games_app" +REPO_URL="${REPO_URL:-https://github.com/japhni/games-project.git}" +BRANCH="${BRANCH:-master}" + +log() { printf '\n==> %s\n' "$*"; } + +log "PostgreSQL status" +sudo systemctl enable --now postgresql +sudo systemctl is-active postgresql +sudo ss -tlnp | grep 5432 || true + +log "Clone or update repo" +if [[ ! -d "$APP_DIR/.git" ]]; then + git clone --branch "$BRANCH" "$REPO_URL" "$APP_DIR" +else + git -C "$APP_DIR" fetch origin + git -C "$APP_DIR" checkout "$BRANCH" + git -C "$APP_DIR" pull --ff-only origin "$BRANCH" || true +fi +cd "$APP_DIR" + +if [[ ! -f .env ]]; then + log "Creating .env with fresh secrets" + cp .env.example .env + chmod 600 .env + + ENC="$(openssl rand -hex 32)" + JWT="$(openssl rand -base64 48 | tr -d '\n=/+' | head -c 48)" + REDIS="$(openssl rand -hex 32)" + SETUP="$(openssl rand -hex 24)" + BREAK="$(openssl rand -hex 32)" + PGPASS="$(openssl rand -hex 24)" + + # BIP39 24 words via Node in Docker (no host Node required) + MNEMO="$(sudo docker run --rm node:20-alpine node -e " +const crypto=require('crypto'); +const words=require('fs').readFileSync(0,'utf8').trim().split(/\s+/); +" 2>/dev/null || true)" + + # Generate mnemonic with bip39 from docker + npm package + MNEMO="$(sudo docker run --rm node:20-alpine sh -c 'npm install -g bip39@3 >/dev/null 2>&1 && node -e "const b=require(\"bip39\"); process.stdout.write(b.generateMnemonic(256));"')" + + # Escape for sed replacements — use Python for safe .env patching + export ENC JWT REDIS SETUP BREAK PGPASS MNEMO + python3 - <<'PY' +import os, re, pathlib +path = pathlib.Path(".env") +text = path.read_text(encoding="utf-8") + +def set_kv(text, key, value): + line = f"{key}={value}" + pat = re.compile(rf"^{re.escape(key)}=.*$", re.M) + if pat.search(text): + return pat.sub(line, text) + return text.rstrip() + "\n" + line + "\n" + +pairs = { + "POSTGRES_USER": "postgres", + "POSTGRES_PASSWORD": os.environ["PGPASS"], + "POSTGRES_DB": "games_platform_db", + "DATABASE_PASSWORD": os.environ["PGPASS"], + "DATABASE_URL": f"postgresql://postgres:{os.environ['PGPASS']}@host.docker.internal:5432/games_platform_db", + "REDIS_PASSWORD": os.environ["REDIS"], + "JWT_SECRET": os.environ["JWT"], + "ENCRYPTION_KEY": os.environ["ENC"], + "PLATFORM_MNEMONIC": os.environ["MNEMO"], + "INITIAL_SETUP_TOKEN": os.environ["SETUP"], + "BREAK_GLASS_TOKEN": os.environ["BREAK"], + "APP_PUBLIC_URL": "http://191.215.41.53:9080", + "CORS_ORIGINS": "http://191.215.41.53:9080", + "VITE_API_BASE_URL": "http://191.215.41.53:9080", + "VITE_WS_ENABLED": "true", + "VITE_WS_URL": "ws://191.215.41.53:9080/ws/v1/games/candle-predict", + "TRON_NODE_URL": "https://api.trongrid.io", + "TRON_CONFIRMATIONS": "20", + "BSC_RPC_URL": "https://bsc-dataseed.binance.org", + "BSC_CONFIRMATIONS": "15", + "ALLOW_WITHDRAWALS": "false", + "SWEEP_ENABLED": "false", + "RUN_MIGRATE_ON_START": "0", + "CERTBOT_DOMAIN1": "tloto.net", + "CERTBOT_DOMAIN2": "www.tloto.net", +} +for k, v in pairs.items(): + text = set_kv(text, k, v) +path.write_text(text, encoding="utf-8") +print("Wrote .env (secrets not printed)") +PY +else + log ".env already exists — leaving it unchanged" +fi + +# Load password for DB bootstrap without printing +PGPASS="$(python3 - <<'PY' +import re, pathlib +m=re.search(r'^POSTGRES_PASSWORD=(.*)$', pathlib.Path('.env').read_text(), re.M) +print(m.group(1).strip() if m else '') +PY +)" + +log "Configure Postgres role + database" +sudo -u postgres psql -v ON_ERROR_STOP=1 </dev/null <<'HBA' + +# tloto-docker-local +host all all 127.0.0.1/32 scram-sha-256 +host all all ::1/128 scram-sha-256 +HBA + sudo systemctl reload postgresql +fi + +log "Phase A done" +echo "APP_DIR=$APP_DIR" +echo "NEXT: sudo docker compose run --rm --no-deps --build backend node dist/db/migrate.js" +grep -E '^(INITIAL_SETUP_TOKEN|APP_PUBLIC_URL)=' .env diff --git a/deploy/vps-hardening/remote-migrate-and-up.sh b/deploy/vps-hardening/remote-migrate-and-up.sh new file mode 100644 index 00000000..d9e545f0 --- /dev/null +++ b/deploy/vps-hardening/remote-migrate-and-up.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail +cd ~/games_app + +echo "== migrate ==" +sudo docker compose run --rm --no-deps --build backend node dist/db/migrate.js +echo "MIGRATE_OK" + +echo "== compose up (http + clamav) ==" +sudo docker compose --profile http --profile clamav up -d --build +echo "COMPOSE_UP_OK" + +echo "== ps ==" +sudo docker compose ps + +echo "== smoke health (wait) ==" +for i in $(seq 1 30); do + if curl -fsS -o /dev/null -w "%{http_code}" http://127.0.0.1:9080/api/health 2>/dev/null | grep -qE '200|404|401'; then + echo "HTTP_REACHABLE" + curl -fsS http://127.0.0.1:9080/api/health || curl -fsS http://127.0.0.1:9080/health || true + break + fi + sleep 3 +done +sudo docker compose logs --tail=40 backend || true +echo "STACK_DONE" diff --git a/deploy/vps-hardening/remote-reset-db-migrate-up.sh b/deploy/vps-hardening/remote-reset-db-migrate-up.sh new file mode 100644 index 00000000..01758a19 --- /dev/null +++ b/deploy/vps-hardening/remote-reset-db-migrate-up.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail +cd ~/games_app + +echo "== reset DB (fresh install) ==" +sudo -u postgres psql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'games_platform_db' AND pid <> pg_backend_pid();" || true +sudo -u postgres psql -c "DROP DATABASE IF EXISTS games_platform_db;" +sudo -u postgres psql -c "CREATE DATABASE games_platform_db OWNER postgres;" + +echo "== migrate ==" +sudo docker compose run --rm --no-deps --build backend node dist/db/migrate.js +echo "MIGRATE_OK" + +echo "== compose up ==" +sudo docker compose --profile http --profile clamav up -d --build +echo "COMPOSE_UP_OK" + +sleep 8 +echo "== ps ==" +sudo docker compose ps + +echo "== smoke ==" +for i in $(seq 1 40); do + code=$(curl -s -o /tmp/tloto_health.txt -w "%{http_code}" http://127.0.0.1:9080/health || echo 000) + if [[ "$code" == "200" ]]; then + echo "HEALTH_OK $code" + cat /tmp/tloto_health.txt + echo + break + fi + echo "wait health ($i) code=$code" + sleep 3 +done + +curl -fsS http://127.0.0.1:9080/api/v1/setup/status || true +echo +sudo docker compose logs --tail=30 backend || true +echo "STACK_DONE" diff --git a/deploy/vps-hardening/tighten-pg-listen.sh b/deploy/vps-hardening/tighten-pg-listen.sh new file mode 100644 index 00000000..36715476 --- /dev/null +++ b/deploy/vps-hardening/tighten-pg-listen.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Listen only on loopback + docker0 (not all interfaces). +set -euo pipefail +PG_CONF=$(ls /etc/postgresql/*/main/postgresql.conf | head -1) +DOCKER0=$(ip -4 -o addr show docker0 2>/dev/null | awk '{print $4}' | cut -d/ -f1 || echo '172.16.0.1') +LISTEN="listen_addresses = '127.0.0.1,${DOCKER0}'" +if sudo grep -qE '^\s*listen_addresses\s*=' "$PG_CONF"; then + sudo sed -i -E "s/^\s*listen_addresses\s*=.*/${LISTEN}/" "$PG_CONF" +else + echo "$LISTEN" | sudo tee -a "$PG_CONF" >/dev/null +fi +sudo systemctl restart postgresql +sleep 1 +sudo ss -tlnp | grep 5432 +# re-test docker connectivity +cd ~/games_app +PGPASS=$(python3 - <<'PY' +import re +from pathlib import Path +m=re.search(r'^POSTGRES_PASSWORD=(.*)$', Path('.env').read_text(), re.M) +print(m.group(1).strip() if m else '') +PY +) +export PGPASSWORD="$PGPASS" +sudo docker run --rm --add-host=host.docker.internal:host-gateway \ + -e PGPASSWORD="$PGPASS" postgres:16-alpine \ + psql -h host.docker.internal -U postgres -d games_platform_db -c 'SELECT 1 AS ok;' +echo "LISTEN_TIGHT_OK" diff --git a/deploy/vps-hardening/verify-harden.sh b/deploy/vps-hardening/verify-harden.sh new file mode 100644 index 00000000..64378c9e --- /dev/null +++ b/deploy/vps-hardening/verify-harden.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Post-harden verification (run as deploy or root on the VPS). +set -euo pipefail + +ok=0 +fail=0 + +ufw_status() { + if [[ "$(id -u)" -eq 0 ]]; then + ufw status + elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then + sudo -n ufw status + else + ufw status + fi +} + +_ufw_active() { ufw_status 2>/dev/null | grep -qi 'Status: active'; } +_ufw_9080() { ufw_status 2>/dev/null | grep -q 9080; } +_ufw_9443() { ufw_status 2>/dev/null | grep -q 9443; } +_pg_localhost() { + # Allow loopback + Docker bridge IPs; fail if listening on a public address + ! ss -tlnp | grep -E ':5432\b' | grep -vE '127\.0\.0\.1|\[::1\]|172\.(1[6-9]|2[0-9]|3[0-1])\.' | grep -q . +} +_ufw_docker_pg() { ufw_status 2>/dev/null | grep -qE '5432.*172\.16'; } +_redis_closed() { ! ss -tlnp | grep -qE ':6379\b'; } + +check() { + local name="$1" + shift + if "$@"; then + printf '[OK] %s\n' "$name" + ok=$((ok + 1)) + else + printf '[FAIL] %s\n' "$name" + fail=$((fail + 1)) + fi +} + +echo "Tloto VPS harden verification" +echo "Host: $(hostname) User: $(id -un)" +echo + +check "ufw active" _ufw_active +check "ufw allows 9080" _ufw_9080 +check "ufw allows 9443" _ufw_9443 +check "ufw docker→5432" _ufw_docker_pg +check "fail2ban running" systemctl is-active --quiet fail2ban +check "docker available" command -v docker +check "sshd drop-in exists" test -f /etc/ssh/sshd_config.d/99-tloto.conf +check "sysctl drop-in exists" test -f /etc/sysctl.d/99-tloto-harden.conf + +if [[ -f /etc/ssh/sshd_config.d/99-tloto.conf ]]; then + check "PasswordAuthentication no" grep -Eq '^PasswordAuthentication no' /etc/ssh/sshd_config.d/99-tloto.conf + check "PermitRootLogin no" grep -Eq '^PermitRootLogin no' /etc/ssh/sshd_config.d/99-tloto.conf +fi + +if command -v ss >/dev/null 2>&1; then + check "postgres not on public iface" _pg_localhost + check "redis not published on host" _redis_closed +fi + +echo +echo "Passed: $ok Failed: $fail" +[[ "$fail" -eq 0 ]] diff --git a/docker-compose.yml b/docker-compose.yml index c5b593c5..11e78a82 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,8 @@ # VPS dédié (80/443 standard) : # npm run ssl:init && npm run phase-b:up:ssl x-backend-common: &backend-common + # Tagged images for CI/CD rollback (default :local keeps current npm phase-b:* behaviour) + image: ${TLOTO_REGISTRY:-127.0.0.1:5000}/tloto-backend:${TLOTO_IMAGE_TAG:-local} build: context: ./backend dockerfile: Dockerfile @@ -317,6 +319,7 @@ services: start_period: 20s prediqo-web: + image: ${TLOTO_REGISTRY:-127.0.0.1:5000}/tloto-web:${TLOTO_IMAGE_TAG:-local} build: context: ./prediqo_web dockerfile: Dockerfile diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index 7c16b049..43f1f94d 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -20,6 +20,12 @@ Ce guide décrit comment lancer Tloto sur un serveur Linux (VPS) **sans perturbe Si Node n’est pas installé, vous pouvez utiliser directement `docker compose` à la place des scripts `npm run`. +### Durcissement hôte (recommandé avant le 1er deploy) + +Sur un VPS neuf (SSH root → user `deploy`, UFW, fail2ban, Docker, Postgres localhost-only) : voir **[deploy/vps-hardening/README.md](../deploy/vps-hardening/README.md)** et la checklist **[PREDEPLOY-CHECKLIST.md](../deploy/vps-hardening/PREDEPLOY-CHECKLIST.md)**. + +**Migration vers un nouveau VPS (fresh install, DB de test)** : **[deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md](../deploy/vps-hardening/MIGRATE-TO-NEW-VPS.md)**. + ### Ouvrir les ports Prediqo (pare-feu) ```bash @@ -28,6 +34,8 @@ sudo ufw allow 9443/tcp # HTTPS sudo ufw reload ``` +> Si tu as déjà exécuté `harden-vps.sh`, UFW ouvre déjà `22` + `9080` + `9443` — inutile de tout refaire. + ### DNS Le domaine **`prediqo.redirectme.net`** doit pointer vers l’IP du VPS (enregistrement **A**). @@ -393,18 +401,25 @@ Si `psql` fonctionne sur l’hôte mais le backend Docker redémarre en boucle ( host all all 172.16.0.0/12 scram-sha-256 ``` -Dans `postgresql.conf`, vérifiez : +Dans `postgresql.conf`, écoutez loopback + passerelle Docker (pas `*` en prod) : ``` -listen_addresses = 'localhost' +listen_addresses = '127.0.0.1,172.16.0.1' ``` -(suffit en général avec `host.docker.internal` + port forwarding Docker) +(`172.16.0.1` = IP de `docker0` sur ce VPS ; adaptez avec `ip -4 addr show docker0`.) + +**UFW** (souvent la cause d’un *connection timeout* depuis les conteneurs) : autoriser Docker → Postgres, sans ouvrir 5432 au public : + +```bash +sudo ufw allow from 172.16.0.0/12 to any port 5432 proto tcp comment 'Docker to Postgres' +sudo ufw allow in on docker0 to any port 5432 proto tcp comment 'docker0 to PG' +``` Puis : ```bash -sudo systemctl reload postgresql +sudo systemctl restart postgresql ``` **Test depuis un conteneur :** diff --git a/docs/GITEA-CICD.md b/docs/GITEA-CICD.md new file mode 100644 index 00000000..cdba7450 --- /dev/null +++ b/docs/GITEA-CICD.md @@ -0,0 +1,69 @@ +# Gitea + CI/CD + `tloto-deploy` (nouveau VPS) + +## URLs + +| Service | URL | +|---------|-----| +| Gitea (temporaire IP) | http://191.215.41.53:3000/ | +| Gitea (après DNS) | https://git.tloto.net/ | +| Registry local | `127.0.0.1:5000` (non public) | +| Tloto HTTP smoke | http://191.215.41.53:9080/ | + +Credentials admin Gitea : `~/gitea-admin-credentials.txt` sur le VPS. + +## Architecture + +- **Gitea** : dépôt central + Actions. +- **act_runner** : CI (build/tests/images) — ne déploie pas la prod directement. +- **`tloto-deploy`** : seul mécanisme prod (manuel SSH ou workflow `Deploy` via clé SSH restreinte). +- **Commandes historiques** inchangées : `sudo npm run db:migrate`, `sudo npm run phase-b:up:https`. + +## Déploiement manuel (SSH) + +```bash +ssh deploy@191.215.41.53 +tloto-deploy --ref main --mode http +# après cutover HTTPS : +tloto-deploy --ref --mode https +tloto-deploy --rollback +``` + +## Déploiement manuel (Gitea UI) + +1. Repo → Actions → workflow **Deploy** → Run workflow. +2. Renseigner `ref` (SHA/branche) et `mode`. +3. Secrets requis : `DEPLOY_SSH_KEY` (privé `~/gitea-deploy-ssh/id_ed25519`), `DEPLOY_SSH_HOST` (ex. `172.16.0.1`). + +## CI (automatique) + +Push/PR sur `main` / `master` / `develop` → workflow **CI** : + +1. `npm ci` + compile backend +2. Build images Docker +3. Push vers registry local `127.0.0.1:5000/tloto-*:` +4. **Pas** de mise en prod + +## pgAdmin (Windows) + +Voir `~/pgadmin-db-credentials.txt` sur le VPS. Tunnel SSH uniquement — jamais exposer 5432. + +```powershell +ssh -N -L 5433:127.0.0.1:5432 deploy@191.215.41.53 +``` + +## Rollback + +- Application : `tloto-deploy --rollback` (réactive le `prev_sha`). +- PostgreSQL : **pas** de rollback automatique ; dumps dans `/var/lib/tloto/backups/` avant migrate si `schema.sql` a changé. + +## Edge HTTPS `git.tloto.net` + +Quand le DNS A de `git.tloto.net` pointe vers le VPS : + +```bash +cd ~/edge +# placer fullchain.pem + privkey.pem dans certs/ puis décommenter le bloc 443 dans nginx.conf +sudo docker compose --profile edge up -d +# Mettre à jour ~/gitea/.env : GITEA_ROOT_URL=https://git.tloto.net/ +sudo docker compose -f ~/gitea/docker-compose.yml up -d gitea +``` diff --git a/package.json b/package.json index 8558b36f..29753207 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,8 @@ "ssl:dns-renew": "docker compose --profile dns-renew run --rm -it certbot-dns-renew", "db:migrate": "docker compose run --rm --no-deps --build backend node dist/db/migrate.js", "migrate": "npm run db:migrate", + "tloto:deploy": "bash deploy/release/tloto-deploy.sh", + "tloto:deploy:rollback": "bash deploy/release/tloto-deploy.sh --rollback", "phase-b:grant-super-admin": "docker compose run --rm --no-deps --build backend node dist/scripts/grantSuperAdminToAdmins.js", "phase-b:verify-smtp": "docker compose run --rm --no-deps --build backend node dist/scripts/verifySmtp.js", "phase-b:break-glass-reset-2fa": "docker compose run --rm --no-deps --build backend node dist/scripts/breakGlassResetAdmin2fa.js",