name: colectivo-dev

# Self-hosted Supabase stack + Keycloak for local development.
# Based on: https://github.com/supabase/supabase/tree/master/docker
#
# Start: just dev
# Stop:  just dev-stop
# Reset: just dev-clean  (drops volumes)

services:

  # ── PostgreSQL 15 ───────────────────────────────────────────────────────────
  db:
    image: supabase/postgres:15.1.1.78
    restart: unless-stopped
    healthcheck:
      test: pg_isready -U postgres -h localhost
      interval: 5s
      timeout: 5s
      retries: 10
    ports:
      - "5432:5432"
    environment:
      POSTGRES_HOST: /var/run/postgresql
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
      JWT_SECRET: ${SUPABASE_JWT_SECRET}
      JWT_EXP: 3600
    volumes:
      - db-data:/var/lib/postgresql/data
      # Sets internal role passwords to POSTGRES_PASSWORD on first init.
      - ./db-init:/docker-entrypoint-initdb.d:ro

  # ── GoTrue (Supabase Auth) ──────────────────────────────────────────────────
  auth:
    image: supabase/gotrue:v2.158.1
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    environment:
      GOTRUE_API_HOST: "0.0.0.0"
      GOTRUE_API_PORT: 9999
      API_EXTERNAL_URL: ${PUBLIC_APP_URL:-http://localhost:5173}
      GOTRUE_API_EXTERNAL_URL: ${PUBLIC_APP_URL:-http://localhost:5173}
      GOTRUE_DB_DRIVER: postgres
      GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${POSTGRES_PASSWORD:-postgres}@db:5432/postgres
      GOTRUE_SITE_URL: ${PUBLIC_APP_URL:-http://localhost:5173}
      # Allow the SPA's /auth/callback subpath (where the /auth/callback +page
      # calls exchangeCodeForSession). Without this GoTrue rejects the
      # redirect_to query param and falls back to SITE_URL, stranding `?code=`
      # at `/` instead of `/auth/callback` — which then re-triggers signIn
      # and creates an infinite login loop. We also allow localhost so that
      # `just test-all` runs can still hit the app through the loopback.
      GOTRUE_URI_ALLOW_LIST: "http://192.168.1.167:5173/auth/callback,http://localhost:5173/auth/callback,http://localhost:3000/auth/callback"
      GOTRUE_JWT_SECRET: ${SUPABASE_JWT_SECRET}
      GOTRUE_JWT_EXP: 3600
      # Allow OIDC-based user creation (Keycloak is the gatekeeper).
      # Direct email/password signup is blocked at the Kong level (no /auth/v1/signup route exposed).
      GOTRUE_DISABLE_SIGNUP: "false"
      # OIDC: Keycloak as external provider
      GOTRUE_EXTERNAL_KEYCLOAK_ENABLED: "true"
      GOTRUE_EXTERNAL_KEYCLOAK_CLIENT_ID: ${PUBLIC_KEYCLOAK_CLIENT_ID:-colectivo-web}
      # colectivo-web is a confidential client in Keycloak (required for GoTrue code exchange).
      # Dev value matches keycloak/realm-export.json. Override in .env for prod.
      GOTRUE_EXTERNAL_KEYCLOAK_SECRET: ${KEYCLOAK_CLIENT_SECRET:-gotrue-dev-secret}
      # openid is required so the access token is an OIDC token and the userinfo endpoint accepts it.
      GOTRUE_EXTERNAL_KEYCLOAK_SCOPES: "openid profile email"
      # Must be reachable from the browser (for the 302 to Keycloak's /auth
      # endpoint) AND from inside this container (for the server-side code→token
      # exchange). The LAN IP in PUBLIC_KEYCLOAK_URL satisfies both: Docker
      # bridge routes container→host via the default gateway, then Docker's
      # port-forward loops 8080 back to the Keycloak container.
      GOTRUE_EXTERNAL_KEYCLOAK_URL: ${PUBLIC_KEYCLOAK_URL:-http://keycloak:8080}/realms/colectivo
      # Browser-reachable URL that Keycloak 302s back to after login. Must be
      # listed in the colectivo-web client's redirectUris in the realm.
      GOTRUE_EXTERNAL_KEYCLOAK_REDIRECT_URI: ${PUBLIC_SUPABASE_URL:-http://localhost:8001}/auth/v1/callback
      GOTRUE_MAILER_AUTOCONFIRM: "true"

  # ── PostgREST ───────────────────────────────────────────────────────────────
  rest:
    image: postgrest/postgrest:v12.2.0
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    environment:
      PGRST_DB_URI: postgres://authenticator:${POSTGRES_PASSWORD:-postgres}@db:5432/postgres
      PGRST_DB_SCHEMAS: public,storage,graphql_public
      PGRST_DB_ANON_ROLE: anon
      PGRST_JWT_SECRET: ${SUPABASE_JWT_SECRET}
      PGRST_DB_USE_LEGACY_GUCS: "false"
      PGRST_APP_SETTINGS_JWT_SECRET: ${SUPABASE_JWT_SECRET}
      PGRST_APP_SETTINGS_JWT_EXP: 3600

  # ── Realtime ─────────────────────────────────────────────────────────────────
  realtime:
    # Pinned to match the version in supabase/supabase's official docker-compose.
    # v2.83.0 had a runtime crash on presence_diff: `RealtimeWeb.RealtimeChannel.handle_out/3
    # is undefined` — presence events were published but couldn't be delivered.
    image: supabase/realtime:v2.76.5
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    environment:
      PORT: 4000
      DB_HOST: db
      DB_PORT: 5432
      # Realtime auto-creates the `realtime` schema (messages, subscription, etc.)
      # on first connect per tenant. It needs CREATE ON DATABASE + ownership, which
      # only supabase_admin (superuser) reliably has. Using
      # supabase_replication_admin fails with `permission denied for schema realtime`.
      DB_USER: supabase_admin
      DB_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
      DB_NAME: postgres
      DB_AFTER_CONNECT_QUERY: SET search_path TO _realtime
      DB_ENC_KEY: supabaserealtime
      API_JWT_SECRET: ${SUPABASE_JWT_SECRET}
      # supabase-js resolves the tenant from the URL subdomain; for bare
      # localhost with no subdomain it defaults to "realtime". We override the
      # default tenant name so the seed creates the tenant the client will look up.
      SELF_HOST_TENANT_NAME: realtime
      # `SEED_SELF_HOST: true` enables the built-in seeding path used by the
      # upstream supabase/supabase docker-compose. This is the canonical
      # startup flow; a custom `command: ... eval Realtime.Release.seeds ...`
      # starts the seed OUTSIDE the normal supervisor tree and was observed
      # to crash the `RealtimeChannel` on presence_diff broadcasts with an
      # "UndefinedFunctionError: handle_out/3" once clients connected.
      SEED_SELF_HOST: "true"
      RUN_JANITOR: "true"
      APP_NAME: realtime
      SECRET_KEY_BASE: UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3bhZkeYTvU
      ERL_AFLAGS: -proto_dist inet_tcp
      DNS_NODES: "''"
      RLIMIT_NOFILE: "10000"
      METRICS_JWT_SECRET: ${SUPABASE_JWT_SECRET}

  # ── Storage ──────────────────────────────────────────────────────────────────
  storage:
    image: supabase/storage-api:v1.11.13
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
      rest:
        condition: service_started
    environment:
      ANON_KEY: ${PUBLIC_SUPABASE_ANON_KEY}
      SERVICE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
      POSTGREST_URL: http://rest:3000
      PGRST_JWT_SECRET: ${SUPABASE_JWT_SECRET}
      DATABASE_URL: postgres://supabase_storage_admin:${POSTGRES_PASSWORD:-postgres}@db:5432/postgres
      FILE_SIZE_LIMIT: 52428800
      STORAGE_BACKEND: file
      FILE_STORAGE_BACKEND_PATH: /var/lib/storage
      TENANT_ID: stub
      REGION: local
      GLOBAL_S3_BUCKET: stub
      ENABLE_IMAGE_TRANSFORMATION: "true"
      IMGPROXY_URL: http://imgproxy:5001
    volumes:
      - storage-data:/var/lib/storage

  # ── ImgProxy (image transformations for Storage) ──────────────────────────
  imgproxy:
    image: darthsim/imgproxy:v3.8.0
    restart: unless-stopped
    environment:
      IMGPROXY_BIND: ":5001"
      IMGPROXY_LOCAL_FILESYSTEM_ROOT: /
      IMGPROXY_USE_ETAG: "true"
      IMGPROXY_ENABLE_WEBP_DETECTION: "true"
    volumes:
      - storage-data:/var/lib/storage:ro

  # ── Kong (API Gateway) ────────────────────────────────────────────────────
  kong:
    image: kong:2.8.1
    restart: unless-stopped
    # kong.yml uses ${SUPABASE_ANON_KEY} / ${SUPABASE_SERVICE_KEY} placeholders.
    # Kong 2.8 does NOT substitute env vars in declarative config automatically.
    # kong-start.sh uses perl to substitute ${VAR} from the container environment
    # before Kong loads the config.
    entrypoint: ["/bin/bash", "/home/kong/kong-start.sh"]
    ports:
      - "8001:8000"  # HTTP API (8000 may conflict; use http://localhost:8001)
      - "8443:8443"  # HTTPS API
    depends_on:
      db:
        condition: service_healthy
    environment:
      KONG_DATABASE: "off"
      KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
      KONG_DNS_ORDER: LAST,A,CNAME
      KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth,rate-limiting
      KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
      KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
      SUPABASE_ANON_KEY: ${PUBLIC_SUPABASE_ANON_KEY}
      SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
    volumes:
      - ./kong.yml:/home/kong/temp.yml:ro
      - ./kong-start.sh:/home/kong/kong-start.sh:ro

  # ── Supabase Studio ───────────────────────────────────────────────────────
  studio:
    image: supabase/studio:2026.04.08-sha-205cbe7
    restart: unless-stopped
    ports:
      - "54323:3000"
    # Override the built-in healthcheck (it uses node fetch which fails inside the container).
    # The studio works fine; this just prevents a misleading "unhealthy" status.
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:3000/api/platform/profile || exit 1"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    depends_on:
      db:
        condition: service_healthy
    environment:
      STUDIO_PG_META_URL: http://meta:8080
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
      DEFAULT_ORGANIZATION_NAME: Colectivo
      DEFAULT_PROJECT_NAME: colectivo-dev
      SUPABASE_URL: http://kong:8000
      SUPABASE_PUBLIC_URL: ${PUBLIC_SUPABASE_URL:-http://localhost:8001}
      SUPABASE_ANON_KEY: ${PUBLIC_SUPABASE_ANON_KEY}
      SUPABASE_SERVICE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
      AUTH_JWT_SECRET: ${SUPABASE_JWT_SECRET}
      LOGFLARE_API_KEY: ""
      LOGFLARE_URL: http://analytics:4000
      NEXT_PUBLIC_ENABLE_LOGS: "true"
      NEXT_ANALYTICS_BACKEND_PROVIDER: postgres

  # ── pg-meta (metadata API for Studio) ───────────────────────────────────
  meta:
    image: supabase/postgres-meta:v0.83.2
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
    environment:
      PG_META_PORT: 8080
      PG_META_DB_HOST: db
      PG_META_DB_PORT: 5432
      PG_META_DB_NAME: postgres
      PG_META_DB_USER: supabase
      PG_META_DB_PASSWORD: ${POSTGRES_PASSWORD:-postgres}

  # ── Keycloak 24 ──────────────────────────────────────────────────────────
  keycloak:
    image: quay.io/keycloak/keycloak:24.0.5
    restart: unless-stopped
    ports:
      - "8080:8080"
    command: start-dev --import-realm
    environment:
      KC_DB: dev-file
      KEYCLOAK_ADMIN: ${KEYCLOAK_ADMIN:-admin}
      KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:-admin}
      KC_HTTP_PORT: 8080
      KC_HOSTNAME_STRICT: "false"
      KC_HOSTNAME_STRICT_HTTPS: "false"
    volumes:
      - keycloak-data:/opt/keycloak/data
      - ../keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro

volumes:
  db-data:
  storage-data:
  keycloak-data:
