# Production Enhancements - Docker Compose Override
# Use with: docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
#
# This file adds production-grade features:
# - Pre-built Docker image from GHCR (instead of local build)
# - Enhanced resource limits
# - Production-optimized settings
# - Secure Traefik configuration (disables insecure dashboard)
# - Docker API only through socket proxies: one for Traefik, one for the app

services:
  # ===========================================
  # APPLICATION (Production Image)
  # ===========================================
  # Override to use pre-built image from GitHub Container Registry
  # Default uses project name; override APP_IMAGE env var if needed
  app:
    image: ${APP_IMAGE:-ghcr.io/{{GITHUB_OWNER}}/{{PROJECT_NAME}}:latest}
    build: !reset null
    # On a server the app reads app.env, never .env. The deploy writes app.env
    # with only the keys the app uses (src/lib/deploy/app-runtime-env.js), while
    # .env stays the substitution source for every ${VAR} here, cloud and DNS
    # tokens included, which the app must never hold.
    env_file: !override
      - app.env
    environment:
      # Admin Infrastructure pages (service discovery + container logs) reach
      # the Docker Engine API through app-docker-proxy below, which answers
      # only the container list and container logs. The app image ships no
      # docker CLI and never mounts the socket, and it cannot reach Traefik's
      # proxy, so it can never inspect a container and read its env (db's
      # password, app-migrate's owner password, Traefik's DNS token).
      - DOCKER_API_PROXY=http://app-docker-proxy:2375
      # Fail closed: without the secret the app cannot sign a session.
      - BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET:?BETTER_AUTH_SECRET missing — vibecarbon create writes it to .env.local}
      # The app creates its super admin from these at startup, and a deploy
      # waits for it (src/server/auth/bootstrap-admin.ts). Required here so
      # a missing value fails deploy's preflight, before anything is created.
      - ADMIN_EMAIL=${ADMIN_EMAIL:?ADMIN_EMAIL missing — vibecarbon create writes it to .env.local}
      - ADMIN_PASSWORD=${ADMIN_PASSWORD:?ADMIN_PASSWORD missing — vibecarbon create writes it to .env.local}
      # The app's own database role's password (app_service). Required here
      # so a missing value fails deploy's preflight, before anything is
      # created; the owner password never reaches the app.
      - DB_PASSWORD=${APP_DB_PASSWORD:?APP_DB_PASSWORD missing, run vibecarbon upgrade to write it to .env}
    # vibecarbon-network for everything it serves and calls; app-docker-proxy
    # for its Docker API path. Traefik dials it on vibecarbon-network
    # (--providers.docker.network below).
    networks:
      - vibecarbon-network
      - app-docker-proxy
    labels:
      - "traefik.enable=true"
      # HTTP to HTTPS redirect (whole host)
      - "traefik.http.routers.app-http.rule=Host(`${DOMAIN:-localhost}`)"
      - "traefik.http.routers.app-http.priority=1"
      - "traefik.http.routers.app-http.entrypoints=web"
      - "traefik.http.routers.app-http.middlewares=redirect-to-https"
      - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
      # HTTPS router for the app at the bare apex (${DOMAIN}). The apex gets its
      # OWN single-domain cert via certresolver, validated over HTTP-01. It is
      # intentionally NOT in the default store cert (tls-default.yml), which
      # names traefik.${DOMAIN} plus the enabled grafana, n8n and metabase hosts.
      # The subdomain routers below use `tls=true` (no resolver) and serve that
      # default cert via SNI. To add your own subdomain, give its router the
      # label `traefik.http.routers.<name>.tls.certresolver=letsencrypt` and
      # Traefik issues it a certificate of its own.
      - "traefik.http.routers.app.rule=Host(`${DOMAIN:-localhost}`)"
      - "traefik.http.routers.app.priority=1"
      - "traefik.http.routers.app.entrypoints=websecure"
      - "traefik.http.routers.app.tls=true"
      - "traefik.http.routers.app.tls.certresolver=letsencrypt"
      - "traefik.http.services.app.loadbalancer.server.port=3000"
      # Deny public access to the ForwardAuth trust anchor. verify-role is
      # called by Traefik over the internal network (app:3000), never by the
      # browser, so blocking it on the public entrypoint costs nothing and
      # removes a role-check oracle. Higher priority than the app catch-all so
      # it wins; the sibling /api/_internal/services/* paths stay public
      # (browser admin panel, super_admin-gated in-handler).
      - "traefik.http.routers.app-internal-deny.rule=Host(`${DOMAIN:-localhost}`) && PathPrefix(`/api/_internal/verify-role`)"
      - "traefik.http.routers.app-internal-deny.priority=100"
      - "traefik.http.routers.app-internal-deny.entrypoints=websecure"
      - "traefik.http.routers.app-internal-deny.tls=true"
      - "traefik.http.routers.app-internal-deny.middlewares=internal-only@file"
      - "traefik.http.routers.app-internal-deny.service=app"

  # The migrate step runs the same pre-built image as the app.
  app-migrate:
    image: ${APP_IMAGE:-ghcr.io/{{GITHUB_OWNER}}/{{PROJECT_NAME}}:latest}
    build: !reset null

  # ===========================================
  # SECURITY HARDENING
  # ===========================================

  # Traefik's Docker socket proxy, for router discovery. POST:0 blocks every
  # mutation, but its GET sections (CONTAINERS/SERVICES/TASKS/NETWORKS) serve
  # container inspect, env included, so it sits on the internal socket-proxy
  # network that only traefik joins. Nothing else can resolve or reach it.
  docker-socket-proxy:
    image: ${DOCKER_SOCKET_PROXY_IMAGE:?DOCKER_SOCKET_PROXY_IMAGE missing, run vibecarbon upgrade to write it to .env}
    container_name: ${PROJECT_NAME}-socket-proxy
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    environment:
      # Only allow read-only access to specific endpoints
      CONTAINERS: 1
      SERVICES: 1
      TASKS: 1
      NETWORKS: 1
      # Deny dangerous operations
      POST: 0
      BUILD: 0
      COMMIT: 0
      CONFIGS: 0
      DISTRIBUTION: 0
      EXEC: 0
      GRPC: 0
      IMAGES: 0
      INFO: 0
      NODES: 0
      PLUGINS: 0
      SECRETS: 0
      SESSION: 0
      SWARM: 0
      SYSTEM: 0
      VOLUMES: 0
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - socket-proxy
    deploy:
      resources:
        limits:
          cpus: '0.25'
          memory: 128M

  # The app's Docker socket proxy: the same image with its own haproxy config
  # (configs below), which answers GET /containers/json (name, state, health:
  # the list carries no env), GET /containers/{id}/logs (the log viewer) and
  # GET /_ping (the Infrastructure page's proxy health row). Everything else
  # is refused with 403: inspect, top, stats, export, archive, attach, every
  # other section and every non-GET. Only the app shares its network.
  # Guarded by tests/integration/docker/compose-secret-reach.test.ts.
  app-docker-proxy:
    image: ${DOCKER_SOCKET_PROXY_IMAGE:?DOCKER_SOCKET_PROXY_IMAGE missing, run vibecarbon upgrade to write it to .env}
    container_name: ${PROJECT_NAME}-app-docker-proxy
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    configs:
      # The image's entrypoint renders this template to /tmp/haproxy.cfg and
      # runs haproxy on it, so this replaces the image's env-gated sections
      # whole.
      - source: app-docker-proxy-haproxy
        target: /usr/local/etc/haproxy/haproxy.cfg.template
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - app-docker-proxy
    deploy:
      resources:
        limits:
          cpus: '0.25'
          memory: 128M

  # Override Traefik to use socket proxy and secure dashboard behind ForwardAuth
  traefik:
    # Our ghcr mirror of the base file's tag (amd64, servers only): no Docker
    # Hub pull on a deploy. Same tag as carbon/docker-compose.yml, by census.
    image: ${TRAEFIK_IMAGE:?TRAEFIK_IMAGE missing, run vibecarbon upgrade to write it to .env}
    command:
      - "--api.dashboard=true"
      - "--providers.docker=true"
      - "--providers.docker.endpoint=tcp://docker-socket-proxy:2375"
      - "--providers.docker.exposedbydefault=false"
      # This project's containers only (see the base file), restated because
      # Compose replaces the whole command list.
      - "--providers.docker.constraints=Label(`com.docker.compose.project`,`${PROJECT_NAME}`)"
      # The app is on two networks; without this Traefik may dial it on the
      # internal app-docker-proxy one, which Traefik is not on. The deploy's
      # compose project is the /opt/${PROJECT_NAME} folder name, the same
      # assumption the constraint above makes.
      - "--providers.docker.network=${PROJECT_NAME}_vibecarbon-network"
      - "--providers.file.directory=/etc/traefik/dynamic"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.letsencrypt.acme.httpchallenge=true"
      - "--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web"
      - "--certificatesresolvers.letsencrypt.acme.email={{ADMIN_EMAIL}}"
      - "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
      # ACME_DISARMED_CA_SERVER first — compose-ha single-active-issuer
      # policy (src/lib/deploy/acme-role.js): set on the STANDBY node only;
      # empty/unset falls through to ACME_CA_SERVER or the prod default.
      - "--certificatesresolvers.letsencrypt.acme.caserver=${ACME_DISARMED_CA_SERVER:-${ACME_CA_SERVER:-https://acme-v02.api.letsencrypt.org/directory}}"
      - "--log.level=WARN"
    # Read by backup/tls-snapshot.sh (docker compose exec traefik printenv),
    # which saves acme.json to the backups bucket: the s3:// folder for this
    # environment's snapshots (TLS_SNAPSHOT_S3_PREFIX in .env, written by the
    # deploy) and the apex whose certificate is worth saving. Traefik itself
    # ignores both.
    environment:
      TLS_SNAPSHOT_S3_PREFIX: ${TLS_SNAPSHOT_S3_PREFIX:-}
      TLS_SNAPSHOT_DOMAIN: ${DOMAIN:-}
      # Go's own soft limit, kept about 10% under the memory limit below.
      GOMEMLIMIT: 460MiB
    ports:
      - "80:80"
      - "443:443"
    # !override drops the base file's raw /var/run/docker.sock mount: in
    # production Traefik reaches Docker only through docker-socket-proxy.
    volumes: !override
      - letsencrypt_data:/letsencrypt
      - ./volumes/traefik:/etc/traefik/dynamic:ro
    networks:
      - vibecarbon-network
      - socket-proxy
    depends_on:
      - docker-socket-proxy
    labels:
      - "traefik.enable=true"
      # HTTP to HTTPS redirect for dashboard subdomain
      - "traefik.http.routers.dashboard-http.rule=Host(`traefik.${DOMAIN}`)"
      - "traefik.http.routers.dashboard-http.entrypoints=web"
      - "traefik.http.routers.dashboard-http.middlewares=redirect-to-https"
      # HTTPS dashboard with super_admin auth — cert from default store
      - "traefik.http.routers.dashboard.entrypoints=websecure"
      - "traefik.http.routers.dashboard.tls=true"
      - "traefik.http.routers.dashboard.middlewares=super-admin-auth@file"
    # No CPU limit, on purpose. Every request and every TLS handshake passes
    # through Traefik, so a limit turns one noisy client into an outage for the
    # whole site: at 0.5 CPU, about 220 new TLS connections a second were
    # throttled in 4,808 of 4,811 periods, the accept queue filled and all HTTPS
    # hung. Without one, Traefik shares the CPU with the app and the db.
    #
    # The memory limit is room for a connection flood, not for traffic: Traefik
    # peaks around 56 MB serving 2,000 new TLS connections a second, and a limit
    # reserves nothing. Each held connection costs about 40 KB, so 512 MB holds
    # about 11,900 before the kernel kills Traefik, where 256 MB held 4,600.
    # GOMEMLIMIT is what makes Go collect harder as it nears the limit.
    # Guarded by tests/unit/template/compose-cpu-limits.test.ts.
    deploy:
      resources:
        limits:
          memory: 512M

  # ===========================================
  # PRODUCTION OPTIMIZATIONS
  # ===========================================

  # No CPU or memory limits on the db, on purpose. Docker refuses a `cpus`
  # figure above the host's CPU count, so any limit over 1.0 stops
  # `docker compose up` on a 1-vCPU server, and one fixed memory figure cannot
  # fit both a 1 GB and a 16 GB server: too high it means nothing, too low the
  # kernel kills postgres inside its own cgroup. Postgres bounds its own
  # memory (shared_buffers and max_connections, docker/postgres-walg/
  # postgresql.conf and the base file's `-c` flags). Keep any `cpus` you add
  # elsewhere at 1.0 or below (tests/unit/template/compose-cpu-limits.test.ts).
  db:
    # Docker checks every second during the start period only, then returns
    # to the base file's `interval`. Dependents (app, app-migrate) start
    # within a second of the db being ready. Needs Docker Engine 25 or newer,
    # which servers have; the base file omits it because Compose 2.18 rejects
    # the key and Compose 2.24-2.29 on Engine 24 refuse to start with it.
    healthcheck:
      start_interval: 1s
    environment:
      # Required (`:?`) so deploy's preflight refuses a .env without the
      # database password before anything is created (findMissingRequiredEnv
      # in src/lib/project.js reads these markers).
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD missing — vibecarbon create writes it to .env.local}
    # The wal-g role (primary or standby), written by the CLI on the host
    # before every start and on a failover. Bound as a DIRECTORY: the CLI
    # replaces the file atomically (a new inode), which a single-file bind
    # would never show the container. Read-only: only the host writes it.
    volumes:
      - ./.vibecarbon-role:/var/lib/vibecarbon/role:ro,Z

