deploy(prod): swap host Caddy for NetBird-Traefik labels + external Keycloak

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) <noreply@anthropic.com>
This commit is contained in:
2026-04-23 23:49:10 +02:00
parent 0e4ada0083
commit 33b32cae4a
7 changed files with 117 additions and 183 deletions

View File

@@ -1,15 +1,27 @@
# Production env for ambrosio — copy to .env on the server and fill in secrets. # Production env for ambrosio — copy to .env on the server and fill in secrets.
# Generate JWT triplet: bash infra/scripts/rotate-jwt.sh # Generate JWT triplet: bash infra/scripts/rotate-jwt.sh
# ── Domains (change if you migrate to new hostnames) ──────────────────────── # ── App + Supabase API (single domain, routed by Traefik on ambrosio) ──────
PUBLIC_APP_URL=https://erosi.oier.ovh PUBLIC_APP_URL=https://erosi.limonia.net
PUBLIC_SUPABASE_URL=https://erosi.oier.ovh PUBLIC_SUPABASE_URL=https://erosi.limonia.net
PUBLIC_KEYCLOAK_URL=https://auth.oier.ovh
# ── 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_REALM=colectivo
PUBLIC_KEYCLOAK_CLIENT_ID=colectivo-web PUBLIC_KEYCLOAK_CLIENT_ID=colectivo-web
KEYCLOAK_CLIENT_SECRET=CHANGEME-paste-from-external-keycloak
# Keycloak sees this as its canonical hostname (KC_HOSTNAME). # ── Traefik (deployed by NetBird's self-hosted installer on ambrosio) ──────
KEYCLOAK_HOSTNAME=auth.oier.ovh # 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 (single password for all internal roles) ───────────────────────
POSTGRES_PASSWORD=CHANGEME-strong-random-password 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 PUBLIC_SUPABASE_ANON_KEY=CHANGEME-sign-with-above
SUPABASE_SERVICE_ROLE_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 ───────────────────────────────────────────────────── # ── Realtime encryption ─────────────────────────────────────────────────────
# DB_ENC_KEY: exactly 16 characters. SECRET_KEY_BASE: ≥ 64 characters. # DB_ENC_KEY: exactly 16 characters. SECRET_KEY_BASE: ≥ 64 characters.
REALTIME_ENC_KEY=CHANGEME16charkey REALTIME_ENC_KEY=CHANGEME16charkey

View File

@@ -4,13 +4,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Status ## Project Status
**Fase 05 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 05 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 ## Documentation Map
- `README.md` — full development plan, confirmed tech stack, Justfile reference, technical warnings - `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/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-{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) - `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) - `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. - 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. - Test the shopping session mode on a real iPhone during development, not only in DevTools.
**nginx (prod) — WebSocket for Realtime:** **Traefik (prod) — WebSocket for Realtime:**
- The `/realtime/` location block **must come before** the `/` block. - 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.
- `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. - 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.
- CSP `connect-src` must include both `https://` and `wss://` for the API domain. - 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:** **External Keycloak:**
- `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. - 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:** **Supabase Realtime self-hosted:**
- Check `MAX_REPLICATION_SLOTS` in PostgreSQL and `REALTIME_MAX_CONNECTIONS` before going to production. - Check `MAX_REPLICATION_SLOTS` in PostgreSQL and `REALTIME_MAX_CONNECTIONS` before going to production.

View File

@@ -2,26 +2,32 @@
## Production stack — ambrosio (OVH VPS) ## 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/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).
- `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). - **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 → 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. - `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`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. - `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. - `.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 ## Prod-specific fixes
Had to be made for the stack to boot cleanly on a fresh volume: 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`). - `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 ## Not yet configured on ambrosio

View File

@@ -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}
}
}

View File

@@ -1,11 +1,13 @@
name: colectivo-erosi name: colectivo-erosi
# Production stack for ambrosio (OVH VPS). # Production stack for ambrosio.
# Domains: erosi.oier.ovh (app + Supabase API) | auth.oier.ovh (Keycloak) # 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, # TLS + reverse proxy is handled by Traefik (deployed by NetBird's self-hosted
# config at /etc/caddy/Caddyfile) — NOT by a container. All services here bind # installer on ambrosio). `kong` and `app` attach to Traefik's Docker network
# to 127.0.0.1 so only Caddy can reach them. # (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 # 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 # 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_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID}
GOTRUE_EXTERNAL_KEYCLOAK_SECRET: ${KEYCLOAK_CLIENT_SECRET} GOTRUE_EXTERNAL_KEYCLOAK_SECRET: ${KEYCLOAK_CLIENT_SECRET}
GOTRUE_EXTERNAL_KEYCLOAK_SCOPES: "openid profile email" GOTRUE_EXTERNAL_KEYCLOAK_SCOPES: "openid profile email"
# Public Keycloak base URL (browser sees this). The `/realms/colectivo` # Browser-facing Keycloak issuer URL. GoTrue appends /.well-known to it.
# suffix is appended by GoTrue.
GOTRUE_EXTERNAL_KEYCLOAK_URL: ${PUBLIC_KEYCLOAK_URL}/realms/${PUBLIC_KEYCLOAK_REALM} GOTRUE_EXTERNAL_KEYCLOAK_URL: ${PUBLIC_KEYCLOAK_URL}/realms/${PUBLIC_KEYCLOAK_REALM}
GOTRUE_EXTERNAL_KEYCLOAK_REDIRECT_URI: ${PUBLIC_SUPABASE_URL}/auth/v1/callback GOTRUE_EXTERNAL_KEYCLOAK_REDIRECT_URI: ${PUBLIC_SUPABASE_URL}/auth/v1/callback
GOTRUE_MAILER_AUTOCONFIRM: "true" GOTRUE_MAILER_AUTOCONFIRM: "true"
@@ -142,13 +143,11 @@ services:
- storage-data:/var/lib/storage:ro - storage-data:/var/lib/storage:ro
networks: [colectivo] networks: [colectivo]
# ── Kong (API Gateway) — bound to localhost only; host Caddy proxies it ──── # ── Kong (API Gateway) — exposed on the Traefik network via labels ────────
kong: kong:
image: kong:2.8.1 image: kong:2.8.1
restart: always restart: always
entrypoint: ["/bin/bash", "/home/kong/kong-start.sh"] entrypoint: ["/bin/bash", "/home/kong/kong-start.sh"]
ports:
- "127.0.0.1:8000:8000"
depends_on: depends_on:
db: { condition: service_healthy } db: { condition: service_healthy }
environment: environment:
@@ -163,39 +162,15 @@ services:
volumes: volumes:
- ./kong.yml:/home/kong/temp.yml:ro - ./kong.yml:/home/kong/temp.yml:ro
- ./kong-start.sh:/home/kong/kong-start.sh:ro - ./kong-start.sh:/home/kong/kong-start.sh:ro
networks: [colectivo] networks: [colectivo, traefik]
labels:
# ── Keycloak 24 ──────────────────────────────────────────────────────────── - "traefik.enable=true"
# Bound to localhost only; host Caddy proxies auth.oier.ovh → 127.0.0.1:8090. - "traefik.docker.network=${TRAEFIK_NETWORK}"
# KC_PROXY=edge expects X-Forwarded-* from Caddy. - "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`))"
keycloak: - "traefik.http.routers.erosi-kong.entrypoints=${TRAEFIK_ENTRYPOINT}"
image: quay.io/keycloak/keycloak:24.0.5 - "traefik.http.routers.erosi-kong.tls.certresolver=${TRAEFIK_CERTRESOLVER}"
restart: always - "traefik.http.routers.erosi-kong.priority=100"
ports: - "traefik.http.services.erosi-kong.loadbalancer.server.port=8000"
- "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]
# ── App (SvelteKit Node server) — built on the host from the repo ────────── # ── App (SvelteKit Node server) — built on the host from the repo ──────────
# Build args bake the PUBLIC_* values into the client bundle (SvelteKit reqs). # 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_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID}
PUBLIC_APP_URL: ${PUBLIC_APP_URL} PUBLIC_APP_URL: ${PUBLIC_APP_URL}
restart: always restart: always
ports:
- "127.0.0.1:3000:3000"
environment: environment:
PUBLIC_SUPABASE_URL: ${PUBLIC_SUPABASE_URL} PUBLIC_SUPABASE_URL: ${PUBLIC_SUPABASE_URL}
PUBLIC_SUPABASE_ANON_KEY: ${PUBLIC_SUPABASE_ANON_KEY} PUBLIC_SUPABASE_ANON_KEY: ${PUBLIC_SUPABASE_ANON_KEY}
@@ -222,13 +195,23 @@ services:
PUBLIC_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID} PUBLIC_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID}
PUBLIC_APP_URL: ${PUBLIC_APP_URL} PUBLIC_APP_URL: ${PUBLIC_APP_URL}
NODE_ENV: production 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: networks:
colectivo: colectivo:
driver: bridge driver: bridge
traefik:
name: ${TRAEFIK_NETWORK}
external: true
volumes: volumes:
db-data: db-data:
storage-data: storage-data:
keycloak-data:

View File

@@ -7,11 +7,15 @@
# #
# First run: # First run:
# 1. rsyncs repo → ambrosio:/opt/colectivo/ # 1. rsyncs repo → ambrosio:/opt/colectivo/
# 2. if .env doesn't exist on server, generates secrets and writes it # 2. if .env doesn't exist on server, generates secrets and writes it with
# 3. patches realm-export.erosi.json with the generated Keycloak client secret # placeholder values the operator must fill in (external Keycloak URL,
# 4. docker compose build + up -d # Keycloak client secret, Traefik network name)
# 5. applies DB migrations # 3. docker compose build + up -d
# 6. installs the Caddyfile snippet into host Caddy and reloads # 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. # Subsequent runs: rsync + rebuild app + rolling restart.
@@ -43,7 +47,7 @@ rsync -az --delete \
--exclude 'playwright-report' \ --exclude 'playwright-report' \
"$REPO_ROOT/" "$DEPLOY_HOST:$DEPLOY_PATH/" "$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' ssh "$DEPLOY_HOST" bash -s << 'REMOTE'
set -euo pipefail set -euo pipefail
cd /opt/colectivo 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))}') 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))}') 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) 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_ENC_KEY=$(openssl rand -hex 8) # 16 chars
REALTIME_SECRET_KEY_BASE=$(openssl rand -hex 48) # 96 chars REALTIME_SECRET_KEY_BASE=$(openssl rand -hex 48) # 96 chars
cat > .env <<EOF cat > .env <<EOF
# Generated on $(date -u +%Y-%m-%dT%H:%M:%SZ). Keep this file mode 600. # Generated on $(date -u +%Y-%m-%dT%H:%M:%SZ). Keep this file mode 600.
PUBLIC_APP_URL=https://erosi.oier.ovh PUBLIC_APP_URL=https://erosi.limonia.net
PUBLIC_SUPABASE_URL=https://erosi.oier.ovh PUBLIC_SUPABASE_URL=https://erosi.limonia.net
PUBLIC_KEYCLOAK_URL=https://auth.oier.ovh
# External Keycloak — FILL THESE IN before the stack will boot usefully.
PUBLIC_KEYCLOAK_URL=FILL_IN_KEYCLOAK_URL
PUBLIC_KEYCLOAK_REALM=colectivo PUBLIC_KEYCLOAK_REALM=colectivo
PUBLIC_KEYCLOAK_CLIENT_ID=colectivo-web PUBLIC_KEYCLOAK_CLIENT_ID=colectivo-web
KEYCLOAK_HOSTNAME=auth.oier.ovh KEYCLOAK_CLIENT_SECRET=FILL_IN_CLIENT_SECRET
# Traefik (deployed by NetBird's self-hosted installer on ambrosio).
# FILL_IN the network name the installer asked you for; defaults for
# entrypoint + certresolver match NetBird's typical setup.
TRAEFIK_NETWORK=FILL_IN_TRAEFIK_NETWORK
TRAEFIK_ENTRYPOINT=websecure
TRAEFIK_CERTRESOLVER=letsencrypt
POSTGRES_PASSWORD=$POSTGRES_PASSWORD POSTGRES_PASSWORD=$POSTGRES_PASSWORD
@@ -79,21 +90,24 @@ SUPABASE_JWT_SECRET=$SUPABASE_JWT_SECRET
PUBLIC_SUPABASE_ANON_KEY=$PUBLIC_SUPABASE_ANON_KEY PUBLIC_SUPABASE_ANON_KEY=$PUBLIC_SUPABASE_ANON_KEY
SUPABASE_SERVICE_ROLE_KEY=$SUPABASE_SERVICE_ROLE_KEY SUPABASE_SERVICE_ROLE_KEY=$SUPABASE_SERVICE_ROLE_KEY
KEYCLOAK_ADMIN=admin
KEYCLOAK_ADMIN_PASSWORD=$KEYCLOAK_ADMIN_PASSWORD
KEYCLOAK_CLIENT_SECRET=$KEYCLOAK_CLIENT_SECRET
REALTIME_ENC_KEY=$REALTIME_ENC_KEY REALTIME_ENC_KEY=$REALTIME_ENC_KEY
REALTIME_SECRET_KEY_BASE=$REALTIME_SECRET_KEY_BASE REALTIME_SECRET_KEY_BASE=$REALTIME_SECRET_KEY_BASE
EOF EOF
chmod 600 .env chmod 600 .env
echo "--- Wrote .env (mode 600). Keycloak admin password stored there." echo "--- Wrote .env (mode 600)."
echo " Fill in: PUBLIC_KEYCLOAK_URL, KEYCLOAK_CLIENT_SECRET, TRAEFIK_NETWORK"
echo " then re-run this script."
exit 0
fi fi
# Always substitute the client secret placeholder in the realm JSON. # Every deploy: fail fast if the operator didn't finish the .env.
# Keycloak only imports the realm if it doesn't exist yet — on first boot only. if grep -q '^PUBLIC_KEYCLOAK_URL=FILL_IN_' .env \
source .env || grep -q '^KEYCLOAK_CLIENT_SECRET=FILL_IN_' .env \
sed -i "s|__KEYCLOAK_CLIENT_SECRET__|$KEYCLOAK_CLIENT_SECRET|g" keycloak/realm-export.erosi.json || grep -q '^TRAEFIK_NETWORK=FILL_IN_' .env; then
echo "ERROR: /opt/colectivo/.env still contains FILL_IN_ placeholders." >&2
echo " Fill in PUBLIC_KEYCLOAK_URL, KEYCLOAK_CLIENT_SECRET, TRAEFIK_NETWORK and retry." >&2
exit 1
fi
REMOTE REMOTE
# ── 4. Build + bring up the stack ───────────────────────────────────────── # ── 4. Build + bring up the stack ─────────────────────────────────────────
@@ -146,39 +160,8 @@ for f in supabase/migrations/*.sql; do
echo "FAIL"; exit 1 echo "FAIL"; exit 1
fi fi
done 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 REMOTE
echo "==> Deploy complete." echo "==> Deploy complete."
echo " App: https://erosi.oier.ovh" echo " App: https://erosi.limonia.net"
echo " Keycloak: https://auth.oier.ovh" echo " Keycloak: external — see PUBLIC_KEYCLOAK_URL in $DEPLOY_PATH/.env"
echo " Admin pw: ssh $DEPLOY_HOST 'grep KEYCLOAK_ADMIN_PASSWORD $DEPLOY_PATH/.env'"

View File

@@ -300,11 +300,11 @@
"clientAuthenticatorType": "client-secret", "clientAuthenticatorType": "client-secret",
"secret": "__KEYCLOAK_CLIENT_SECRET__", "secret": "__KEYCLOAK_CLIENT_SECRET__",
"redirectUris": [ "redirectUris": [
"https://erosi.oier.ovh/*", "https://erosi.limonia.net/*",
"https://erosi.oier.ovh/auth/v1/callback" "https://erosi.limonia.net/auth/v1/callback"
], ],
"webOrigins": [ "webOrigins": [
"https://erosi.oier.ovh" "https://erosi.limonia.net"
], ],
"notBefore": 0, "notBefore": 0,
"bearerOnly": false, "bearerOnly": false,