From 33b32cae4aec5f977afcb3d9386d4c00e662e784 Mon Sep 17 00:00:00 2001 From: Oier Bravo Urtasun Date: Thu, 23 Apr 2026 23:49:10 +0200 Subject: [PATCH] deploy(prod): swap host Caddy for NetBird-Traefik labels + external Keycloak MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ambrosio's TLS is now handled by the Traefik that NetBird's self-hosted installer deploys. kong + app attach to that Traefik network and expose themselves via Docker-provider labels (erosi-kong priority 100 for Supabase API paths, erosi-app priority 1 for everything else on erosi.limonia.net). No container publishes host ports; host Caddy is out of the deploy path permanently. Keycloak is no longer bundled — PUBLIC_KEYCLOAK_URL points at an external IdP. The deploy script writes .env with FILL_IN_* placeholders for PUBLIC_KEYCLOAK_URL, KEYCLOAK_CLIENT_SECRET, and TRAEFIK_NETWORK, and fails fast until they are filled. New domain: erosi.limonia.net. realm-export.erosi.json is retained as reference for the external Keycloak operator; it is no longer imported by this stack. Co-Authored-By: Claude Opus 4.7 (1M context) --- .env.erosi.example | 30 ++++++----- CLAUDE.md | 18 ++++--- docs/deployment.md | 30 ++++++----- infra/caddy/erosi.Caddyfile | 46 ---------------- infra/docker-compose.erosi.yml | 77 +++++++++++--------------- infra/scripts/deploy-erosi.sh | 93 +++++++++++++------------------- keycloak/realm-export.erosi.json | 6 +-- 7 files changed, 117 insertions(+), 183 deletions(-) delete mode 100644 infra/caddy/erosi.Caddyfile diff --git a/.env.erosi.example b/.env.erosi.example index f5e21ab..92e9700 100644 --- a/.env.erosi.example +++ b/.env.erosi.example @@ -1,15 +1,27 @@ # Production env for ambrosio — copy to .env on the server and fill in secrets. # Generate JWT triplet: bash infra/scripts/rotate-jwt.sh -# ── Domains (change if you migrate to new hostnames) ──────────────────────── -PUBLIC_APP_URL=https://erosi.oier.ovh -PUBLIC_SUPABASE_URL=https://erosi.oier.ovh -PUBLIC_KEYCLOAK_URL=https://auth.oier.ovh +# ── App + Supabase API (single domain, routed by Traefik on ambrosio) ────── +PUBLIC_APP_URL=https://erosi.limonia.net +PUBLIC_SUPABASE_URL=https://erosi.limonia.net + +# ── External Keycloak ────────────────────────────────────────────────────── +# The client must be confidential, with `openid` as a default client scope +# (GoTrue v2.158.1 doesn't send `openid` in the OAuth scope param — Keycloak +# must inject it), redirectUris including https://erosi.limonia.net/* and +# https://erosi.limonia.net/auth/v1/callback, and webOrigins https://erosi.limonia.net. +PUBLIC_KEYCLOAK_URL=https://your-keycloak.example.com PUBLIC_KEYCLOAK_REALM=colectivo PUBLIC_KEYCLOAK_CLIENT_ID=colectivo-web +KEYCLOAK_CLIENT_SECRET=CHANGEME-paste-from-external-keycloak -# Keycloak sees this as its canonical hostname (KC_HOSTNAME). -KEYCLOAK_HOSTNAME=auth.oier.ovh +# ── Traefik (deployed by NetBird's self-hosted installer on ambrosio) ────── +# Copy these three values from what you answered during the NetBird install. +# The Docker network name is mandatory (Traefik auto-discovers our kong+app +# via labels only when we join the same network). +TRAEFIK_NETWORK=netbird +TRAEFIK_ENTRYPOINT=websecure +TRAEFIK_CERTRESOLVER=letsencrypt # ── Postgres (single password for all internal roles) ─────────────────────── POSTGRES_PASSWORD=CHANGEME-strong-random-password @@ -20,12 +32,6 @@ SUPABASE_JWT_SECRET=CHANGEME-openssl-rand-base64-48 PUBLIC_SUPABASE_ANON_KEY=CHANGEME-sign-with-above SUPABASE_SERVICE_ROLE_KEY=CHANGEME-sign-with-above -# ── Keycloak admin + client secret ────────────────────────────────────────── -KEYCLOAK_ADMIN=admin -KEYCLOAK_ADMIN_PASSWORD=CHANGEME-strong-random-password -# Must match the `secret` field of the colectivo-web client in realm-export.erosi.json. -KEYCLOAK_CLIENT_SECRET=CHANGEME-client-secret-32-chars - # ── Realtime encryption ───────────────────────────────────────────────────── # DB_ENC_KEY: exactly 16 characters. SECRET_KEY_BASE: ≥ 64 characters. REALTIME_ENC_KEY=CHANGEME16charkey diff --git a/CLAUDE.md b/CLAUDE.md index 9038315..aa4b127 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,13 +4,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Status -**Fase 0–5 complete. Fase 6 complete (deploy readiness: PWA injectManifest SW + manifest + iOS meta tags + placeholder icons + Kong rate-limit on invitations + dev JWT rotation + prod env template + rls-audit.sh + Justfile lighthouse/rls-audit/test-rate-limit). Production stack deployed to ambrosio (OVH VPS) at https://erosi.oier.ovh (app + Supabase) + https://auth.oier.ovh (Keycloak); Let's Encrypt certs via host Caddy; PWA strategy switched to generateSW to unblock the prod build (see the "injectManifest hardcoded filename" gotcha below). Fase 7 complete: 12 new Playwright tests fill the collective-flow UI gap (O-01..O-03 onboarding, I-01..I-05 invitation acceptance, MC-02..MC-05 admin-manage) — writing them surfaced + fixed three latent bugs in the product code (atomic `create_collective()` RPC, pendingInvitationToken restore after login, manage page not reloading on late $currentCollective hydration). Plus migration 013 (auth.users role/aud default trigger) — found after the first real self-registration on prod via Keycloak→GoTrue left the user with empty `role`/`aud` columns, breaking every REST call with `role "" does not exist`. Post-fase-7 prod auth hardening (2026-04-20..21, see `docs/history/fase-8-auth-logout.md`): migration 014 extends the role/aud guard to UPDATE (GoTrue's pop-ORM resends role='' right after the INSERT and clobbered the INSERT trigger's backfill); `logout()` now does RP-initiated Keycloak end-session + lands on a new public `/logged-out` route, which both actually ends the Keycloak SSO cookie (so the next login re-prompts) and closes a PKCE-verifier race that produced "PKCE code verifier not found in storage" on prod. 259 tests green: 45 pgTAP + 140 Vitest integration + 15 Vitest unit + 59 Playwright + 1 Vitest rate-limit (gated, run via `just test-rate-limit`). 3 skipped in `just test-all` (2 Realtime presence — upstream `handle_out/3` bug; 1 rate-limit — gated). Push notifications + CI Docker + final production icons deliberately out of scope. ✅** +**Fase 0–5 complete. Fase 6 complete (deploy readiness: PWA injectManifest SW + manifest + iOS meta tags + placeholder icons + Kong rate-limit on invitations + dev JWT rotation + prod env template + rls-audit.sh + Justfile lighthouse/rls-audit/test-rate-limit). Production stack deployed to ambrosio (OVH VPS) at https://erosi.limonia.net (app + Supabase, external Keycloak); TLS via Traefik (deployed by NetBird's self-hosted installer, Docker-provider with label-based routing); PWA strategy switched to generateSW to unblock the prod build (see the "injectManifest hardcoded filename" gotcha below). Fase 7 complete: 12 new Playwright tests fill the collective-flow UI gap (O-01..O-03 onboarding, I-01..I-05 invitation acceptance, MC-02..MC-05 admin-manage) — writing them surfaced + fixed three latent bugs in the product code (atomic `create_collective()` RPC, pendingInvitationToken restore after login, manage page not reloading on late $currentCollective hydration). Plus migration 013 (auth.users role/aud default trigger) — found after the first real self-registration on prod via Keycloak→GoTrue left the user with empty `role`/`aud` columns, breaking every REST call with `role "" does not exist`. Post-fase-7 prod auth hardening (2026-04-20..21, see `docs/history/fase-8-auth-logout.md`): migration 014 extends the role/aud guard to UPDATE (GoTrue's pop-ORM resends role='' right after the INSERT and clobbered the INSERT trigger's backfill); `logout()` now does RP-initiated Keycloak end-session + lands on a new public `/logged-out` route, which both actually ends the Keycloak SSO cookie (so the next login re-prompts) and closes a PKCE-verifier race that produced "PKCE code verifier not found in storage" on prod. 259 tests green: 45 pgTAP + 140 Vitest integration + 15 Vitest unit + 59 Playwright + 1 Vitest rate-limit (gated, run via `just test-rate-limit`). 3 skipped in `just test-all` (2 Realtime presence — upstream `handle_out/3` bug; 1 rate-limit — gated). Push notifications + CI Docker + final production icons deliberately out of scope. ✅** ## Documentation Map - `README.md` — full development plan, confirmed tech stack, Justfile reference, technical warnings - `docs/development.md` — local dev stack, repo layout, Justfile + test commands, endpoints, credentials, secrets -- `docs/deployment.md` — production deploy to ambrosio (erosi.oier.ovh) + prod-specific fixes +- `docs/deployment.md` — production deploy to ambrosio (erosi.limonia.net) + prod-specific fixes - `docs/history/fase-{1,2a,2b,3,4,5,6,7}.md` — per-phase record of what was built - `docs/history/fase-8-auth-logout.md` — post-fase-7 prod auth hardening (migration 014 + RP-initiated logout) - `analysis/analisis-funcional.md` — complete functional specification (domain model, use cases, data models, business rules) @@ -165,13 +165,15 @@ Defined in `keycloak/realm-export.json` and `supabase/seed.sql`. All use passwor - Push notifications require iOS 16.4+ and the PWA must be installed to the home screen. - Test the shopping session mode on a real iPhone during development, not only in DevTools. -**nginx (prod) — WebSocket for Realtime:** -- The `/realtime/` location block **must come before** the `/` block. -- `proxy_read_timeout 3600s` is required on the Realtime block — without it, nginx closes WebSocket connections after 60 seconds, forcing continuous reconnects during active shopping sessions. -- CSP `connect-src` must include both `https://` and `wss://` for the API domain. +**Traefik (prod) — WebSocket for Realtime:** +- Traefik routes `Host(erosi.limonia.net) && PathPrefix(/rest/v1, /auth/v1, /realtime/v1, ...)` to Kong via Docker-provider labels (priority 100); everything else on the same host falls through to the SvelteKit app (priority 1). Routing lives on the `kong` and `app` services' `labels:` block in `infra/docker-compose.erosi.yml` — no Traefik config files. +- The HTTPS entrypoint must set `--entryPoints.websecure.transport.respondingTimeouts.idleTimeout=3600s` in Traefik's static config (NetBird-managed container — edit once when setting up). Default is ~180s; without the bump, Realtime WebSockets drop mid-shopping-session and the client reconnects continuously. +- Traefik auto-sets `X-Forwarded-{Proto,Host,Port,For}` when `tls.certresolver` is configured on the router, so no extra middleware is needed for the app. +- CSP `connect-src` must include both `https://erosi.limonia.net` and `wss://erosi.limonia.net`. -**Keycloak behind nginx:** -- `X-Forwarded-Host` and `X-Forwarded-Port` headers are mandatory. Without them, Keycloak builds redirect URIs with the internal port (8080) instead of 443, breaking the OIDC flow. +**External Keycloak:** +- Keycloak runs outside this stack; `PUBLIC_KEYCLOAK_URL` in `.env` points at it. Whatever proxy sits in front of it must forward `X-Forwarded-{Host,Port,Proto}` or Keycloak builds redirect URIs with internal ports and the OIDC flow breaks — that's the external operator's concern, not ours. +- The realm + client configuration required on the external Keycloak is documented in `docs/deployment.md` and mirrored in `keycloak/realm-export.erosi.json` (kept as reference; not imported by this stack). **Supabase Realtime self-hosted:** - Check `MAX_REPLICATION_SLOTS` in PostgreSQL and `REALTIME_MAX_CONNECTIONS` before going to production. diff --git a/docs/deployment.md b/docs/deployment.md index 1305b23..7a66c31 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2,26 +2,32 @@ ## Production stack — ambrosio (OVH VPS) -Live URLs: **https://erosi.oier.ovh** (app + Supabase API, single-domain) + **https://auth.oier.ovh** (Keycloak). OVH VPS, Ubuntu 24, Docker 29. +Live URL: **https://erosi.limonia.net** (app + Supabase API, single-domain). Keycloak is external — its URL is set via `PUBLIC_KEYCLOAK_URL` in `/opt/colectivo/.env`. OVH VPS, Ubuntu 24, Docker 29. -- `infra/docker-compose.erosi.yml` — full stack bound to `127.0.0.1` only (db, auth, rest, realtime, storage, imgproxy, kong, keycloak, app). `studio` + `meta` intentionally dropped for prod. -- `infra/caddy/erosi.Caddyfile` — snippet appended to the host's `/etc/caddy/Caddyfile` between `# BEGIN colectivo-erosi` / `# END colectivo-erosi` markers. Host Caddy 2.11.2 handles TLS (Let's Encrypt via tls-alpn-01). `erosi.oier.ovh` routes `/auth/v1/*`, `/rest/v1/*`, `/realtime/v1/*`, `/storage/v1/*`, `/graphql/v1/*`, `/pg/*` → Kong :8000; everything else → SvelteKit :3000. `auth.oier.ovh` → Keycloak :8090 with `X-Forwarded-Port` explicitly (Caddy auto-sets Proto/Host/For). -- `infra/scripts/deploy-erosi.sh` — idempotent redeploy: rsync → generate secrets on first run (via `infra/scripts/rotate-jwt.sh`) → substitute `__KEYCLOAK_CLIENT_SECRET__` in `keycloak/realm-export.erosi.json` → docker compose build + up → run pending migrations → re-install Caddy snippet → reload. -- `keycloak/realm-export.erosi.json` — prod realm: `registrationAllowed: true`, redirect URIs scoped to `https://erosi.oier.ovh/*`, client secret placeholder that the deploy script substitutes with a per-install random value. No dev users. +- `infra/docker-compose.erosi.yml` — full stack (db, auth, rest, realtime, storage, imgproxy, kong, app). `studio`, `meta`, and the bundled `keycloak` service are intentionally absent. `kong` and `app` attach to two Docker networks: `colectivo` (internal, for DB and inter-service traffic) and `traefik` (external, named via `${TRAEFIK_NETWORK}` — the Traefik instance that NetBird's self-hosted installer deployed). +- **Reverse proxy**: Traefik owns ports 80 + 443 on ambrosio. It discovers our services via `traefik.*` labels (Docker provider): `erosi-kong` (priority 100) catches `/rest/v1`, `/auth/v1`, `/realtime/v1`, `/storage/v1`, `/graphql/v1`, `/pg` on `erosi.limonia.net` → `kong:8000`; `erosi-app` (priority 1) catches everything else on the same host → `app:3000`. TLS via Traefik's certresolver (`${TRAEFIK_CERTRESOLVER}`, defaults to `letsencrypt`). No container binds a host port. +- `infra/scripts/deploy-erosi.sh` — idempotent redeploy: rsync → on first run generate secrets + write `/opt/colectivo/.env` with placeholders the operator fills in (`PUBLIC_KEYCLOAK_URL`, `KEYCLOAK_CLIENT_SECRET`, `TRAEFIK_NETWORK`) → subsequent runs fail fast if any placeholder is unfilled → docker compose build + up → apply pending migrations. Never touches `/etc/caddy/*`, never runs `sudo`. +- `keycloak/realm-export.erosi.json` — **not imported** by this stack (no bundled Keycloak). Kept as reference for what the external Keycloak's `colectivo-web` client must have: `redirectUris: ["https://erosi.limonia.net/*", "https://erosi.limonia.net/auth/v1/callback"]`, `webOrigins: ["https://erosi.limonia.net"]`, confidential client, `openid` as a default client scope with `include.in.token.scope=true`. - `.env.erosi.example` — committed template. The real `/opt/colectivo/.env` on ambrosio is 600 and stays on the server. -- UFW allows `80/tcp`, `443/tcp`, `22/tcp`. All other ports remain DENY. Docker services listen on `127.0.0.1` only, so Kong / Keycloak / the app are unreachable from the public internet except via Caddy. + +## Pre-deploy prerequisites + +1. **External Keycloak** reachable from ambrosio's Docker network (outbound HTTPS). Realm + `colectivo-web` client configured as described above; operator pastes the client secret into `.env` as `KEYCLOAK_CLIENT_SECRET`. +2. **Users in the external Keycloak must match existing `auth.users` UUIDs** (`auth.users.id = keycloak sub`) or the stack starts fresh with no prior users. Re-registering produces new sub UUIDs; either re-seed `auth.users` + `auth.identities` or wipe and start over. +3. **NetBird's Traefik long-idle-timeout** on the HTTPS entrypoint — required for Realtime WebSockets. Add to the Traefik container's args: + ``` + --entryPoints.websecure.transport.respondingTimeouts.idleTimeout=3600s + ``` + Default is ~180s; active shopping sessions disconnect without this. One-time change outside this repo. +4. **DNS** for `erosi.limonia.net` → ambrosio (A/AAAA). +5. **Host Caddy disabled**. The previous deploy used a systemd Caddy as TLS terminator; it must be stopped and `systemctl disable caddy` so it doesn't race Traefik for 80/443 on reboot. Remove any `# BEGIN colectivo-erosi … # END colectivo-erosi` block from `/etc/caddy/Caddyfile` for tidiness. ## Prod-specific fixes Had to be made for the stack to boot cleanly on a fresh volume: -- `infra/db-init/00-role-passwords.sh` — rewrote as idempotent bootstrap (see the "supabase/postgres doesn't bootstrap Supabase roles" gotcha in `CLAUDE.md`): creates all Supabase service roles if absent, enables `pg_cron` + `pgcrypto` + `uuid-ossp`, creates `auth` / `storage` / `graphql_public` / `_realtime` / `realtime` schemas + empty `supabase_realtime` publication + `keycloak` database + role, sets `supabase_auth_admin` search_path to `auth`. The old `00-role-passwords.sql` (ALTER-only) has been removed. +- `infra/db-init/00-role-passwords.sh` — rewrote as idempotent bootstrap (see the "supabase/postgres doesn't bootstrap Supabase roles" gotcha in `CLAUDE.md`): creates all Supabase service roles if absent, enables `pg_cron` + `pgcrypto` + `uuid-ossp`, creates `auth` / `storage` / `graphql_public` / `_realtime` / `realtime` schemas + empty `supabase_realtime` publication, sets `supabase_auth_admin` search_path to `auth`. The old `00-role-passwords.sql` (ALTER-only) has been removed. - `apps/web/vite.config.ts` — PWA strategy switched `injectManifest` → `generateSW` (see the "injectManifest hardcoded filename" gotcha in `CLAUDE.md`). -- Keycloak container uses `start --import-realm` (no `--optimized`) so Quarkus re-builds with the Postgres driver on first boot; with `--optimized` it silently falls back to H2 and fails with "jdbc:h2 URL format error". - -## Keycloak admin password - -Generated per-install — retrieve with `ssh ambrosio 'grep KEYCLOAK_ADMIN_PASSWORD /opt/colectivo/.env'`. Console at https://auth.oier.ovh/admin. ## Not yet configured on ambrosio diff --git a/infra/caddy/erosi.Caddyfile b/infra/caddy/erosi.Caddyfile deleted file mode 100644 index b34d2aa..0000000 --- a/infra/caddy/erosi.Caddyfile +++ /dev/null @@ -1,46 +0,0 @@ -# Caddyfile snippet for ambrosio host Caddy. -# Install path: /etc/caddy/Caddyfile (append these blocks). -# Reload: sudo systemctl reload caddy -# -# Docker services bind to 127.0.0.1 only; this file is the public entrypoint. -# TLS certificates are issued automatically by Caddy via Let's Encrypt. - -# ── App + Supabase (single domain) ────────────────────────────────────────── -erosi.oier.ovh { - encode zstd gzip - - # Supabase API paths → Kong gateway. - # Realtime MUST come before /auth, /rest, /storage to match its WS upgrade path first. - @supabase path /auth/v1/* /rest/v1/* /storage/v1/* /realtime/v1/* /graphql/v1/* /pg/* - handle @supabase { - # Realtime WebSockets require a long read timeout; PostgREST benefits from - # flush_interval for streaming responses. Caddy handles WS upgrades natively. - reverse_proxy 127.0.0.1:8000 { - transport http { - read_timeout 3600s - } - header_up X-Real-IP {remote_host} - } - } - - # Everything else → SvelteKit Node server. - handle { - reverse_proxy 127.0.0.1:3000 { - header_up X-Real-IP {remote_host} - } - } -} - -# ── Keycloak ──────────────────────────────────────────────────────────────── -auth.oier.ovh { - encode zstd gzip - - # Keycloak 24 with KC_PROXY=edge uses the X-Forwarded-* headers that Caddy - # already sets automatically on every reverse_proxy (Proto, For, Host). - # Only X-Forwarded-Port is not default, so we add it explicitly — without - # it Keycloak builds redirect URIs with the internal port (8080). - reverse_proxy 127.0.0.1:8090 { - header_up X-Real-IP {remote_host} - header_up X-Forwarded-Port {server_port} - } -} diff --git a/infra/docker-compose.erosi.yml b/infra/docker-compose.erosi.yml index cb6bb74..8eff279 100644 --- a/infra/docker-compose.erosi.yml +++ b/infra/docker-compose.erosi.yml @@ -1,11 +1,13 @@ name: colectivo-erosi -# Production stack for ambrosio (OVH VPS). -# Domains: erosi.oier.ovh (app + Supabase API) | auth.oier.ovh (Keycloak) +# Production stack for ambrosio. +# Domain: erosi.limonia.net (app + Supabase API, single-domain). +# Keycloak: external — URL set via PUBLIC_KEYCLOAK_URL in .env. # -# TLS + reverse proxy is handled by the HOST Caddy (systemd service on ambrosio, -# config at /etc/caddy/Caddyfile) — NOT by a container. All services here bind -# to 127.0.0.1 so only Caddy can reach them. +# TLS + reverse proxy is handled by Traefik (deployed by NetBird's self-hosted +# installer on ambrosio). `kong` and `app` attach to Traefik's Docker network +# (name in ${TRAEFIK_NETWORK}) and expose themselves via traefik.* labels. +# No container binds a host port. # # Bring up: docker compose -f infra/docker-compose.erosi.yml --env-file .env up -d --build # Logs: docker compose -f infra/docker-compose.erosi.yml logs -f @@ -54,8 +56,7 @@ services: GOTRUE_EXTERNAL_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID} GOTRUE_EXTERNAL_KEYCLOAK_SECRET: ${KEYCLOAK_CLIENT_SECRET} GOTRUE_EXTERNAL_KEYCLOAK_SCOPES: "openid profile email" - # Public Keycloak base URL (browser sees this). The `/realms/colectivo` - # suffix is appended by GoTrue. + # Browser-facing Keycloak issuer URL. GoTrue appends /.well-known to it. GOTRUE_EXTERNAL_KEYCLOAK_URL: ${PUBLIC_KEYCLOAK_URL}/realms/${PUBLIC_KEYCLOAK_REALM} GOTRUE_EXTERNAL_KEYCLOAK_REDIRECT_URI: ${PUBLIC_SUPABASE_URL}/auth/v1/callback GOTRUE_MAILER_AUTOCONFIRM: "true" @@ -142,13 +143,11 @@ services: - storage-data:/var/lib/storage:ro networks: [colectivo] - # ── Kong (API Gateway) — bound to localhost only; host Caddy proxies it ──── + # ── Kong (API Gateway) — exposed on the Traefik network via labels ──────── kong: image: kong:2.8.1 restart: always entrypoint: ["/bin/bash", "/home/kong/kong-start.sh"] - ports: - - "127.0.0.1:8000:8000" depends_on: db: { condition: service_healthy } environment: @@ -163,39 +162,15 @@ services: volumes: - ./kong.yml:/home/kong/temp.yml:ro - ./kong-start.sh:/home/kong/kong-start.sh:ro - networks: [colectivo] - - # ── Keycloak 24 ──────────────────────────────────────────────────────────── - # Bound to localhost only; host Caddy proxies auth.oier.ovh → 127.0.0.1:8090. - # KC_PROXY=edge expects X-Forwarded-* from Caddy. - keycloak: - image: quay.io/keycloak/keycloak:24.0.5 - restart: always - ports: - - "127.0.0.1:8090:8080" - # Plain `start` (no --optimized) so Quarkus re-builds with the Postgres - # driver on first boot. --optimized skips the build phase and falls back - # to H2, producing "URL format error ... jdbc:h2" on startup. - command: start --import-realm - depends_on: - db: { condition: service_healthy } - environment: - KC_DB: postgres - KC_DB_URL: jdbc:postgresql://db:5432/keycloak - KC_DB_USERNAME: keycloak - KC_DB_PASSWORD: ${POSTGRES_PASSWORD} - KC_HOSTNAME: ${KEYCLOAK_HOSTNAME} - KC_HOSTNAME_STRICT: "true" - KC_HOSTNAME_STRICT_HTTPS: "true" - KC_PROXY: edge - KC_HTTP_ENABLED: "true" - KEYCLOAK_ADMIN: ${KEYCLOAK_ADMIN} - KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD} - KC_FEATURES: token-exchange - volumes: - - keycloak-data:/opt/keycloak/data - - ../keycloak/realm-export.erosi.json:/opt/keycloak/data/import/realm-export.json:ro - networks: [colectivo] + networks: [colectivo, traefik] + labels: + - "traefik.enable=true" + - "traefik.docker.network=${TRAEFIK_NETWORK}" + - "traefik.http.routers.erosi-kong.rule=Host(`erosi.limonia.net`) && (PathPrefix(`/rest/v1`) || PathPrefix(`/auth/v1`) || PathPrefix(`/realtime/v1`) || PathPrefix(`/storage/v1`) || PathPrefix(`/graphql/v1`) || PathPrefix(`/pg`))" + - "traefik.http.routers.erosi-kong.entrypoints=${TRAEFIK_ENTRYPOINT}" + - "traefik.http.routers.erosi-kong.tls.certresolver=${TRAEFIK_CERTRESOLVER}" + - "traefik.http.routers.erosi-kong.priority=100" + - "traefik.http.services.erosi-kong.loadbalancer.server.port=8000" # ── App (SvelteKit Node server) — built on the host from the repo ────────── # Build args bake the PUBLIC_* values into the client bundle (SvelteKit reqs). @@ -212,8 +187,6 @@ services: PUBLIC_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID} PUBLIC_APP_URL: ${PUBLIC_APP_URL} restart: always - ports: - - "127.0.0.1:3000:3000" environment: PUBLIC_SUPABASE_URL: ${PUBLIC_SUPABASE_URL} PUBLIC_SUPABASE_ANON_KEY: ${PUBLIC_SUPABASE_ANON_KEY} @@ -222,13 +195,23 @@ services: PUBLIC_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID} PUBLIC_APP_URL: ${PUBLIC_APP_URL} NODE_ENV: production - networks: [colectivo] + networks: [colectivo, traefik] + labels: + - "traefik.enable=true" + - "traefik.docker.network=${TRAEFIK_NETWORK}" + - "traefik.http.routers.erosi-app.rule=Host(`erosi.limonia.net`)" + - "traefik.http.routers.erosi-app.entrypoints=${TRAEFIK_ENTRYPOINT}" + - "traefik.http.routers.erosi-app.tls.certresolver=${TRAEFIK_CERTRESOLVER}" + - "traefik.http.routers.erosi-app.priority=1" + - "traefik.http.services.erosi-app.loadbalancer.server.port=3000" networks: colectivo: driver: bridge + traefik: + name: ${TRAEFIK_NETWORK} + external: true volumes: db-data: storage-data: - keycloak-data: diff --git a/infra/scripts/deploy-erosi.sh b/infra/scripts/deploy-erosi.sh index 787685b..d2330b5 100755 --- a/infra/scripts/deploy-erosi.sh +++ b/infra/scripts/deploy-erosi.sh @@ -7,11 +7,15 @@ # # First run: # 1. rsyncs repo → ambrosio:/opt/colectivo/ -# 2. if .env doesn't exist on server, generates secrets and writes it -# 3. patches realm-export.erosi.json with the generated Keycloak client secret -# 4. docker compose build + up -d -# 5. applies DB migrations -# 6. installs the Caddyfile snippet into host Caddy and reloads +# 2. if .env doesn't exist on server, generates secrets and writes it with +# placeholder values the operator must fill in (external Keycloak URL, +# Keycloak client secret, Traefik network name) +# 3. docker compose build + up -d +# 4. applies DB migrations +# +# TLS + routing is handled by Traefik (deployed by NetBird's self-hosted +# installer on ambrosio). This script never touches /etc/caddy/* or any host +# reverse-proxy config — it only manages the Docker stack. # # Subsequent runs: rsync + rebuild app + rolling restart. @@ -43,7 +47,7 @@ rsync -az --delete \ --exclude 'playwright-report' \ "$REPO_ROOT/" "$DEPLOY_HOST:$DEPLOY_PATH/" -# ── 3. Bootstrap secrets on first run ────────────────────────────────────── +# ── 3. Bootstrap secrets on first run; sanity-check placeholders every run ─ ssh "$DEPLOY_HOST" bash -s << 'REMOTE' set -euo pipefail cd /opt/colectivo @@ -57,21 +61,28 @@ if [ ! -f .env ]; then PUBLIC_SUPABASE_ANON_KEY=$(echo "$JWT_OUT" | awk -F= '/^PUBLIC_SUPABASE_ANON_KEY=/{print substr($0, index($0,$2))}') SUPABASE_SERVICE_ROLE_KEY=$(echo "$JWT_OUT" | awk -F= '/^SUPABASE_SERVICE_ROLE_KEY=/{print substr($0, index($0,$2))}') - # Other passwords + keys + # Postgres + Realtime secrets POSTGRES_PASSWORD=$(openssl rand -hex 24) - KEYCLOAK_ADMIN_PASSWORD=$(openssl rand -hex 24) - KEYCLOAK_CLIENT_SECRET=$(openssl rand -hex 24) REALTIME_ENC_KEY=$(openssl rand -hex 8) # 16 chars REALTIME_SECRET_KEY_BASE=$(openssl rand -hex 48) # 96 chars cat > .env <&2 + echo " Fill in PUBLIC_KEYCLOAK_URL, KEYCLOAK_CLIENT_SECRET, TRAEFIK_NETWORK and retry." >&2 + exit 1 +fi REMOTE # ── 4. Build + bring up the stack ───────────────────────────────────────── @@ -146,39 +160,8 @@ for f in supabase/migrations/*.sql; do echo "FAIL"; exit 1 fi done - -echo "--- Keycloak may need an extra minute to import the realm on first boot" -REMOTE - -# ── 5. Install Caddyfile snippet into host Caddy (idempotent) ───────────── -ssh "$DEPLOY_HOST" bash -s << 'REMOTE' -set -euo pipefail -cd /opt/colectivo - -MARKER_START="# BEGIN colectivo-erosi" -MARKER_END="# END colectivo-erosi" - -# Strip any previous version of our block from /etc/caddy/Caddyfile, then append fresh. -sudo awk -v start="$MARKER_START" -v end="$MARKER_END" ' - $0 ~ start {skip=1} - !skip {print} - $0 ~ end {skip=0} -' /etc/caddy/Caddyfile > /tmp/Caddyfile.new - -{ - echo "" - echo "$MARKER_START" - cat infra/caddy/erosi.Caddyfile - echo "$MARKER_END" -} >> /tmp/Caddyfile.new - -sudo mv /tmp/Caddyfile.new /etc/caddy/Caddyfile -sudo caddy validate --config /etc/caddy/Caddyfile -sudo systemctl reload caddy -echo "--- Caddy reloaded" REMOTE echo "==> Deploy complete." -echo " App: https://erosi.oier.ovh" -echo " Keycloak: https://auth.oier.ovh" -echo " Admin pw: ssh $DEPLOY_HOST 'grep KEYCLOAK_ADMIN_PASSWORD $DEPLOY_PATH/.env'" +echo " App: https://erosi.limonia.net" +echo " Keycloak: external — see PUBLIC_KEYCLOAK_URL in $DEPLOY_PATH/.env" diff --git a/keycloak/realm-export.erosi.json b/keycloak/realm-export.erosi.json index a366b85..1835329 100644 --- a/keycloak/realm-export.erosi.json +++ b/keycloak/realm-export.erosi.json @@ -300,11 +300,11 @@ "clientAuthenticatorType": "client-secret", "secret": "__KEYCLOAK_CLIENT_SECRET__", "redirectUris": [ - "https://erosi.oier.ovh/*", - "https://erosi.oier.ovh/auth/v1/callback" + "https://erosi.limonia.net/*", + "https://erosi.limonia.net/auth/v1/callback" ], "webOrigins": [ - "https://erosi.oier.ovh" + "https://erosi.limonia.net" ], "notBefore": 0, "bearerOnly": false,