volumes:
  letsencrypt_data:

networks:
  # Traefik and its socket proxy. Internal: no route out, no other member.
  socket-proxy:
    internal: true
  # The app and its socket proxy. Internal: no route out, no other member.
  app-docker-proxy:
    internal: true

configs:
  # app-docker-proxy's whole haproxy config. Paths are matched raw (no URL
  # decoding) against anchored patterns whose id class has no `/` or `%`, so
  # `..` segments and encoded slashes cannot reach another endpoint. The
  # version prefix is optional because the app calls unversioned paths
  # (src/server/lib/docker-api.ts). `$$` is Compose's escape for a literal `$`.
  app-docker-proxy-haproxy:
    content: |
      global
          log stdout format raw daemon info
          maxconn 1000

      defaults
          mode http
          log global
          option httplog
          option dontlognull
          option http-server-close
          timeout http-request 10s
          timeout connect 10s
          timeout client 10m
          timeout server 10m
          errorfile 403 /usr/local/etc/haproxy/errors/403.http

      backend dockerbackend
          server dockersocket /var/run/docker.sock

      frontend dockerfrontend
          bind :2375
          http-request deny unless METH_GET
          http-request allow if { path -m reg ^(/v[0-9.]+)?/containers/json$$ }
          http-request allow if { path -m reg ^(/v[0-9.]+)?/containers/[a-zA-Z0-9_.-]+/logs$$ }
          http-request allow if { path -m reg ^(/v[0-9.]+)?/_ping$$ }
          http-request deny
          default_backend dockerbackend
