diff --git a/.env.dev b/.env.dev index dc0f60d..c936d30 100644 --- a/.env.dev +++ b/.env.dev @@ -119,12 +119,13 @@ LIQUIDSOAP_HARBOR_PORT=8001 # --- TLS / identity ---------------------------------------------------------- # DOMAIN is also the auth cookie's domain, so it must be the host the browser -# is on. certbot is disabled in dev, so EMAIL is never used. +# is on. Nothing reads EMAIL any more (it was certbot's). DOMAIN=localhost EMAIL=dev@example.invalid # --- Cloudflare Tunnel ------------------------------------------------------- -# cloudflared is disabled in dev and certbot with it. +# cloudflared is disabled in dev, and dev's Caddy sites use `tls internal`, +# so neither token is ever used. CLOUDFLARE_TUNNEL_TOKEN=dev-dummy-tunnel-token CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token diff --git a/.env.example b/.env.example index 17710f7..6379352 100644 --- a/.env.example +++ b/.env.example @@ -7,8 +7,7 @@ # it parses the file, before any container exists. This is how container # names and published ports are built. # 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment -# variables inside that container. nginx, backend, db, icecast2, -# certbot and gitea all do this. +# variables inside that container. backend, db and icecast2 do this. # The `python` and `jobs` services deliberately do neither wholesale — each # uses an explicit `environment:` allow-list, so neither sees the site's # database password, the JWT secret, or any key it does not use. @@ -54,7 +53,7 @@ POSTGRES_TRACKER_USER=tracker POSTGRES_TRACKER_PASSWORD= # --- Gitea ------------------------------------------------------------------- -# GITEA_HOST is the container name AND the nginx upstream host. +# GITEA_HOST is the container name AND the Caddy upstream host. # The three secrets below are passed as GITEA__section__KEY overrides so the # committed app.ini.template can keep those fields blank. Generate each as a # long random hex string. @@ -125,14 +124,10 @@ ADZUNA_APP_ID= ADZUNA_APP_KEY= REED_API_KEY= -# --- Services that nginx substitutes but no longer runs ----------------------- -# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no -# compose service uses them today. Harmless if blank. - # --- SilverBullet (notes) --------------------------------------------------- # Two instances over the same vault: the admin-only editor at /sb/, and the # public read-only notes site at /notes/ (which replaced Quartz). All four -# default in nginx/entrypoint.sh and docker-compose.yml, so they can be left +# default in docker-compose.yml (the caddy service's list), so they can be left # blank. SILVERBULLET_HOST=silverbullet SILVERBULLET_PORT=3000 @@ -142,8 +137,8 @@ SILVERBULLET_PUBLIC_PORT=3000 SILVERBULLET_GIT_INTERVAL= # --- Go backend -------------------------------------------------------------- -# BACKEND_HOST is the container name and the nginx upstream. -# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then +# BACKEND_HOST is the container name and the Caddy upstream. +# BACKEND_ENDPOINT is the public URL prefix Caddy mounts the API at and then # strips; the Vue app's GraphQL client assumes /api. # BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs # everyone out. @@ -173,7 +168,7 @@ SPOTIFY_AUTH_STATE= # ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast # with it, and a live-broadcasting client authenticates to the liquidsoap # harbor port with it. Anyone holding it can take over the stream. -# LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host. +# LIQUIDSOAP_HARBOR_PORT is the only non-Caddy port published to the host. ICECAST_SOURCE_PASSWORD= ICECAST_RELAY_PASSWORD= ICECAST_ADMIN_USER= @@ -185,10 +180,11 @@ LIQUIDSOAP_HARBOR_MOUNT=/live LIQUIDSOAP_HARBOR_PORT=8001 # --- TLS / identity ---------------------------------------------------------- -# DOMAIN is the APEX domain with no scheme and no www; certbot requests both -# it and www.DOMAIN on one certificate, and nginx canonicalises to www. -# EMAIL is the Let's Encrypt account address for certbot. Caddy registers -# its ACME account without one (Let's Encrypt no longer sends expiry notices). +# DOMAIN is the APEX domain with no scheme and no www; Caddy gets a +# certificate for it and for www.DOMAIN, and canonicalises to www. +# EMAIL was certbot's Let's Encrypt account address. Nothing reads it since +# the move to Caddy, which registers its ACME account without one; it stays +# for the nginx/certbot rollback (DEPLOYMENT.md §7). DOMAIN= EMAIL= @@ -199,13 +195,12 @@ EMAIL= # dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves # the container restarting with an error and the site reachable directly. CLOUDFLARE_TUNNEL_TOKEN= -# Cloudflare API token for the DNS-01 challenge (My Profile -> API Tokens -> -# Create Token -> "Edit zone DNS", limited to this zone). Set, the certificate -# renews without any inbound port, so the router's 80/443 forwards can close. -# certbot: blank falls back to HTTP-01 on port 80. -# Caddy (caddy/sites/prod.caddy) has no fallback and also needs Zone -> Zone -# -> Read on the same zone, so add that permission to the token. Changing it -# needs `docker compose up -d caddy`. +# Cloudflare API token for Caddy's DNS-01 challenge (caddy/sites/prod.caddy): +# My Profile -> API Tokens -> Create Token -> "Edit zone DNS", limited to this +# zone, then add Zone -> Zone -> Read on the same zone (the template only has +# DNS -> Edit). Certificates are issued and renewed with no inbound port, so +# the router forwards nothing. Required in production: Caddy has no HTTP +# challenge to fall back to. Changing it needs `docker compose up -d caddy`. CLOUDFLARE_DNS_API_TOKEN= # --- Third-party API keys (backend) ------------------------------------------ @@ -286,14 +281,14 @@ TRACKER_TZ=Europe/London # --- Receipt printer (/receipt/) --------------------------------------------- # Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi, -# which reaches the printer over the home LAN, and nginx proxies to it over +# which reaches the printer over the home LAN, and Caddy proxies to it over # Tailscale. # host:port of that server, by Tailscale IP. Blank points nowhere and # /receipt/ answers "offline". RECEIPT_WEB_UPSTREAM=100.107.152.119:8765 -# Shared secret nginx adds as X-Receipt-Token; the same value as +# Shared secret Caddy adds as X-Receipt-Token; the same value as # RECEIPT_WEB_TOKEN in stppi's ~/.config/receipt-web.env. Generate with -# `openssl rand -hex 32`. Changing it needs `docker compose up -d nginx`. +# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`. RECEIPT_WEB_TOKEN= # TfL Unified API key (500 req/min); used by the Python hotel finder @@ -318,7 +313,7 @@ S3_SECRET_ACCESS_KEY= # Blank keeps uploads on disk. Set to http://garage:3900 (after running # garage/bootstrap.sh) to store new public uploads in the bucket; recreate the # backend after changing it. If a write to Garage fails the backend logs it and -# writes to disk instead, and nginx serves the file from there. +# writes to disk instead, and Caddy serves the file from there. S3_ENDPOINT= # Optional; these defaults match garage.toml and bootstrap.sh. S3_REGION=garage diff --git a/.gitea/workflows/renovate.yaml b/.gitea/workflows/renovate.yaml index 50be26b..eb2215a 100644 --- a/.gitea/workflows/renovate.yaml +++ b/.gitea/workflows/renovate.yaml @@ -8,7 +8,7 @@ # The same host-mode act_runner as deploy.yaml, so (as there) nothing but # git and docker is assumed on the host: Renovate runs from its own image. # --network host lets the container reach Gitea on localhost:3000, the port -# the runner itself registers against, so this keeps working while nginx or +# the runner itself registers against, so this keeps working while Caddy or # the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same reason: # without it Renovate clones from the URL Gitea advertises, which is # ROOT_URL — the public https://…/gitea/ path. diff --git a/CLAUDE.md b/CLAUDE.md index 2522d40..0f92a9c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co make check ``` -Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it. +Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, `docker compose config` for both compose files, and the Caddy image build, which validates `caddy/` for both modes. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`, `check-caddy`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it. ### Full stack (dev mode, HTTP only) @@ -19,7 +19,7 @@ cp .env.dev .env docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build ``` -`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`. +`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. Visit `http://localhost`. ### Full stack (production, HTTPS) @@ -57,15 +57,15 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun **Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies. -**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode). +**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served by Caddy (production) or proxied to Vite dev server (dev mode). -**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes"). +**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Caddy proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and Caddy 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes"). -**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`. +**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; Caddy redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`. -**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7. +**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). Caddy serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7. -**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public. +**Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit `) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated at the edge because a crawler swarm hammers them; the branch views stay public. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. `nginx/` and `certbot/` are the pre-cutover edge, kept only as the rollback. ## Backend Structure @@ -96,7 +96,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun - **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded). - **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`. - **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`. -- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. nginx's *permission gate* (`set $auth_permission ; auth_request /internal/auth/validate;`, see `nginx/nginx_routes.conf.template`) asks `GET /auth/validate/`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its location from the admin gate to the permission gate. `/auth/validate-admin` and the admin gate are unchanged. +- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. Caddy's *permission gate* (`import permission_gate ` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) asks `GET /auth/validate/`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its route from `import admin_gate` to `import permission_gate `. `/auth/validate-admin` and the admin gate are unchanged. - **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts. - **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor. - **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API. @@ -114,7 +114,7 @@ Each area has its own README with the detail that doesn't belong here: ## Conventions -- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them. +- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, the edge's route order). Preserve these when editing; if you change the behaviour they describe, update them. - **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating. - **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output. - **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 91748a8..b038849 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -2,18 +2,18 @@ How this site is put together and how to operate it. Application code is documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only -— compose, nginx, TLS, the runner, and the runbook. +— compose, the Caddy edge, TLS, the runner, and the runbook. Everything runs on a single host, `stpvm` (an x86-64 Ubuntu VM on Proxmox, reached over Tailscale as `stpvm.tailf20278.ts.net`; until 2026-10-15 it was the Raspberry Pi `stppi`), as Docker containers on one bridge -network, behind one nginx. +network, behind one Caddy (nginx and certbot until 2026-11-17). --- ## 1. Service topology -Only three things are reachable from outside the host: nginx on 80/443, Gitea on +Only three things are reachable from outside the host: Caddy on 80/443, Gitea on 3000/2222, and the liquidsoap harbor port. Everything else is internal. Web traffic can also come in through the Cloudflare tunnel (`cloudflared`), which dials out and publishes no port; see "Cloudflare Tunnel" in §3. @@ -24,7 +24,7 @@ dials out and publishes no port; see "Cloudflare Tunnel" in §3. :80 :443| :3000 / :2222 :8001 v v v +--------------+ +--------+ +-------------+ - | nginx | | gitea | | liquidsoap | + | caddy | | gitea | | liquidsoap | | (TLS, SPA, | | (git + | | harbor | | reverse | | CI) | | (live DJ) | | proxy) | +--------+ +------+------+ @@ -45,74 +45,86 @@ backend icecast2 gitea sb sb-pub python | | | db | postgres:16 +------+ (app database + gitea database) - vue one-shot build container -> writes vue_dist volume -> nginx serves it - certbot no ports; shares ./certbot/conf and ./certbot/www with nginx + vue one-shot build container -> writes vue_dist volume -> caddy serves it ``` ### Who listens where | Service | Container name | Internal port | Public route | Published to host | | --------------------------------------------- | ----------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------- | -| nginx | `nginx` | 80, 443 | — | **80, 443** | +| caddy (the edge) | `caddy` | 80, 443 (fixed IP `172.28.255.251`) | everything below | **80, 443** | | backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no | | db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no | | silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no | | silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no | | silverbullet-git | n/a | n/a | none (timer loop) | no | | python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no | -| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by nginx `auth_request`; capture API and userscript public, bearer-token) | no | -| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by nginx `auth_request`; `/api/v1/` bearer/app-checked) | no | +| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by Caddy `forward_auth`; capture API and userscript public, bearer-token) | no | +| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by Caddy `forward_auth`; `/api/v1/` bearer/app-checked) | no | | icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** | | gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** | | vue | `vue` | 5173 (dev only) | `/` (dev only) | no | -| certbot | `certbot` | — | — | no | -| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) | -| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no | -| receipt printer (`receipt serve`, adamf/receipt_maker) | — (runs on **stppi**, not in this stack) | 8765 on stppi's Tailscale IP (`RECEIPT_WEB_UPSTREAM`) | `/receipt/`, prefix stripped (permission-gated on `receipt` by nginx `auth_request`; nginx adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no | +| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of Caddy, via Cloudflare | no (outbound only) | +| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by Caddy `forward_auth`; reads the Docker socket) | no | +| receipt printer (`receipt serve`, adamf/receipt_maker) | — (runs on **stppi**, not in this stack) | 8765 on stppi's Tailscale IP (`RECEIPT_WEB_UPSTREAM`) | `/receipt/`, prefix stripped (permission-gated on `receipt` by Caddy `forward_auth`; Caddy adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no | | traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no | -| autoheal (restarts unhealthy nginx) | `autoheal` | — (no network) | none; reads the Docker socket | no | +| autoheal (restarts unhealthy caddy) | `autoheal` | — (no network) | none; reads the Docker socket | no | | garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no | -| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by nginx `auth_request`) | no | +| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by Caddy `forward_auth`) | no | -Container names come from `.env`, and nginx builds its upstreams from the same -variables. **Renaming a `*_HOST` value renames the container and repoints nginx -in one step — never change one without the other.** +Container names come from `.env`, and Caddy builds its upstreams from the same +variables (passed through the caddy service's `environment:` list). **Renaming +a `*_HOST` value renames the container and repoints Caddy in one step — never +change one without the other.** -### Things nginx does that are easy to miss +### Things Caddy does that are easy to miss -- **Canonical host.** `http://` → `https://`, and apex → `www`. The SPA, the - cookies and the CORS rules all assume `www.`. -- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/py` are stripped - — but `/sb/` and `/notes/` deliberately are NOT: SilverBullet is told its own base path via - `SB_URL_PREFIX` and builds its service-worker scope from it, so stripping the - prefix serves a blank page with nothing in the log. - by a `rewrite ... break` before proxying; each upstream serves from `/`. -- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with - `resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a - backend down (502s until it appears) instead of refusing to start. +The config is `caddy/Caddyfile` (global options and snippets), `caddy/routes.caddy` +(every proxied route, shared by dev and production) and `caddy/sites/` +(`prod.caddy`, `dev.caddy`). Each file's header explains it. + +- **Canonical host.** `http://` → `https://www.`, and apex → `www`. The + SPA, the cookies and the CORS rules all assume `www.`. +- **Route order is literal.** `routes.caddy` is one ordered list inside a + `route` block, and the first matching `handle` wins: denials first, then each + carve-out ahead of the gated prefix it is carved out of. A new route goes in + the right place in that list, not just anywhere. +- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/py`, `/tracker` and + `/receipt` are stripped with `uri strip_prefix` before proxying; each of + those upstreams serves from `/`. `/sb/`, `/notes/`, `/jobs/`, `/usaco/`, + `/dozzle/` and `/garage/` deliberately are NOT: those apps are told their own + base path (SilverBullet's `SB_URL_PREFIX` builds its service-worker scope from + it, so stripping the prefix serves a blank page with nothing in the log). +- **Upstreams resolve when dialled.** Caddy starts with any upstream container + missing and answers 502 until it appears; it never refuses to start over one. - **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the branch views stay public) are - protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure - redirects to the SPA login. Most of these services have no auth of their own at that path; the + protected by `forward_auth` to the backend's `/auth/validate-admin` (the + `admin_gate` snippet); a 401/403 redirects to the SPA login. Most of these services have no auth of their own at that path; the job and activity trackers also check the session themselves. Their carve-outs, which a session - cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps: + cookie never reaches, stay public at the edge and are guarded by bearer tokens in the apps: `/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`. -- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead, which also lets in a + Paths are matched cleaned and case-insensitively, so `/SB/` or `/uploads/x/../private/y` + land on the gate too. With the backend down every gated path answers 502: it fails closed. +- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead (the + `permission_gate` snippet), which also lets in a non-admin account granted `receipt` in the admin panel's Manage Users tab. Not signed in redirects to the login; signed in without the grant redirects to `/no-access`. To let a friend print: create their user (admin panel → User), then tick "Receipt printer" for them under Manage Users. Revoking is the same tick, and applies on their next request. - **Public notes privacy boundary.** `/notes/` is public, and the only thing keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of - nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its + `path_regexp` deny rules at the top of `caddy/routes.caddy`. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its file _list_; direct `/.fs/` fetches and server-rendered page URLs still serve them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without - adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the - comment above `location /notes/` in `nginx_routes.conf.template`. + adding it to the deny regex publishes it. `caddy/edge_test.sh` checks these + denials against a running edge. - **Uploads: the bucket first, then disk.** `/uploads/` is fetched from Garage's website endpoint and, if Garage has no such file or is down, from - the shared `uploads` volume (`@uploads_disk`). Both paths add `nosniff`, + the shared `uploads` volume (the `uploads_disk` snippet, which hands the + request to a loopback-only site inside the container so that 206 and 304 + answers keep their status). Both paths add `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so user-supplied files cannot execute anything on our origin. The bucket is the source of truth; a Garage outage only affects files that exist nowhere else. See "Garage" @@ -130,14 +142,12 @@ docker compose up --build ``` 1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected). -2. `nginx` starts, runs `nginx/entrypoint.sh`, which: - - is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`; - - renders `nginx.conf.template` if the cert is there, else - `nginx_setup.conf.template`; - - polls up to 120s for `index.html` to appear in `vue_dist`, then starts - nginx either way. -3. `certbot` obtains or confirms the certificate, then loops renewing. -4. Everything else comes up in parallel; `depends_on` here is the plain list +2. `caddy` starts with the image's own command (`caddy run` on + `/etc/caddy/Caddyfile`). `CADDY_SITE` is unset, so it loads + `sites/prod.caddy`. It serves at once: the SPA is whatever is in `vue_dist`, + and upstreams that are not up yet are 502s. If `./caddy/data` holds no + certificate it obtains one first (§3), and TLS fails for those seconds. +3. Everything else comes up in parallel; `depends_on` here is the plain list form, which waits only for _start_, not readiness. On the host this is triggered automatically by `.gitea/workflows/deploy.yaml`, @@ -145,9 +155,10 @@ which has two jobs: - **`test`** runs on every push to any branch. It exports the pushed commit (never the deploy checkout) and runs the backend's `go vet` + `go test` in - `golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build is - not repeated here: the image build in the deploy step does it, and a failed - build leaves the old containers running. + `golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build and + the Caddy config check are not repeated here: the image builds in the deploy + step do them (`caddy/Dockerfile` runs `caddy validate`), and a failed build + leaves the old containers running. - **`deploy`** runs only on `main`, only after `test` passes, and only if the tested commit is still the tip of `main` (so an older run cannot deploy a newer, untested commit). It fetches over `ssh://git@localhost:2222`, @@ -180,21 +191,24 @@ rather than be passed with `--env-file`, because several services read volume created with them, and as in production only `POSTGRES_DB` is created automatically. -The override layer changes five services and disables one: +The override layer changes these services and disables `cloudflared`: - **vue** — `npm run dev` instead of a one-shot build; `./vue` is bind-mounted for hot reload, with an anonymous-volume mask on `/app/node_modules` so the image's installed deps are not hidden by the bind mount. You don't need `node_modules` on the host. -- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a - `CN=localhost` certificate (once, kept in `certbot/conf`) and render - `nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and - `:443` serve the whole site, no HSTS, no HTTP→HTTPS redirect. +- **caddy** — `CADDY_SITE=dev`, which loads `caddy/sites/dev.caddy`: `/` + proxies to the Vite dev server, both `:80` and `:443` serve the whole site, + no HSTS or other security headers, no HTTP→HTTPS redirect. HTTPS uses a + certificate from Caddy's own local CA (kept in `./caddy/data`), which the + browser warns about. Every proxied route, gate and limit is the same + `routes.caddy` as production. - **backend** — `DEV_MODE`, GraphQL playground and introspection on, a localhost Spotify redirect URI, and **`SEED_DB=true`**. - **python** — `uvicorn --reload` with `python/app` bind-mounted. -- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt - cannot validate localhost anyway. +- **jobs** — seeded, with the GraphQL playground on. +- **cloudflared** — put in the `disabled` profile, so it never starts: a dev + stack must never join the production tunnel. Visit `http://localhost`. @@ -207,82 +221,78 @@ Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies --- -## 3. TLS: first issuance and renewal +## 3. TLS: certificates -### The chicken-and-egg +Caddy obtains and renews its own certificates (`prod_tls` in +`caddy/sites/prod.caddy`): one per name, `` and `www.`, from +Let's Encrypt over **DNS-01**. It creates the `_acme-challenge` TXT record +through the Cloudflare API with `CLOUDFLARE_DNS_API_TOKEN`, so nothing has to +reach the host: the router forwards no ports. The certificates, their keys and +the ACME account live in `./caddy/data` (gitignored, private key material). -The production nginx config references -`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that -file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port 80. On a brand-new host neither can go first. +**First run on a new host or domain.** Set `CLOUDFLARE_DNS_API_TOKEN` (the +token needs **Zone → Zone → Read** and **Zone → DNS → Edit** on this zone; see +`.env.example`), then `docker compose up -d`. Caddy serves straight away and +obtains both certificates in the background, usually within seconds; until +they land the TLS handshake fails, so the tunnel answers 502. There is no +bootstrap config and nothing to restart. -`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no -upstreams, nothing that can fail to load. It serves -`/.well-known/acme-challenge/` from `/var/www/certbot` and 404s everything else, -so a half-configured site is never partially exposed. +``` +docker compose logs caddy | grep -E 'obtaining certificate|certificate obtained|error' +``` -**First run on a new domain:** +**Renewal** happens in-process when a third of a certificate's lifetime is +left, and the new one is served immediately, with no reload. A failed attempt +is retried with backoff and logged. To see what is being served: -1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx -config.` -2. certbot runs `certbot certonly --webroot` and writes the certificate into - `./certbot/conf` (bind-mounted into both containers — that sharing is what - makes the whole thing work). -3. **`docker compose restart nginx`.** This step is manual. Nothing watches the - cert directory. On restart the entrypoint re-checks, finds the cert, and - renders the production config. +``` +for n in www.$DOMAIN $DOMAIN; do echo | openssl s_client -connect 127.0.0.1:443 -servername $n 2>/dev/null | openssl x509 -noout -subject -enddate; done +``` -### Renewal +**`resolvers 1.1.1.1 1.0.0.1`** in `prod_tls` matters: on `app-network` +`` is an alias for the caddy container itself, so Docker's DNS would +answer the plugin's zone lookup and the order would fail with "expected 1 +zone, got 0". -`certbot/entrypoint.sh` loops `certbot renew` every 12 hours. Renewal is a no-op -until the cert is inside its 30-day window, so this is well within Let's Encrypt -rate limits — it just means the window is checked twice a day. Certs are valid 90 -days, so renewal lands around day 60. +**Losing `./caddy/data`** costs only a re-issue on the next start. Let's +Encrypt allows five certificates for the same name a week, so do not make a +habit of it. -**Validation method.** With `CLOUDFLARE_DNS_API_TOKEN` set, certbot proves -control of the domain by creating a `_acme-challenge` TXT record through the -Cloudflare API (DNS-01), so renewal needs no inbound port at all. That is -what lets the router's 80/443 forwards close behind the tunnel. Without the -token it uses the webroot (HTTP-01) on port 80, as it always did. Switching -either way takes effect at the next renewal; see `certbot/entrypoint.sh`. - -**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container -cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the -certificate at startup and holds it in memory, so **a renewed certificate is not -served until nginx is reloaded or restarted.** In practice pushes to `main` -recreate nginx often enough to hide this. If the site ever serves an expired -cert, `docker compose restart nginx` is the fix. See proposal 1 in §8. +Until 2026-11-17 this was certbot plus a bootstrap nginx config, a reload +sentinel and a watcher loop. `certbot/` and its `./certbot/conf` stay on the +host as the rollback (§7); that certificate expires on 2027-01-20. ### Cloudflare Tunnel The `cloudflared` container holds an outbound connection to Cloudflare and -forwards requests for the site's hostnames down it to nginx. It is a +forwards requests for the site's hostnames down it to Caddy. It is a _remotely managed_ tunnel: the only thing in this repo is the token (`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and origin settings live in the dashboard. **Origin: `https://www.`, the site's own name.** Cloudflare terminates the visitor's TLS at its edge, and cloudflared opens a second TLS -connection to nginx. That is deliberate. Pointed at `http://nginx:80`, the +connection to Caddy. That is deliberate. Pointed at `http://caddy:80`, the tunnel would hit the HTTP→HTTPS redirect and loop. Going to :443 keeps every redirect, security header and the `X-Forwarded-Proto: https` the backend's -Secure cookies depend on, and needs no nginx change. +Secure cookies depend on, and needs no change to the edge. -The origin is the public name, not `nginx`, because nginx carries `` +The origin is the public name, not `caddy`, because Caddy carries `` and `www.` as network aliases on `app-network` (`docker-compose.yml`). -Inside the network those names resolve to the nginx container, so the hop +Inside the network those names resolve to the caddy container, so the hop never leaves the host, and cloudflared verifies the Let's Encrypt certificate -against a name it covers. `https://nginx` would fail that check and need No -TLS Verify. The flip side: **an expired certificate now takes the tunnel down +against a name it covers. `https://caddy` would fail that check and need No +TLS Verify. The flip side: **an expired certificate takes the tunnel down with a 502**, which is why renewal over DNS-01 (step 5) matters. -An alias only exists while nginx is running, so cloudflared also pins both -names to nginx's fixed address (`172.28.255.251`) with `extra_hosts`. Without -that, while nginx is stopped for a deploy or the weekly maintenance, the name +An alias only exists while Caddy is running, so cloudflared also pins both +names to Caddy's fixed address (`172.28.255.251`) with `extra_hosts`. Without +that, while Caddy is stopped for a deploy or the weekly maintenance, the name falls through to public DNS, resolves to Cloudflare itself, and visitors see Cloudflare error 1000 instead of a 502. The aliases have a side effect for anything else on `app-network` that uses -the public name for a port nginx does not serve. `silverbullet-git` pushes to +the public name for a port Caddy does not serve. `silverbullet-git` pushes to Gitea's SSH on `:2222`, so it maps `` to the host gateway instead, where Gitea publishes that port. @@ -297,27 +307,28 @@ Setup, once: 4. Add a public hostname per name, each with service `HTTPS` and its own name as the URL, and no other settings: - `www.` → `https://www.`: the site. - - `` → `https://`: nginx redirects it to www, and it serves Gitea's registry + - `` → `https://`: Caddy redirects it to www, and it serves Gitea's registry at `/v2/`. Creating each hostname replaces the existing A record for that name with a CNAME to the tunnel. **That is the cutover**: until then the tunnel carries nothing. 5. Create a Cloudflare API token (My Profile → API Tokens → "Edit zone - DNS", this zone only) and set it as `CLOUDFLARE_DNS_API_TOKEN`. certbot - then renews over DNS-01 (see Renewal above) and needs no inbound port. -6. On the host, point the apex at nginx locally (next section). + DNS", this zone only), add **Zone → Zone → Read** to it, and set it as + `CLOUDFLARE_DNS_API_TOKEN`. Caddy then obtains and renews over DNS-01 + (§3) and needs no inbound port. +6. On the host, point the apex at Caddy locally (next section). 7. Close the router's 80 and 443 forwards. Once 5 and 6 are done nothing depends on them. #### What the tunnel does not carry, and where it goes instead -- **Certificate renewal.** Over DNS-01 with `CLOUDFLARE_DNS_API_TOKEN` set; - without it certbot falls back to HTTP-01, which needs port 80 forwarded. - The certificate matters behind the tunnel: cloudflared verifies it, as - do the registry path below and any direct LAN access. A fresh machine with no - certificate at all boots the setup config (§3), which serves nothing over - 443, so the tunnel carries nothing until the first issuance. +- **Certificate renewal.** Over DNS-01 only: Caddy is given no HTTP + challenge to fall back to, so without a working `CLOUDFLARE_DNS_API_TOKEN` + nothing is issued or renewed. The certificate matters behind the tunnel: + cloudflared verifies it, as do the registry path below and any direct LAN + access. A fresh machine with no certificate serves nothing over 443 until + the first issuance (§3), so the tunnel carries nothing for those seconds. - **Registry pushes and pulls on the host.** Cloudflare caps request bodies at 100 MB on the free plan, so a push of a larger image layer through the tunnel fails. The runner on the host pushes to `/adamf/...` and the @@ -328,7 +339,7 @@ Setup, once: 127.0.0.1 ``` - so registry traffic goes straight to nginx on :443, with the real + so registry traffic goes straight to Caddy on :443, with the real certificate, and never leaves the host. (Without it the name resolves to Cloudflare once DNS moves there.) Only the apex: www stays on Cloudflare for anything on the host that wants the public site. Pushing from another machine still goes @@ -364,24 +375,25 @@ Setup, once: | `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) | | `garage_data` | The bucket's object bytes | Every upload stored in Garage | | `vue_dist` | The built SPA | Nothing — rebuilt on next deploy | +| `caddy_config` | Caddy's autosaved JSON config | Nothing — rewritten on every start | **Bind mounts** — live in the repo checkout on the host, survive everything short of deleting the directory: | Path | Holds | Notes | | --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. | -| `./certbot/www` | ACME challenge webroot | Transient by nature | +| `./caddy/data` | Caddy's TLS certificates, **private keys** and ACME account | Gitignored. Never commit. Losing it means a re-issue on the next start (§3). | +| `./certbot/conf` | The old certbot certificate and keys | Unused since 2026-11-17; kept as the rollback until it is cleaned up (§7). | | `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. | | `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. | | `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data | | `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea | -| `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") | +| `./logs` | Backend logs (`go.log`); Caddy's JSON request-body log in `logs/caddy/payloads.log` | Caddy rotates the payload log itself (50 MiB, five kept). `logs/nginx/` is nginx's, finished. | | `./icecast2/fallback_music` | Radio fallback MP3s | Copied to the host by hand, not git | | `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public | **Ephemeral:** anything else inside a container. Notably the Vue build, the -rendered nginx/icecast configs, and the Gitea runner's downloaded binary +rendered icecast config, and the Gitea runner's downloaded binary are all regenerated. --- @@ -396,11 +408,11 @@ Two distinct mechanisms read it, and services use both: - **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse time. Builds container names and published ports. - **`env_file: ./.env`** — injects the whole file into the container. Used by - nginx, backend, db, icecast2, certbot. + backend, db and icecast2. `gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own convention for overriding `app.ini` keys), and `python` receives an explicit -allow-list, so it never sees the database password or any API key other than +allow-list (as do `jobs`, `caddy` and the rest), so it never sees the database password or any API key other than the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`, which picks the model). The Python service makes the site's one Claude call (the rowing photo reader); the `jobs` container @@ -414,7 +426,7 @@ to be added to its allow-list as well as `~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's `.env` (often with dev values) never reaches production by accident. -An unset variable is not an error: `envsubst` renders it as an empty string, +An unset variable is not an error: compose substitutes an empty string, which for a password field means _no password_. After editing `.env`, confirm with `docker compose config`. @@ -422,40 +434,48 @@ with `docker compose config`. Edit `.env` on the host, and recreate only the services that read the variable: `docker compose up -d `. A plain `up -d` would also restart Postgres, -since nginx, db, icecast2 and certbot load the whole file. +since backend, db and icecast2 load the whole file. --- ## 6. Rate limits -Defined once per config in the `http` block, applied per location. Keyed on -`$binary_remote_addr` — the client IP in packed form, so each entry is ~64 bytes -and a `10m` zone holds roughly 160k IPs. `10m` is a safe round number, not a -tuned value. +The `rate_limit` directive comes from the `mholt/caddy-ratelimit` plugin +(compiled in by `caddy/Dockerfile`) and is applied per route through the +`limit` snippet: `import limit `. Each zone is a +**sliding window** keyed on `{client_ip}`: at most `` requests per +`` per IP, then the request is refused. There is no separate burst, so +the numbers are nginx's old rates, which keeps the sustained rates the same; +the instant allowance comes out close to nginx's burst + 1. -`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one -request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead -of that drip, and `nodelay` (used everywhere here) serves those N immediately. -So the effective behaviour is _"N instant requests, then throttled to the drip -rate"_. Anything beyond the burst gets an immediate **503**. +A refused request gets **503**, not the plugin's 429: `handle_errors 429` in +the Caddyfile rewrites it, because `vue/src/views/hotels/hotelsStream.js` +tells a rate-limit 503 ("too many searches from your address") apart from the +Python service's own 429 ("someone else is searching"). -| Zone | Rate | Burst | Applied to | Why | -| -------------- | ------ | ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. | -| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. | -| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. | -| `upload` | 30/min | 20 | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. | -| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. | +A zone's state is shared by every route that names it (`/api/`, `/py/`, +`/jobs/`, `/usaco/` and `/tracker/` share one `api` bucket per IP), so a zone +name must always be given the same numbers. A route that wants different ones +gets its own zone, as `/receipt/` does. + +| Zone | Limit | Applied to | Why | +| -------------- | --------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `login` | 5 / 1m | `/api/auth/login` | Brute-force defence, on top of the backend's own 5/min. A human mistyping gets five tries a minute; a credential-stuffing script gets nothing useful. | +| `api` | 30 / 1s | `/api/`, `/py/`, `/jobs/`, `/usaco/`, `/tracker/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. | +| `graphql` | 10 / 1s | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. Dev has it too now. | +| `upload` | 30 / 1m | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. | +| `hotel_search` | 3 / 1m | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. | +| `receipt` | 10 / 1s | `/receipt/` | Prints are slow and physical; ten a second is far above any real use. | The WebSocket endpoint is deliberately unlimited: a socket is one long-lived request, and a limit there would drop reconnect storms rather than abuse. -These zones key on `$remote_addr`. For tunnel traffic nginx rewrites that -from Cloudflare's `CF-Connecting-IP` header (`set_real_ip_from` / -`real_ip_header` in `nginx.conf.template`), trusting the header only from -cloudflared's fixed address. **If that address changes in -`docker-compose.yml` without the nginx line, every tunnel visitor shares -cloudflared's one bucket**, and the login limit locks everyone out together. +`{client_ip}` is the visitor's address only because of `trusted_proxies` and +`client_ip_headers CF-Connecting-IP` in the Caddyfile's global options, which +trust that header from cloudflared's fixed address alone. **If that address +changes in `docker-compose.yml` without the Caddyfile, every tunnel visitor +shares cloudflared's one bucket**, and the login limit locks everyone out +together. --- @@ -477,99 +497,76 @@ git pull && docker compose up -d --build --remove-orphans docker compose up -d --build backend ``` -Note: editing `certbot/entrypoint.sh` needs no rebuild (it is bind-mounted over -the stock image's entrypoint) — just `docker compose restart certbot`. Editing -an nginx **template** does need a rebuild, since templates are `COPY`'d into the -image. - -**Apply a new nginx config / pick up a renewed certificate:** +**Apply a Caddy config change.** Everything in `caddy/` is copied into the +image, so a change needs a rebuild, which also validates it (the Dockerfile's +last step runs `caddy validate` for the production and dev sites, and a +config that would not load fails the build before any container is +replaced). Only the first build on a host, or a Caddy or plugin version bump, +compiles Caddy itself (about 25 minutes on stpvm's two CPUs); a config-only +change rebuilds in seconds. The recreate drops connections for a second or +two. Certificates need nothing. ``` -docker compose up -d --build nginx # template changed -docker compose restart nginx # certificate changed +make check-caddy # on a laptop, before pushing +docker compose up -d --build caddy # on the host ``` -**Renew certificates manually** (then restart nginx so it is actually served): - -``` -docker compose exec certbot certbot renew --webroot -w /var/www/certbot -docker compose restart nginx -``` - -Add `--dry-run` to test without burning rate limit. - -**Caddy beside nginx (the edge migration, in progress).** `caddy/` is the -replacement for `nginx/` and certbot. Until the cutover the `caddy` container -runs next to nginx and serves nothing public: it listens on the host's -loopback only (`127.0.0.1:8880` http, `127.0.0.1:8443` https), has no network -aliases, and gets its own certificates over DNS-01 into `./caddy/data`. That -needs `CLOUDFLARE_DNS_API_TOKEN` to carry **Zone → Zone → Read** as well as -DNS → Edit (certbot only needed the second); without it Caddy logs failed -orders and the public site is unaffected. Watch the first issuance with: - -``` -docker compose logs -f caddy | grep -i -E 'certificate|error' -``` - -Then compare the two edges request by request (the script's header explains -the output; pass an admin session's cookie as `EDGE_COOKIE` to cover the -signed-in cases too): +**Check the edge.** `caddy/edge_test.sh` sends a fixed set of requests and +checks the privacy denials and every gate (non-zero exit on a FAIL), then +prints redirects, headers and uploads for comparison. Pass an admin session's +`Cookie` header value as `EDGE_COOKIE` to cover the signed-in cases. On the +host, pin the name to the machine or curl goes out over the internet: ``` export "$(grep '^DOMAIN=' .env)" -caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >nginx.txt -caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >caddy.txt -diff nginx.txt caddy.txt +caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 ``` -The expected differences: `Server: nginx` is gone, the gates match paths -case-insensitively (so `/SB/` is gated instead of falling to the SPA), and -`X-Frame-Options`/`Cache-Control` come out in a different order or combined. -A Caddyfile change is checked by `make check-caddy`, the same image build the -deploy runs, which validates the production and dev configs. +**Roll back to nginx** (until `nginx/` and `certbot/` are removed; the certbot +certificate in `./certbot/conf` is valid until 2027-01-20). `git revert` the +cutover commit and push, or by hand on the host, under the lock so a deploy +cannot interleave: + +``` +git revert --no-edit +flock .compose.lock sh -c 'docker compose stop caddy && docker compose rm -f caddy && docker compose up -d --build nginx certbot cloudflared traffic' +``` **Check logs:** ``` -docker compose logs -f nginx # follow one service +docker compose logs -f caddy # follow one service (one line per request) docker compose logs --tail=200 backend docker compose ps # note: `vue` Exited(0) is correct -docker compose logs certbot # issuance / renewal outcomes +docker compose logs caddy | grep -E 'tls|certificate' # issuance / renewal ``` Or browse every container's logs at `https://www./dozzle/` (admin login required). -**Incoming request bodies.** nginx writes one JSON line per request, body -included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The -`traffic` container tails it, so in Dozzle pick **traffic** and each request -renders as fields you can search. From a shell: +**Incoming request bodies.** Caddy writes one JSON line per request, body +included, to `logs/caddy/payloads.log` (the `payloads_file` logger and the +`logging` snippet in `caddy/Caddyfile`). The `traffic` container tails it, so +in Dozzle pick **traffic** and each request renders as fields you can search. +From a shell: ``` -tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")' -jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log +tail -f logs/caddy/payloads.log | jq 'select(.request.method=="POST")' +jq -r 'select(.request.uri=="/api/graphql") | .req_body | fromjson? | .operationName' logs/caddy/payloads.log +jq -r '[.ts, .request.client_ip, .request.method, .request.uri, .status] | @tsv' logs/caddy/payloads.log ``` Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]` -(that covers every login and the refresh call). Bodies over 64 KB, i.e. -uploads, are logged with an empty `body`, and responses are never logged. +(that covers every login and the refresh call), and `Cookie`/`Authorization` +headers as `REDACTED`. A body is only logged when the client declared a +length under 100 KB on a route that is not an upload (`/api/uploads`, +`/garage/`, `/receipt/`, `/v2/`); everything else has no `req_body`, and +responses are never logged. -The file is never rotated by the stack. On the host, add -`/etc/logrotate.d/web_server`: - -``` -/home/adamf/deploy/web_server/logs/nginx/*.log { - weekly - rotate 4 - compress - missingok - notifempty - copytruncate -} -``` - -`copytruncate` because nginx keeps the file open; `tail -F` in `traffic` -follows the truncation. +Caddy rotates the file itself (50 MiB, five old files kept), and `tail -F` +in `traffic` follows the rotation, so it needs no logrotate entry. The +`logs/nginx/*.log` stanza in `/etc/logrotate.d/web_server` is nginx's and +can go when `logs/nginx/` does. **Reset the database** — destructive; wipes the app database **and Gitea's**: @@ -594,8 +591,8 @@ or not set up: - the backend writes to disk until `S3_ENDPOINT` is set, and falls back to disk (with a log line) whenever Garage refuses a write; -- nginx serves `/uploads/` from Garage and falls back to the volume when - Garage has no such file or is unreachable, and it boots without the +- Caddy serves `/uploads/` from Garage and falls back to the volume when + Garage has no such file or is unreachable, and it starts without the `garage` container. Turning it on: @@ -640,7 +637,7 @@ to drop Garage entirely, first copy them back **Managing files:** garage-webui at `/garage/` (site admin login). Files uploaded there are public at `/uploads/` and skip the backend's type checks; keep them under a prefix such as `media/`. Uploads through it are -capped at 2G by nginx. +capped at 2 GB by Caddy. **Backups:** Garage here is one node on the same disk — it is not a backup. Back up `garage_meta` and `garage_data` together (meta without data, or the @@ -681,26 +678,27 @@ icecast source password. liquidsoap pre-empts the fallback playlist immediately silence. Adding MP3s to `icecast2/fallback_music/` is picked up live (`reload_mode="watch"`) with no restart. -**Only nginx is restarted when unhealthy.** Docker marks a container +**Only caddy is restarted when unhealthy.** Docker marks a container `unhealthy` but never acts on it; `restart: always` only brings back a process that exits. The `autoheal` container restarts anything labelled -`autoheal=true`, which today is just nginx (its healthcheck fetches -`/nginx-health` on :80 every 30s; three misses, about 90s, and it is +`autoheal=true`, which today is just caddy (its healthcheck fetches +`http://127.0.0.1/caddy-health` every 30s; three misses, about 90s, and it is restarted). `backend` and `python` also define healthchecks, but carry no label, so for them `unhealthy` is only visible in `docker ps`. Add the label to cover another service. -**Site down but every container `Up`.** That is what a stalled nginx worker -looks like (2026-10-19: 4.6 hours, every tunnel request a `TLS handshake -timeout` in `docker logs cloudflared`, and the Cloudflare dashboard still -showing the tunnel healthy, since that only covers the tunnel's own link). The -healthcheck should now catch it. If it recurs, capture the stuck worker before -restarting, since a restart destroys the only evidence of why: +**Site down but every container `Up`.** That is what a stalled edge looks +like (2026-10-19, under nginx: 4.6 hours, every tunnel request a `TLS +handshake timeout` in `docker logs cloudflared`, and the Cloudflare dashboard +still showing the tunnel healthy, since that only covers the tunnel's own +link). The healthcheck should catch it. If it happens, capture what Caddy is +doing before restarting, since a restart destroys the only evidence of why. +Its admin API (inside the container only) serves Go's profiler: ``` -docker inspect nginx --format '{{.State.Health.Status}}' -docker top nginx -o pid,stat,wchan:30,etime,cmd # what each worker is waiting in -docker compose restart nginx +docker inspect caddy --format '{{.State.Health.Status}}' +docker compose exec caddy wget -q -O - 'http://localhost:2019/debug/pprof/goroutine?debug=2' > caddy-goroutines.txt +docker compose restart caddy ``` --- @@ -709,25 +707,12 @@ docker compose restart nginx Documented, not fixed — each would change deploy behaviour. -1. **Renewed certificates are not served until nginx restarts.** No - `--deploy-hook` in `certbot/entrypoint.sh`. Fix: add - `--deploy-hook "touch /var/www/certbot/.reloadme"` plus a watcher, or give - certbot the docker socket to send nginx a `HUP`. -2. **First TLS issuance needs a manual `docker compose restart nginx`.** The - entrypoint only re-evaluates cert presence at container start. -3. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be +1. **`nginx/`, `certbot/` and their host directories are still here** as the + rollback from the 2026-11-17 cutover. Once Caddy has run for a couple of + weeks: move `nginx/` and `certbot/` to `.deprecated/`, then delete + `./certbot/` and `./logs/nginx/` on the host and the `logs/nginx` logrotate + stanza. +2. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be mounted to the same in-container path as the real wrapper. It is currently shadowed by an explicit file mount — fragile. Deleting it would be safe but is a file removal. -4. **The `/uploads/` location blocks (with `@uploads_disk`) are still written twice** — once in - `nginx.conf.template` and once in `nginx_dev_common.conf.template` — - because production adds security headers inside an auth-gated block. Every - other proxied route lives once in `nginx_routes.conf.template`, which both - configs include; the `auth_request` lines on `/uploads/private/` are the - one thing that must be kept in step by hand. -5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing - only our own origin**, which defeats the point of having the header at all. -6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert - today (neither contains whitespace) but a latent quoting bug. -7. **`UPTIMEKUMA_*` and `WALLABAG_*` are substituted by nginx but no compose - service provides them** — leftovers from removed services. diff --git a/Makefile b/Makefile index 71e2fed..9f166c9 100644 --- a/Makefile +++ b/Makefile @@ -128,6 +128,6 @@ check-caddy: generate: cd backend && go run github.com/99designs/gqlgen generate -# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx. +# Dev stack: http and https, seeded database, Vite hot reload behind Caddy. dev: docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build diff --git a/README.md b/README.md index 06fff49..e492428 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,11 @@ After hearing all the hype on LinkedIn and feeling the pressure to keep up a hig ## Architecture -All services run in Docker containers orchestrated by Docker Compose behind Nginx as a reverse proxy on a single bridge network. +All services run in Docker containers orchestrated by Docker Compose behind Caddy as a reverse proxy on a single bridge network. (nginx and certbot did that job until 2026-11-17.) ``` vue ── Frontend build (outputs dist to shared volume) -nginx (80, 443) ── Frontend SPA + Reverse Proxy +caddy (80, 443) ── Frontend SPA + Reverse Proxy + TLS certificates backend (8080) ── Go API (GraphQL + REST) db (5432) ── PostgreSQL 16 icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap) @@ -28,7 +28,6 @@ silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0) silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY) silverbullet-git ── Commits/pushes notes edits to the notes repo python (8000) ── Python API (FastAPI) -certbot ── SSL Certificate Management (disabled in dev) ``` ## Tech Stack @@ -39,7 +38,7 @@ certbot ── SSL Certificate Management (disabled in dev) **Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2 -**Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner +**Infrastructure** - Docker Compose, Caddy, Let's Encrypt (DNS-01 via Cloudflare), Cloudflare Tunnel, Gitea + Act Runner ## Features @@ -56,7 +55,7 @@ certbot ── SSL Certificate Management (disabled in dev) - Printable CV with role-specific sections - Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`) - Database-backed bookmarks grouped by category, managed via GraphQL (admin-only) -- Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request` +- Admin-gated routes: `/sb`, `/jobs`, `/tracker`, `/dozzle`, `/garage` and more require the admin session, checked by Caddy's `forward_auth` against the backend - Landing page with animated stamps section - Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading) - Backend healthcheck (reported in `docker ps`; nothing restarts on it) @@ -123,7 +122,7 @@ certbot ── SSL Certificate Management (disabled in dev) | POST | `/api/auth/refresh` | Refresh token | | GET | `/api/auth/check` | Check token validity | | POST | `/api/auth/logout` | Logout | -| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Nginx auth_request) | +| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Caddy's `forward_auth` admin gate) | Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry. @@ -174,7 +173,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` | --- | --- | --- | | GET | `/api/ws` | WebSocket chat (10s ping keepalive) | -### Nginx Proxy Routes +### Proxy Routes (Caddy) | Route | Target | Notes | | ---------- | ------------ | ------------------------------------------ | @@ -186,7 +185,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` | `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) | | `/uploads` | local alias | User-uploaded files | -`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401. +`/sb` is protected by `forward_auth` to the backend's `/auth/validate-admin`. Requests without a valid admin session are redirected to `/admin/login`. The full table is `caddy/routes.caddy`; `DEPLOYMENT.md` §1 explains it. ### Deprecated Endpoints @@ -272,21 +271,19 @@ Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at `/notes/` with `SB_READ_ONLY` 3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off - `/notes/` by `SB_SPACE_IGNORE` **and** nginx deny blocks — the nginx blocks are the ones that + `/notes/` by `SB_SPACE_IGNORE` **and** Caddy deny rules — the Caddy rules are the ones that actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary") 4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above) -### SSL Certificates (Certbot) +### TLS certificates -**Initial setup (production):** +Caddy obtains and renews them itself, over DNS-01 through the Cloudflare API, so no port has to be reachable from the internet: -1. Set `DOMAIN` and `EMAIL` in `.env` -2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/` -3. Certbot requests a certificate via `certbot certonly --webroot` -4. Once the certificate is issued to `certbot/conf/live//`, restart Nginx — it will detect the certs and switch to the full `nginx.conf.template` -5. Certbot checks for renewal every 12 hours automatically +1. Set `DOMAIN` and `CLOUDFLARE_DNS_API_TOKEN` in `.env` (the token needs Zone → Zone → Read and Zone → DNS → Edit on the zone) +2. `docker compose up -d`. Caddy serves immediately and fetches both certificates (apex and www) into `./caddy/data` within seconds +3. Renewal is automatic and needs no restart -**Dev mode:** Nginx generates a self-signed certificate for localhost automatically. +**Dev mode:** Caddy issues a certificate for localhost from its own local CA. ### Icecast Radio @@ -309,9 +306,9 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build This: -- Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.) -- Generates a self-signed certificate for localhost -- Disables certbot +- Loads Caddy's dev sites (`caddy/sites/dev.caddy`): all the same routing (SPA via Vite, backend proxy, radio, gitea, etc.) on both http and https, with no redirects or security headers +- Uses a localhost certificate from Caddy's local CA +- Disables the Cloudflare tunnel - Seeds the database with test data (`SEED_DB=true`) - Enables GraphQL playground and introspection @@ -331,7 +328,7 @@ Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets defaul make check ``` -Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`. +Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build, `docker compose config` validation and the Caddy image build, which validates the edge config. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`. The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass. @@ -343,7 +340,7 @@ These files are git-ignored and must be created manually: | ------------------------------- | --------------------------------------------------------------- | | `.env` | See setup section above | | `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it | -| `certbot/conf/`, `certbot/www/` | Created automatically by certbot; use dev mode to skip | +| `caddy/data/` | Created automatically by Caddy (certificates and their keys) | | `backend/token/` | Created automatically by Docker volume mount | | `icecast2/fallback_music/*.mp3` | Place at least one MP3 file | | `gitea-runner/act_runner` | Download from Gitea releases | diff --git a/backend/Dockerfile b/backend/Dockerfile index 0c28742..d30860e 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -22,7 +22,7 @@ # would fail certificate verification without a trust store. # # EXPOSE 8080 is documentation only; the port is never published to the host. -# nginx reaches it over app-network as BACKEND_HOST:BACKEND_PORT. +# Caddy reaches it over app-network as BACKEND_HOST:BACKEND_PORT. # # Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and # amd64 (a dev laptop) with no platform pin. diff --git a/backend/README.md b/backend/README.md index c5c7c57..af53301 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,11 +1,11 @@ # Backend -The Go API for adam-french.co.uk. It is one process behind nginx, serving a +The Go API for adam-french.co.uk. It is one process behind Caddy, serving a GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything that needs Claude is asked of the Python service, not called from here. -Nginx strips the `/api` prefix before proxying, so a browser request to +Caddy strips the `/api` prefix before proxying, so a browser request to `/api/graphql` arrives here as `/graphql`. Every path below is as this service sees it. @@ -33,7 +33,7 @@ graph/ GraphQL layer ## Request lifecycle -1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and +1. Caddy terminates TLS, applies its own rate limits, strips `/api`, and proxies to this service. 2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so that `ClientIP()` — which the login rate limiter keys on — cannot be @@ -65,7 +65,7 @@ graph/ GraphQL layer and will transparently refresh, so returning admins are recognised without a visible re-login. - `GET /auth/validate/:permission` is the same for one named permission - (200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's + (200 / 403 / 401, and 404 for a key that does not exist). It backs Caddy's *permission gate*, which lets a non-admin account into one service — the receipt printer at `/receipt/` — without making it an admin. Grantable keys are the registry `services.PermissionTypes` (`services/permissions.go`); @@ -73,7 +73,7 @@ graph/ GraphQL layer Users tab (`setUserPermissions`). Admins pass every permission check. The check reads the user row, not the token, so a grant or revoke applies on the next request. On 200 it returns the username in `X-Auth-User`, which - nginx forwards to the gated service as `X-Remote-User`. + Caddy forwards to the gated service as `X-Remote-User`. - Tokens are stateless. **Logout only clears the browser's cookies**; nothing is revoked server-side, and a token that has already been issued stays valid until it expires. The same is true of demoting an admin: it takes effect on @@ -195,7 +195,7 @@ no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at `/jobs/` is a separate app with its own Claude calls.) It reaches the internal routes directly over the Docker network (`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through -nginx, which answers 404 for `/py/internal/`: +Caddy, which answers 404 for `/py/internal/`: | route | caller | sends | gets back | | --- | --- | --- | --- | @@ -244,7 +244,7 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends. to show them. Public files go to the Garage bucket wrapped in `FallbackFileStore` (a failed S3 write is logged and retried on disk), or to disk alone when `S3_ENDPOINT` is unset; private ones always to disk - (nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket + (the edge cannot gate a bucket). Caddy serves `/uploads/` from the bucket first and disk second, so either store's files work at the same URL. A new handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind admin-only `GET /uploads`, for the canvas's upload picker) returns the union diff --git a/backend/graph/page_helpers.go b/backend/graph/page_helpers.go index bf3f992..74e8a35 100644 --- a/backend/graph/page_helpers.go +++ b/backend/graph/page_helpers.go @@ -22,8 +22,8 @@ var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a- const maxSlugLen = 100 // reservedFirstSegments are paths a page could never be reached at, because -// nginx or one of the SPA's own routes answers them first (see -// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the +// Caddy or one of the SPA's own routes answers them first (see +// caddy/routes.caddy and vue/src/router/index.js), plus the // landing page's key "index", whose boxes a page of the same slug would // share. "shrines" and "stp" are deliberately absent: /shrines, the shrine // pages under it and the home page /stp are all canvas pages. diff --git a/backend/graph/page_helpers_test.go b/backend/graph/page_helpers_test.go index 7e76eaf..60d9a2c 100644 --- a/backend/graph/page_helpers_test.go +++ b/backend/graph/page_helpers_test.go @@ -20,7 +20,7 @@ func TestValidateSlug(t *testing.T) { {"shrines", true}, // the index is a canvas page too {"shrines/demoman", true}, // no longer an SPA route {"admin/pages", false}, // under an SPA route - {"jobs/x", false}, // under an nginx route + {"jobs/x", false}, // under a Caddy route {"stp", true}, // the home page is a canvas page too {"stp2", false}, // an SPA route {"index", false}, // the landing canvas's key diff --git a/backend/graph/schema/user.graphql b/backend/graph/schema/user.graphql index 06ea522..0ab0e0a 100644 --- a/backend/graph/schema/user.graphql +++ b/backend/graph/schema/user.graphql @@ -10,7 +10,7 @@ type User { } # One grantable service, from services.PermissionTypes: `key` is what is -# stored and what nginx gates on, `label` and `path` are for display. +# stored and what Caddy gates on, `label` and `path` are for display. type PermissionType { key: String! label: String! diff --git a/backend/handlers/handle_auth.go b/backend/handlers/handle_auth.go index d8864f3..799df0e 100644 --- a/backend/handlers/handle_auth.go +++ b/backend/handlers/handle_auth.go @@ -93,7 +93,7 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) { } // ValidateAdmin backs GET /auth/validate-admin, which the front end calls to -// decide whether to show admin UI, nginx's admin gate calls as an +// decide whether to show admin UI, Caddy's admin gate calls as an // auth_request, and the jobs container calls with the visitor's cookies. It // answers with a bare status code and no body: 200 admin, 403 authenticated // but not admin, 401 not authenticated. @@ -114,11 +114,11 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) { }) } -// ValidatePermission backs GET /auth/validate/:permission, nginx's permission +// ValidatePermission backs GET /auth/validate/:permission, Caddy's permission // gate (see services/permissions.go). Same bare-status contract and refresh // fallback as ValidateAdmin — 200 allowed, 403 signed in without the // permission, 401 not signed in — plus 404 for a key that is not in -// services.PermissionTypes, so a typo in an nginx location fails closed and +// services.PermissionTypes, so a typo in a Caddy route fails closed and // visibly rather than as a 403 that looks like a missing grant. // // The decision reads the user row, not the token, for admins as well: a @@ -141,9 +141,10 @@ func (store *Store) ValidatePermission(ctx *gin.Context) { // allow receives the access token's claims, or nil when the caller was // identified from the refresh token (which carries no authorisation claims). // -// On 200 the username goes back in X-Auth-User, which nginx can lift with -// auth_request_set and hand to the service behind the gate, so that service -// knows who is using it without having accounts of its own. +// On 200 the username goes back in X-Auth-User, which Caddy's forward_auth +// copies onto the proxied request (as X-Remote-User for /receipt/), so the +// service behind the gate knows who is using it without having accounts of +// its own. func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) { accessToken, err := ctx.Cookie("access_token") if err == nil { @@ -287,10 +288,10 @@ func (store *Store) RefreshToken(ctx *gin.Context) { // Login backs POST /auth/login. The user object it returns omits the password // because models.User tags that field `json:"-"`. func (store *Store) Login(ctx *gin.Context) { - // Per-IP limit (5/min) on top of nginx's own login rate limit. + // Per-IP limit (5/min) on top of Caddy's own login rate limit. // ctx.ClientIP is only trustworthy because main.go pins the trusted // proxy range, so the X-Forwarded-For header cannot be spoofed by a - // client talking through nginx. + // client talking through Caddy. if !store.LoginLimiter.Allow(ctx.ClientIP()) { ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"}) return diff --git a/backend/handlers/handle_rowing.go b/backend/handlers/handle_rowing.go index 5a4744e..f8092cc 100644 --- a/backend/handlers/handle_rowing.go +++ b/backend/handlers/handle_rowing.go @@ -34,8 +34,8 @@ type ExtractedRowingData struct { Distance uint64 `json:"distance"` } -// rowingReadPath is the Python route. It is internal: nginx refuses -// /py/internal/ and the route itself refuses anything nginx forwarded, so the +// rowingReadPath is the Python route. It is internal: Caddy refuses +// /py/internal/ and the route itself refuses anything Caddy forwarded, so the // only way in is the direct container-to-container call services.CallPython // makes. const rowingReadPath = "/internal/rowing/read" diff --git a/backend/handlers/handle_rowing_test.go b/backend/handlers/handle_rowing_test.go index 99dff2b..28ec0a8 100644 --- a/backend/handlers/handle_rowing_test.go +++ b/backend/handlers/handle_rowing_test.go @@ -32,7 +32,7 @@ func TestReadRowingDisplayRequestAndReply(t *testing.T) { var forwarded bool store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) { path = r.URL.Path - // The Python route treats either header as "came through nginx" and + // The Python route treats either header as "came through Caddy" and // answers 404, so this call must never carry them. forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != "" if err := json.NewDecoder(r.Body).Decode(&got); err != nil { diff --git a/backend/handlers/handlers_pure_test.go b/backend/handlers/handlers_pure_test.go index 821283c..b5d5574 100644 --- a/backend/handlers/handlers_pure_test.go +++ b/backend/handlers/handlers_pure_test.go @@ -255,7 +255,7 @@ func TestRequestIsAdmin(t *testing.T) { // --- Permission gate ------------------------------------------------------ // An unknown key must be refused before any session lookup (Store has no DB -// or Auth here, so reaching one would panic): it is how a typo in an nginx +// or Auth here, so reaching one would panic): it is how a typo in a Caddy // location shows up as a 404 rather than as a missing grant. func TestValidatePermissionUnknownKey(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/handlers/store.go b/backend/handlers/store.go index 1942c14..15f6312 100644 --- a/backend/handlers/store.go +++ b/backend/handlers/store.go @@ -34,7 +34,7 @@ type Store struct { LoginLimiter *services.RateLimiter // Base URL of the Python service on the Docker network, no trailing - // slash. Used for the calls that bypass nginx, all through + // slash. Used for the calls that bypass Caddy, all through // services.CallPython: reading a rowing display photo (handle_rowing.go). PythonURL string diff --git a/backend/main.go b/backend/main.go index b7d3885..c407186 100644 --- a/backend/main.go +++ b/backend/main.go @@ -50,7 +50,7 @@ func main() { r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter)) r.Use(gin.Recovery()) - // Only the Docker network nginx sits on may set X-Forwarded-For. Without + // Only the Docker network Caddy sits on may set X-Forwarded-For. Without // this pin any client could spoof its IP and defeat the per-IP login rate // limiter, which keys on ctx.ClientIP(). The CIDR must match the network // defined in docker-compose.yml. @@ -115,7 +115,7 @@ func main() { steamID := os.Getenv("STEAM_ID") // PYTHON SERVICE - // Called directly over the Docker network, not through nginx, for its + // Called directly over the Docker network, not through Caddy, for its // /internal/ Claude route (services/python_call.go). The defaults // mirror docker-compose.yml, where both variables are optional. pythonHost := os.Getenv("PYTHON_HOST") @@ -145,7 +145,7 @@ func main() { uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/") // 5 login attempts per IP per minute, applied by both the REST handler - // and the GraphQL login mutation. Nginx rate-limits the login route too. + // and the GraphQL login mutation. Caddy rate-limits the login route too. loginLimiter := services.NewRateLimiter(5, time.Minute) store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads} @@ -153,7 +153,7 @@ func main() { // Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in // the Gin context, so the order in the admin group matters. // - // Paths below have no /api prefix: nginx strips it before proxying. + // Paths below have no /api prefix: Caddy strips it before proxying. protected := r.Group("/", store.AuthMiddlewear) admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware) diff --git a/backend/services/permissions.go b/backend/services/permissions.go index 2d88ff7..dd006d0 100644 --- a/backend/services/permissions.go +++ b/backend/services/permissions.go @@ -10,17 +10,17 @@ import ( // service (the receipt printer, say) without being made an admin. // // A permission is a key from PermissionTypes stored in models.User.Permissions. -// nginx gates a service on one key by asking GET /auth/validate/ +// Caddy gates a service on one key by asking GET /auth/validate/ // (handlers.Store.ValidatePermission); admins pass every such check, so // moving a service from the admin gate to a permission gate never locks an // admin out. Services that are not listed here stay admin-only. // -// Adding a grantable service is one entry below plus swapping that location's -// nginx gate from /internal/auth/admin-validate to the permission gate (see -// "Permission gate" in nginx/nginx_routes.conf.template). +// Adding a grantable service is one entry below plus swapping its route in +// caddy/routes.caddy from `import admin_gate` to `import permission_gate +// ` (the snippet is in caddy/Caddyfile). // PermissionType describes one grantable service. Key is what is stored and -// what nginx names; Label and Path are for the admin panel's checkboxes and +// what Caddy names; Label and Path are for the admin panel's checkboxes and // the signed-in user's /account list of links. type PermissionType struct { Key string diff --git a/backend/services/permissions_test.go b/backend/services/permissions_test.go index f11adb9..c5da47f 100644 --- a/backend/services/permissions_test.go +++ b/backend/services/permissions_test.go @@ -19,7 +19,7 @@ func TestValidPermission(t *testing.T) { } } -// Keys must be URL-path safe: nginx splices them into /auth/validate/. +// Keys must be URL-path safe: Caddy splices them into /auth/validate/. func TestPermissionKeysArePathSafe(t *testing.T) { seen := map[string]bool{} for _, p := range PermissionTypes { diff --git a/backend/services/python_call.go b/backend/services/python_call.go index 112b12d..3099c49 100644 --- a/backend/services/python_call.go +++ b/backend/services/python_call.go @@ -16,7 +16,7 @@ import ( // (handlers/handle_rowing.go); the job posting reader, email classifier and // lead scorer went with the job tracker to its own repo. // -// The routes are internal in a specific sense: nginx answers 404 for +// The routes are internal in a specific sense: Caddy answers 404 for // /py/internal/, and each route itself refuses a request carrying a proxy // header, so the only way in is this direct container-to-container call. That // is why the request below sets nothing but Content-Type. diff --git a/backend/services/python_call_test.go b/backend/services/python_call_test.go index dd96f06..d24f8cd 100644 --- a/backend/services/python_call_test.go +++ b/backend/services/python_call_test.go @@ -36,7 +36,7 @@ func TestCallPythonRequestAndReply(t *testing.T) { ) url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) { method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type") - // The Python routes treat either header as "came through nginx" and + // The Python routes treat either header as "came through Caddy" and // answer 404, so the helper must never send them. forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != "" if err := json.NewDecoder(r.Body).Decode(&got); err != nil { diff --git a/backend/services/ratelimit.go b/backend/services/ratelimit.go index c7349ee..7f0e443 100644 --- a/backend/services/ratelimit.go +++ b/backend/services/ratelimit.go @@ -12,7 +12,7 @@ import ( // RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary // string (in practice the client IP). It is process-local: restarting the // backend clears every window, and a multi-replica deployment would limit -// per replica rather than globally. Nginx applies its own rate limits in +// per replica rather than globally. Caddy applies its own rate limits in // front of this, so this layer is a second line of defence, not the only one. type RateLimiter struct { mu sync.Mutex diff --git a/backend/services/traffic_log.go b/backend/services/traffic_log.go index 18e7e35..e3172a5 100644 --- a/backend/services/traffic_log.go +++ b/backend/services/traffic_log.go @@ -11,7 +11,7 @@ import ( // site owner scanning the log for "who is using my site". Two goals: // // 1. Quietness. The log is flooded by traffic that is not a human visit: -// nginx auth_request subrequests (/auth/validate-admin, re-run for every +// Caddy forward_auth subrequests (/auth/validate-admin, re-run for every // admin page hit), the front end's own polling (`/auth/refresh_token`, // home-data refreshes), and Vite dev asset fetches. Each is collapsed to // a single terse line, or dropped entirely when repeated in a short @@ -24,7 +24,7 @@ import ( // logQuietDrop lists paths whose 2xx responses are dropped outright. These // are all heartbeat-style endpoints: identical every few seconds, no signal. var logQuietDrop = map[string]bool{ - "/auth/validate-admin": true, // nginx auth_request subrequest + "/auth/validate-admin": true, // Caddy forward_auth subrequest "/auth/refresh": true, // front-end token refresh "/auth/check": true, // front-end session check } @@ -76,7 +76,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string { fmt.Sprintf("%.0f%s", float64(latency), unit), marker) // Visitor traffic gets the IP appended — the "who". Infrastructure - // traffic (nginx's own feet on the internal subnet) already has its IP + // traffic (the edge's own feet on the internal subnet) already has its IP // implied and is left lean. if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) { line += " " + params.ClientIP @@ -86,10 +86,10 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string { } // logIsInterestingClient reports whether a client IP is likely an actual -// visitor rather than infrastructure. nginx proxies everything, so the IPs +// visitor rather than infrastructure. Caddy proxies everything, so the IPs // that appear are either forwarded-from-humans or the ingress itself. func logIsInterestingClient(ip string) bool { - // Docker's bridge network: nginx's own feet. Not a visitor. + // Docker's bridge network: the edge's own feet. Not a visitor. return !startsWith(ip, "172.28.") } diff --git a/backend/services/uploads.go b/backend/services/uploads.go index a5e4996..3c5c959 100644 --- a/backend/services/uploads.go +++ b/backend/services/uploads.go @@ -34,26 +34,26 @@ import ( // // WHERE FILES GO // Public files go to the Garage bucket `uploads` (garage/garage.toml), with -// the `uploads` volume as a fallback for when Garage refuses a write. nginx +// the `uploads` volume as a fallback for when Garage refuses a write. Caddy // mirrors that: /uploads/ is fetched from the bucket first and the -// volume second (nginx.conf.template), so the URL is the same wherever the +// volume second (caddy/routes.caddy), so the URL is the same wherever the // file landed. With S3_ENDPOINT unset there is no bucket and the volume is // the only store. // Private files (admin-only chat attachments) always go to the volume, under -// /uploads/private/, which nginx gates behind an admin check. nginx can't +// /uploads/private/, which Caddy gates behind an admin check. Caddy can't // sign S3 requests, so it has no way to gate a bucket. // // Everything public is reachable by anyone who has the URL, with no login. // That is why the type checks below are strict, and why names are random. // MaxUploadSize caps one upload. It bounds how fast one account can fill the -// disk or the bucket; nginx rate-limits the route as well. +// disk or the bucket; Caddy rate-limits the route as well. const MaxUploadSize = 10 << 20 // 10MB // UploadType describes one allowed file extension. type UploadType struct { // ContentType is stored with the file and served back with it. Garage - // returns exactly this, and the browser renders by it: nginx adds + // returns exactly this, and the browser renders by it: Caddy adds // `nosniff`, so a wrong type means the file doesn't display. ContentType string // SniffPrefix is what http.DetectContentType must report for the file's @@ -100,7 +100,7 @@ type Uploads struct { private FileStore } -// URL prefixes the files are served under; nginx owns both paths. +// URL prefixes the files are served under; Caddy owns both paths. const ( publicURLPrefix = "/uploads/" privateURLPrefix = "/uploads/private/" @@ -238,7 +238,7 @@ type FileStore interface { type DiskFileStore struct{ Dir string } func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error { - // 0755 and 0644 so nginx, a different user, can reach and read the files. + // 0755 and 0644 so the edge, in another container, can reach and read the files. if err := os.MkdirAll(d.Dir, 0755); err != nil { return err } @@ -334,7 +334,7 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea // List pages through the whole bucket. Keys containing "/" are skipped: they // are not uploads (Save never makes one) but something put under a prefix by -// hand, and nginx's /uploads/ only ever serves a top-level name anyway. +// hand, and Caddy's /uploads/ only ever serves a top-level name anyway. func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) { ctx, cancel := context.WithTimeout(ctx, s3Timeout) defer cancel() @@ -358,7 +358,7 @@ func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) { } // FallbackFileStore tries Primary and, if that fails, logs it and writes to -// Fallback instead. The upload still succeeds and its URL still works (nginx +// Fallback instead. The upload still succeeds and its URL still works (Caddy // looks in both places), so a Garage outage costs a log line rather than // broken uploads. type FallbackFileStore struct { @@ -378,7 +378,7 @@ func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r i return f.Fallback.Put(ctx, key, contentType, r, size) } -// List is the union of both stores, since nginx serves from both: the +// List is the union of both stores, since Caddy serves from both: the // fallback holds whatever was written while the primary was down (and, on // the live volume, the pre-Garage copies). A name in both is listed once, // with the primary's details. A primary that can't list is logged and the diff --git a/caddy/Caddyfile b/caddy/Caddyfile index 8aeffb6..344bdf9 100644 --- a/caddy/Caddyfile +++ b/caddy/Caddyfile @@ -89,8 +89,8 @@ # The payload log: one JSON line per request, body included (log_append # in `logging`), for seeing what actually arrives at the edge. - # logs/caddy/ on the host; from the cutover the `traffic` container tails - # it so Dozzle shows it as its own stream. Caddy rotates it itself, and + # logs/caddy/ on the host; the `traffic` container tails it so Dozzle + # shows it as its own stream. Caddy rotates it itself, and # `tail -F` follows the rotation. 0644 so `jq` on the host can read it # unprivileged (Caddy's default is 0600). # diff --git a/caddy/edge_test.sh b/caddy/edge_test.sh index 6190ee2..752ac2a 100755 --- a/caddy/edge_test.sh +++ b/caddy/edge_test.sh @@ -32,11 +32,13 @@ # Dev stack: # caddy/edge_test.sh https://localhost -k # -# COMPARING TWO EDGES (the nginx -> Caddy cutover) -# Run it against each and diff the output: -# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >nginx.txt -# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >caddy.txt -# diff nginx.txt caddy.txt +# COMPARING TWO EDGES +# Run it against each and diff the output. This is how Caddy was checked +# against nginx before the 2026-11-17 cutover (Caddy on 8443 beside nginx), +# and how a big change to caddy/ can be checked against the running edge: +# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >before.txt +# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >after.txt +# diff before.txt after.txt # Every remaining difference should be one that was intended. # # NOTHING HERE WRITES. Every request is a GET, apart from one POST to diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 0b2a790..1e2a9c7 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -12,17 +12,15 @@ # - vue : one-shot `vite build` becomes the long-running Vite dev server # with the source bind-mounted for hot reload. # - backend : dev flags on, including database seeding. -# - nginx : DEV_MODE=true, which makes its entrypoint render -# nginx_dev.conf.template and self-sign a localhost certificate. -# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy. Until the -# cutover it runs beside nginx, on 127.0.0.1:8880 / :8443. +# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy instead of +# the production sites: no redirects, no security headers, a +# certificate from Caddy's own local CA, `/` proxied to Vite. # - python : uvicorn --reload with the app source bind-mounted. -# - certbot : disabled entirely. # - cloudflared : disabled entirely. # # HOW TO REACH IT -# http://localhost (HTTPS also works on :443 with the self-signed cert, which -# the browser will warn about — that is expected). +# http://localhost (HTTPS also works on :443 with the local-CA certificate, +# which the browser will warn about — that is expected). # # NOT USED ON THE PI. The deploy workflow runs plain `docker compose up`. # ============================================================================= @@ -30,7 +28,7 @@ services: vue: # Replaces the one-shot `vite build`: the container now stays up serving - # the Vite dev server on :5173, which nginx_dev.conf proxies `/` to. + # the Vite dev server on :5173, which caddy/sites/dev.caddy proxies `/` to. command: ["npm", "run", "dev"] volumes: - ./vue:/app @@ -57,21 +55,11 @@ services: # because dev uses a throwaway local dbdata volume; it is NEVER set # in production — seeding a live database would inject fake content. - SEED_DB=true - nginx: - environment: - # The single switch that selects nginx_dev.conf.template and the - # self-signed localhost certificate. See nginx/entrypoint.sh. - - DEV_MODE=true - # Same mapping as the base file; restated because compose replaces the - # `ports` list rather than merging it, so omitting it here would be fine - # but restating it makes the dev surface explicit. - ports: - - 80:80 - - 443:443 caddy: environment: - # Loads caddy/sites/dev.caddy instead of the production sites: - # localhost on http and https, `tls internal`, `/` -> Vite. + # The single switch that loads caddy/sites/dev.caddy instead of + # the production sites: localhost on http and https, `tls + # internal`, `/` -> Vite. - CADDY_SITE=dev python: # Same command as the Dockerfile's CMD plus --reload, paired with the @@ -91,17 +79,12 @@ services: - GQL_PLAYGROUND=true - GQL_INTROSPECTION=true - MSGRAPH_REDIRECT_URI=https://localhost/jobs/api/email/callback - certbot: + cloudflared: # Profiles are opt-in: a service with a profile is only started when # that profile is explicitly requested. Nothing ever requests - # "disabled", so this is the idiomatic way to switch a service off in an - # override file. Dev gets TLS from nginx's self-signed cert instead, and - # Let's Encrypt could not validate localhost anyway. - profiles: - - disabled - cloudflared: - # Same profile trick as certbot. A dev stack must never join the - # production tunnel: Cloudflare would load-balance real visitors onto - # this machine's seeded database. + # "disabled", so this is the idiomatic way to switch a service off in + # an override file. A dev stack must never join the production tunnel: + # Cloudflare would load-balance real visitors onto this machine's + # seeded database. profiles: - disabled diff --git a/docker-compose.yml b/docker-compose.yml index b1536dc..8d0a21f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,24 +27,25 @@ # inline defaults. # # NAMING CONVENTION / WHY container_name IS SET FROM env -# Service discovery is by container name on app-network. nginx builds its -# upstreams from the same ${*_HOST} variables (nginx/entrypoint.sh), so -# naming the containers from .env keeps the proxy and the containers in sync -# from one source of truth. Renaming a *_HOST value renames the container AND -# repoints nginx at it — do not change one without the other. +# Service discovery is by container name on app-network. Caddy builds its +# upstreams from the same ${*_HOST} variables (the caddy service's +# environment list), so naming the containers from .env keeps the proxy and +# the containers in sync from one source of truth. Renaming a *_HOST value +# renames the container AND repoints Caddy at it — do not change one without +# the other. # # WHAT IS PUBLISHED TO THE HOST -# Only nginx (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor +# Only caddy (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor # port. Everything else is reachable only from inside app-network, which is # why the backend, db, silverbullet and python have no `ports:` — they are -# deliberately not exposed and are reached through nginx. Web traffic can +# deliberately not exposed and are reached through Caddy. Web traffic can # also arrive through the `cloudflared` tunnel, which publishes nothing. # ============================================================================= networks: # One flat bridge network; every service resolves every other by container - # name via docker's embedded DNS at 172.28.0.11 (nginx configs point their - # `resolver` there). The subnet is pinned explicitly so it cannot collide + # name via docker's embedded DNS at 127.0.0.11 (Caddy resolves an upstream + # through it each time it dials one). The subnet is pinned explicitly so it cannot collide # with the Pi's LAN range or wander between compose versions. app-network: driver: bridge @@ -63,7 +64,7 @@ networks: # Named volumes below survive `docker compose down` and container rebuilds; # they are only destroyed by `docker compose down -v` or an explicit # `docker volume rm`. Bind mounts (./gitea/data, ./backend/token, ./logs, -# ./certbot/conf) live in the repo checkout on the Pi and survive everything +# ./caddy/data) live in the repo checkout on the Pi and survive everything # short of deleting the directory. Anything inside a container's own # filesystem is ephemeral and gone on rebuild. volumes: @@ -71,10 +72,10 @@ volumes: # Deleting this wipes posts, users, messages and every git repo's metadata. dbdata: # File upload — PERSISTENT. Written by the backend at /backend/uploads, - # served read-only by nginx at /uploads/. Shared so nginx can serve user + # served read-only by Caddy at /uploads/. Shared so Caddy can serve user # uploads without proxying through the Go process. Since Garage, it holds # private attachments (always), the uploads from before the bucket, and any - # upload the backend wrote here because Garage refused it. nginx serves + # upload the backend wrote here because Garage refused it. Caddy serves # /uploads/ from the bucket first and only then from here. uploads: # Garage object store — PERSISTENT, both. garage_meta is the metadata DB @@ -84,8 +85,8 @@ volumes: garage_meta: garage_data: # Vue build — EPHEMERAL in spirit but a named volume for handoff: the - # one-shot `vue` container writes the built SPA here and exits; nginx mounts - # it at /etc/nginx/html and serves it. Repopulated on every rebuild. + # one-shot `vue` container writes the built SPA here and exits; Caddy mounts + # it at /srv/www and serves it. Repopulated on every rebuild. vue_dist: # Caddy's /config: the JSON it autosaves on each config load. Nothing in it # is needed across restarts (the Caddyfile is the source); named only so @@ -109,103 +110,17 @@ services: networks: - app-network - # The only public entrypoint. Terminates TLS, serves the SPA, reverse-proxies - # everything else. Its config is chosen at container start — see - # nginx/entrypoint.sh for the DEV_MODE / cert-present / bootstrap decision. - # - # START ORDERING: these `depends_on` entries are the plain list form, which - # only waits for each container to be *created and started*, NOT for it to be - # ready or healthy. That is deliberate — nginx's `resolver 127.0.0.11` means - # upstreams are resolved per-request, so a late-starting backend produces a - # temporary 502 rather than a failed nginx boot. The one ordering nginx - # genuinely cares about (the Vue build finishing) is handled by the polling - # loop in its entrypoint, because depends_on cannot express "wait for a - # one-shot container to exit successfully" here. - nginx: - build: - context: ./nginx - dockerfile: Dockerfile - container_name: nginx - env_file: ./.env - restart: always - depends_on: - - vue - - backend - - icecast2 - - gitea - - silverbullet - - silverbullet-public - - python - - jobs - - activity-tracker - - dozzle - networks: - app-network: - # The site's public names, resolving to this container for everything - # on app-network. They exist for cloudflared: its tunnel origin is - # https://www.DOMAIN, which lands here over the bridge with a name the - # Let's Encrypt certificate actually covers, so the tunnel verifies - # TLS with no extra dashboard settings (`https://nginx` would fail the - # name check). Any other container that calls the public site now - # reaches nginx directly instead of hairpinning through the internet. - aliases: - - ${DOMAIN} - - www.${DOMAIN} - # Fixed for cloudflared's extra_hosts (see there): an alias only - # exists while nginx is running, and this address is pinned to the - # same names for when it is not. Top of the /16 beside cloudflared's, - # away from docker's dynamic allocations. - ipv4_address: 172.28.255.251 - ports: - - 80:80 - - 443:443 - volumes: - # Shared with certbot: the cert store nginx reads and certbot writes. - # PERSISTENT, and private key material — gitignored, never commit. - - ./certbot/conf:/etc/letsencrypt - # Shared with certbot: the ACME HTTP-01 challenge webroot. certbot drops - # tokens in, nginx serves them on port 80. - - ./certbot/www:/var/www/certbot - - uploads:/uploads - # The SPA written by the one-shot `vue` container. - - vue_dist:/etc/nginx/html - # The JSON request-body log (nginx/payload_log.conf), kept on the host so - # it survives rebuilds and the `traffic` container can tail it. Grows - # without bound unless rotated — see DEPLOYMENT.md. - - ./logs/nginx:/var/log/nginx/payloads - # restart: always only acts when nginx's master exits. On 2026-10-19 the - # worker stalled while the master lived, and the site was down 4.6 hours - # with the container "Up". /nginx-health is answered by a worker, so a - # stall shows here; Docker only marks it unhealthy, and the `autoheal` - # label is what gets it restarted (see the autoheal service). Plain HTTP - # on :80 so it also passes in the first-boot setup config, which has no - # :443; the workers that serve :80 are the ones serving TLS. - healthcheck: - test: ["CMD", "curl", "-fsS", "--max-time", "5", "-o", "/dev/null", "http://127.0.0.1/nginx-health"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 30s - labels: - - autoheal=true - - # The replacement edge (caddy/Caddyfile), RUNNING BESIDE nginx until the - # cutover. While it does: - # - it is reachable only from this host, on 127.0.0.1:8880 (http) and - # 127.0.0.1:8443 (https), so the public site is still nginx; - # - it holds no network aliases and a fixed address of its own, so nothing - # on app-network (cloudflared included) is sent to it; - # - it obtains its certificates over DNS-01 into ./caddy/data, which needs - # no inbound port, so they are ready before it takes over; - # - autoheal ignores it. - # Compare the two with caddy/edge_test.sh (its header has the commands). - # The cutover gives it nginx's ports, aliases, address and autoheal label, - # and removes nginx and certbot. + # The only public entrypoint: Caddy (caddy/Caddyfile). Terminates TLS, + # serves the SPA, reverse-proxies everything else, and obtains and renews + # its own certificates over DNS-01 into ./caddy/data, with no reload and no + # inbound port. It replaced nginx and the certbot container on 2026-11-17; + # nginx/ and certbot/ stay in the repo until that has settled, as the + # rollback. # # ENVIRONMENT: an explicit list, not the whole .env, so the edge never sees # the database password or the JWT secret. A variable the Caddyfile reads # must be added here, or it reaches Caddy empty. The ${X:-default} forms - # are the defaults nginx/entrypoint.sh gave the optional services; they live + # are the defaults nginx's entrypoint gave the optional services; they live # here because Caddy's own {$X:default} keeps a variable that is set but # empty, which is how a blank line in .env arrives. # @@ -240,66 +155,67 @@ services: - CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-} networks: app-network: - # Beside nginx's .251 and cloudflared's .250. Becomes .251 at the - # cutover. - ipv4_address: 172.28.255.252 + # The site's public names, resolving to this container for everything + # on app-network. They exist for cloudflared: its tunnel origin is + # https://www.DOMAIN, which lands here over the bridge with a name the + # Let's Encrypt certificate actually covers, so the tunnel verifies + # TLS with no extra dashboard settings (`https://caddy` would fail the + # name check). Any other container that calls the public site now + # reaches Caddy directly instead of hairpinning through the internet. + aliases: + - ${DOMAIN} + - www.${DOMAIN} + # Fixed for cloudflared's extra_hosts (see there): an alias only + # exists while Caddy is running, and this address is pinned to the + # same names for when it is not. Top of the /16 beside cloudflared's, + # away from docker's dynamic allocations. + ipv4_address: 172.28.255.251 ports: - - 127.0.0.1:8880:80 - - 127.0.0.1:8443:443 + - 80:80 + - 443:443 volumes: # The certificates, their keys and the ACME account. PERSISTENT and # private key material: gitignored, never commit. Losing it only costs - # a re-issue on the next start (about a minute over DNS-01). + # a re-issue on the next start (seconds over DNS-01), during which the + # tunnel, which verifies the certificate, serves 502s. - ./caddy/data:/data - caddy_config:/config - uploads:/srv/uploads:ro # The SPA written by the one-shot `vue` container. - vue_dist:/srv/www:ro - # The JSON request-body log, tailed by `traffic` after the cutover. + # The JSON request-body log, kept on the host so it survives rebuilds + # and the `traffic` container can tail it. Caddy rotates it itself + # (50 MiB, five files kept). - ./logs/caddy:/var/log/caddy - # Answered by Caddy itself (http://127.0.0.1 in the Caddyfile). The image - # has busybox wget, not curl. + # restart: always only acts when the process exits. On 2026-10-19 nginx's + # worker stalled while its master lived, and the site was down 4.6 hours + # with the container "Up". /caddy-health (http://127.0.0.1 in the + # Caddyfile) is answered by Caddy's own server, so a hung server shows + # here; Docker only marks it unhealthy, and the `autoheal` label is what + # gets it restarted (see the autoheal service). The image has busybox + # wget, not curl. healthcheck: test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/caddy-health"] interval: 30s timeout: 10s retries: 3 start_period: 30s - - # Obtains the cert once, then renews every 12h forever. Disabled in dev via - # the `disabled` profile in docker-compose.dev.yml. Note this is the stock - # certbot image with our script bind-mounted over the entrypoint, so editing - # certbot/entrypoint.sh takes effect on restart with no rebuild. Version is - # pinned so a certbot release cannot change behaviour under us on redeploy. - # The dns-cloudflare variant is plain certbot plus the Cloudflare DNS plugin: - # with CLOUDFLARE_DNS_API_TOKEN set it validates over DNS, so renewal needs - # no inbound port, and without it falls back to the webroot method. - certbot: - image: certbot/dns-cloudflare:v3.1.0 - container_name: certbot - volumes: - - ./certbot/entrypoint.sh:/entrypoint.sh - - ./certbot/conf:/etc/letsencrypt - - ./certbot/www:/var/www/certbot - entrypoint: ["/entrypoint.sh"] - env_file: - - .env - networks: - - app-network + labels: + - autoheal=true # Cloudflare Tunnel: an OUTBOUND connection from here to Cloudflare's edge, - # which then forwards visitors' requests back down it to nginx. Nothing is + # which then forwards visitors' requests back down it to Caddy. Nothing is # published to the host, so with the tunnel live the router's 80/443 # forwards can be closed. The tunnel is "remotely managed": its public # hostnames and origin settings live in the Cloudflare dashboard, and this # container only needs the token. The routing set up there (DEPLOYMENT.md, - # "Cloudflare Tunnel") is https://www.DOMAIN, which nginx's network aliases - # resolve to nginx itself, so the certificate verifies; nginx's config, + # "Cloudflare Tunnel") is https://www.DOMAIN, which Caddy's network aliases + # resolve to Caddy itself, so the certificate verifies; Caddy's config, # redirects and security headers apply to tunnel traffic exactly as to # direct traffic, and both paths work side by side. # - # Fixed address so nginx can trust the CF-Connecting-IP header from this - # container and no other (set_real_ip_from in nginx.conf.template). It sits + # Fixed address so Caddy can trust the CF-Connecting-IP header from this + # container and no other (trusted_proxies in caddy/Caddyfile). It sits # at the top of the /16 because docker hands out dynamic addresses from the # bottom; the two must change together. # @@ -313,12 +229,12 @@ services: environment: - TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-} depends_on: - - nginx - # Pins the tunnel origin's names to nginx's fixed address. nginx's aliases + - caddy + # Pins the tunnel origin's names to Caddy's fixed address. Its aliases # vanish while it is stopped (every deploy and the weekly maintenance), and # docker's DNS then forwards the name to public DNS, which answers with # Cloudflare's own IPs: the tunnel sent requests back to the edge and - # visitors got error 1000. /etc/hosts wins over DNS, so a stopped nginx is + # visitors got error 1000. /etc/hosts wins over DNS, so a stopped Caddy is # now a refused connection, which cloudflared reports as a plain 502. extra_hosts: - "${DOMAIN}:172.28.255.251" @@ -360,7 +276,7 @@ services: # read-only into silverbullet-public (the /notes/ site). - ${OBSIDIAN_DIR}:/backend/notes - ./logs:/backend/logs - # Same named volume nginx serves at /uploads/ — backend writes, nginx reads. + # Same named volume Caddy serves at /uploads/ — backend writes, Caddy reads. - uploads:/backend/uploads # Shared with icecast2, which plays these as the radio fallback playlist; # the backend reads them to report what is queued. @@ -418,12 +334,12 @@ services: # listeners connect to, proxied at /radio/) and liquidsoap (the source that # feeds it). See icecast2/entrypoint.sh. # - # This is the only non-nginx service that publishes a host port, and it has + # This is the only non-Caddy service that publishes a host port, and it has # to: LIQUIDSOAP_HARBOR_PORT is the live-DJ input. A broadcasting client # (e.g. butt) connects straight to the Pi on that port, by its Tailscale # name now that the public domain resolves to Cloudflare, with the icecast # source password and pre-empts the fallback playlist. It is NOT proxied - # through nginx because it is a raw source protocol, not HTTP the SPA uses. + # through Caddy because it is a raw source protocol, not HTTP the SPA uses. # Note the host:container mapping uses the same variable on both sides, so # the published port always matches what liquidsoap actually binds. icecast2: @@ -442,7 +358,7 @@ services: - "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}" # Browser-based editor for the vault, so notes are editable from a phone. - # Proxied at /sb/ behind the nginx admin gate. The public site at /notes/ is + # Proxied at /sb/ behind Caddy's admin gate. The public site at /notes/ is # a SECOND, read-only SilverBullet over the same folder (silverbullet-public, # below). # @@ -460,7 +376,7 @@ services: environment: SB_PORT: "${SILVERBULLET_PORT:-3000}" # The app builds its service-worker scope and asset URLs from this, which - # is why nginx must NOT strip the /sb/ prefix. See nginx.conf.template. + # is why Caddy must NOT strip the /sb/ prefix. See caddy/routes.caddy. SB_URL_PREFIX: /sb # Only .obsidian: it is editor config and plugin JS, not notes. # @@ -495,14 +411,14 @@ services: # URL /notes/private/x (server-rendered with the # note's content), nor /.fs/.git/ — SilverBullet # only applies it to listing (checked in 2.11.0). - # 2. nginx deny blocks 404 any private/ or templates/ segment and any + # 2. Caddy deny rules 404 any private/ or templates/ segment and any # nested dot-folder under /notes/; this is what # actually closes those holes. Keep its folder list # in step with the one below. # 3. SB_REVISIONS the default ("unmanaged") serves history from the # vault's own .git, i.e. every version of every file # including private/ and deleted ones. Disabled here, - # and nginx blocks /notes/.revisions as well. + # and Caddy blocks /notes/.revisions as well. # # SB_READ_ONLY rejects writes server-side and also disables the shell and the # /.proxy endpoint (otherwise an open fetch proxy). The :ro mount is a second @@ -519,13 +435,13 @@ services: - app-network environment: SB_PORT: "${SILVERBULLET_PUBLIC_PORT:-3000}" - # Same reason as the editor's SB_URL_PREFIX: nginx must not strip /notes/. + # Same reason as the editor's SB_URL_PREFIX: Caddy must not strip /notes/. SB_URL_PREFIX: /notes SB_READ_ONLY: "true" SB_REVISIONS: disabled # Newline separated (commas are silently ignored). Gitignore semantics, # so these match at any depth. Must match the folder list in the - # /notes/ deny regex in nginx/nginx_routes.conf.template, or a new entry here is + # /notes/ deny regex in caddy/routes.caddy, or a new entry here is # hidden from the list but still publicly fetchable. SB_SPACE_IGNORE: | private/ @@ -540,7 +456,7 @@ services: # writes, and pulls what Obsidian pushes from elsewhere. # # WHY A SEPARATE CONTAINER and not SilverBullet's own shell backend: enabling - # that would give anyone who gets past the nginx admin gate command execution + # that would give anyone who gets past Caddy's admin gate command execution # inside the container. Since SilverBullet itself runs with no SB_USER, that # gate is the only thing protecting it, so the blast radius stays here. silverbullet-git: @@ -549,8 +465,8 @@ services: restart: always networks: - app-network - # The vault's remotes are ssh://git@DOMAIN:2222/..., but nginx's network - # aliases make DOMAIN resolve to nginx on app-network, which has no :2222, + # The vault's remotes are ssh://git@DOMAIN:2222/..., but Caddy's network + # aliases make DOMAIN resolve to Caddy on app-network, which has no :2222, # so every pull and push was refused. /etc/hosts wins over Docker's DNS, so # this sends DOMAIN back to the host, where gitea publishes 2222. The name # is unchanged, so known_hosts still matches. @@ -576,7 +492,7 @@ services: # ssh will not run for a uid with no passwd entry; see the file's comment. - ./silverbullet/passwd:/etc/passwd:ro - # FastAPI side-service, proxied at /py/ with the prefix stripped by nginx. + # FastAPI side-service, proxied at /py/ with the prefix stripped by Caddy. # ROOT_PATH=/py tells FastAPI it is mounted under a prefix so the generated # OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own # routes are written relative to /. @@ -584,7 +500,7 @@ services: # than `env_file: ./.env` — it only gets the variables it needs and never # sees the database password, Spotify secrets, or the other API keys. # CLAUDE_API_KEY is the one secret on the list: the rowing photo reader - # (POST /internal/rowing/read, called by the backend, blocked at nginx) + # (POST /internal/rowing/read, called by the backend, blocked at Caddy) # makes its Claude call here. python: build: @@ -616,10 +532,10 @@ services: # database role of its own. A variable the tracker reads must be added to # the list below as well as .env.example. # - # It has no login. nginx's auth_request gates /jobs/ like /sb/ (except the + # It has no login. Caddy's admin gate gates /jobs/ like /sb/ (except the # bearer-token capture API and the userscript), and the tracker checks # again itself: AUTH_VALIDATE_URL is the backend's validate-admin route - # (the one nginx's auth_request uses), which it asks with the visitor's + # (the one Caddy's admin gate uses), which it asks with the visitor's # cookies on each admin request. # # ./jobs-data holds the Microsoft Graph session and the capture token. The @@ -764,7 +680,7 @@ services: # Two kinds of auth. Collectors send per-device bearer keys, made on the # tracker's /tracker/setup page or with `docker exec activity-tracker # tracker apikey create`. The dashboard and setup pages have no login of - # their own: nginx's auth_request gates them like /sb/ (everything but + # their own: Caddy's admin gate gates them like /sb/ (everything but # /tracker/api/v1/ and the userscript), and like jobs the tracker also asks # AUTH_VALIDATE_URL (the backend's validate-admin) with the visitor's # cookies and sends anyone else to /admin/login. @@ -782,9 +698,9 @@ services: - TRACKER_TZ=${TRACKER_TZ:-} - AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin - # Echoes nginx's JSON request-body log to its own stdout, and does nothing + # Echoes Caddy's JSON request-body log to its own stdout, and does nothing # else. It exists so Dozzle shows the payloads as a stream of their own, - # rendered as JSON fields, instead of interleaved with nginx's compact access + # rendered as JSON fields, instead of interleaved with Caddy's compact access # log and error output. -F re-opens the file after rotation; -n0 skips the # backlog on restart, which stays in the file on the host. traffic: @@ -794,10 +710,10 @@ services: command: ["tail", "-n0", "-F", "/logs/payloads.log"] network_mode: none volumes: - - ./logs/nginx:/logs:ro + - ./logs/caddy:/logs:ro # Dozzle: a live, searchable web view of every container's logs, served at - # /dozzle/ behind the admin login (nginx/nginx_routes.conf.template). The + # /dozzle/ behind the admin login (caddy/routes.caddy). The # `traffic` container is the one to watch for incoming request bodies. # # The Docker socket is mounted :ro, but that only stops the file being @@ -818,7 +734,7 @@ services: # Restarts any container labelled autoheal=true once Docker marks it # unhealthy, which Docker itself never does (restart policies only see the - # process exit). Only nginx carries the label today; give it to another + # process exit). Only caddy carries the label today; give it to another # service with a healthcheck to cover that one too. It polls every 5s. # # It needs the Docker socket read-write to restart things, which is root on @@ -844,16 +760,16 @@ services: - /var/run/docker.sock:/var/run/docker.sock # S3-compatible object store holding public uploads (the `uploads` bucket). - # The backend writes to it on :3900 once S3_ENDPOINT is set in .env; nginx + # The backend writes to it on :3900 once S3_ENDPOINT is set in .env; Caddy # serves /uploads/ from it anonymously on :3902, falling back to the # `uploads` volume; garage-webui manages it via :3903. Nothing is published # to the host. Config is garage/garage.toml (no secrets in it); the two # secrets come from .env through the explicit list below. # - # Nothing depends on this container being up. nginx is deliberately NOT - # given it in depends_on: its upstream is a variable, so a missing or - # crash-looping garage only makes bucket-only files 404 (everything on the - # volume is still served), never nginx's boot; and the backend falls back + # Nothing depends on this container being up. Caddy is deliberately NOT + # given it in depends_on: it resolves garage when it dials it, so a missing + # or crash-looping garage only makes bucket-only files 404 (everything on + # the volume is still served), never Caddy's start; and the backend falls back # to the volume when a write fails. # # FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access). @@ -879,9 +795,9 @@ services: retries: 3 start_period: 10s - # Admin web UI for Garage, served at /garage/ behind the nginx admin gate. + # Admin web UI for Garage, served at /garage/ behind Caddy's admin gate. # Manages buckets and keys, and browses/uploads/deletes objects. Its own - # login (AUTH_USER_PASS) is left unset because nginx's auth_request already + # login (AUTH_USER_PASS) is left unset because Caddy's admin gate already # requires the site admin — and it holds the admin token, so never publish # its port. It reads the s3/web settings from garage.toml; the token comes # from .env instead, since the file has none. diff --git a/garage/bootstrap.sh b/garage/bootstrap.sh index 7d45d81..57992a3 100755 --- a/garage/bootstrap.sh +++ b/garage/bootstrap.sh @@ -25,7 +25,7 @@ # with the same credentials and the backend needs no change. # 4. Grants that key read+write on the bucket. garage-webui also browses # with it: it borrows the first key that has access to a bucket. -# 5. Opens the bucket on the website endpoint, which is what nginx serves +# 5. Opens the bucket on the website endpoint, which is what Caddy serves # /uploads/ from, anonymously. # # ENV / .env diff --git a/garage/garage.toml b/garage/garage.toml index f296288..e64ce88 100644 --- a/garage/garage.toml +++ b/garage/garage.toml @@ -19,7 +19,7 @@ # garage/bootstrap.sh imports); garage-webui browses through it. # 3901 RPC between Garage nodes. Only this node talks to itself. # 3902 Website endpoint. Serves a bucket ANONYMOUSLY, choosing it from the -# Host header: "", so nginx's /uploads/ location +# Host header: "", so Caddy's /uploads/ route # sends `Host: uploads.web.garage`. Only buckets that bootstrap.sh # opened with `garage bucket website --allow` are served. # 3903 Admin API, used by garage-webui and authenticated by admin_token. diff --git a/gitea-runner/run.sh b/gitea-runner/run.sh index 7c31fa3..a9cf4d1 100755 --- a/gitea-runner/run.sh +++ b/gitea-runner/run.sh @@ -20,8 +20,8 @@ # rather than retrying, so the loop polls (forever, by design — there is no # sensible timeout when the answer is "wait longer") until Gitea responds. # It targets localhost:3000, the port docker-compose.yml publishes directly, -# NOT the public /gitea/ path through nginx — so the runner keeps working -# even while TLS or nginx is broken. +# NOT the public /gitea/ path through Caddy — so the runner keeps working +# even while TLS or Caddy is broken. # # THE REGISTRATION TOKEN (one-shot, and easy to get wrong) # GITEA_RUNNER_REGISTRATION_TOKEN comes from ./.env and is generated in the diff --git a/gitea/config/app.ini.template b/gitea/config/app.ini.template index 72cb7ae..bea5889 100644 --- a/gitea/config/app.ini.template +++ b/gitea/config/app.ini.template @@ -14,7 +14,7 @@ ; Gitea generates one itself on first run and writes it into the live app.ini. ; ; SETTINGS WORTH KNOWING -; ROOT_URL must match the public path nginx serves Gitea at (/gitea/), or +; ROOT_URL must match the public path Caddy serves Gitea at (/gitea/), or ; every link, clone URL and OAuth redirect Gitea emits will be wrong. ; START_SSH_SERVER = true with SSH_PORT 2222: the rootless image cannot bind ; 22 and cannot use the host's sshd, so Gitea runs its own Go SSH server. @@ -25,10 +25,11 @@ ; MagicDNS name, not the public domain: SSH ; (22 and 2222) is not forwarded by the router, so the SSH clone URL Gitea ; shows only works from a device on the tailnet. HTTPS clones go through -; nginx at ROOT_URL and stay public. +; Caddy at ROOT_URL and stay public. ; REVERSE_PROXY_LIMIT = 1 / TRUSTED_PROXIES = * : trust exactly one hop of -; X-Forwarded-For, i.e. our nginx, so Gitea logs real client IPs. This is -; only safe because nginx is the sole edge. +; X-Forwarded-For, i.e. our Caddy, so Gitea logs real client IPs. Caddy +; sends a single entry, the visitor (its `proxy` snippet). This is only +; safe because Caddy is the sole edge. ; INSTALL_LOCK = true skips the first-run web installer. ; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up. ; OFFLINE_MODE = true — no calls out to gravatar/CDNs. diff --git a/icecast2/entrypoint.sh b/icecast2/entrypoint.sh index cb9ea3e..cf5ac08 100755 --- a/icecast2/entrypoint.sh +++ b/icecast2/entrypoint.sh @@ -4,7 +4,7 @@ # # WHAT IT DOES # This one container holds two cooperating daemons: -# icecast2 - the HTTP streaming server listeners connect to. nginx +# icecast2 - the HTTP streaming server listeners connect to. Caddy # proxies /radio/ to it. # liquidsoap - the *source*: it decides what audio to play and pushes a # single MP3 stream into icecast's mount point. @@ -17,7 +17,7 @@ # # THE TEMPLATING STEP # Both configs are rendered by bare `envsubst` (no allow-list) because unlike -# the nginx templates, neither icecast.xml nor stream.liq has any legitimate +# the old nginx templates, neither icecast.xml nor stream.liq has any legitimate # dollar-token of its own — every ${VAR} in them is meant to be substituted, # so an unrestricted envsubst is safe here. NOTE the consequence: any # referenced variable that is unset silently becomes an empty string, which diff --git a/icecast2/stream.liq.template b/icecast2/stream.liq.template index 15c6d5d..f09ed5b 100644 --- a/icecast2/stream.liq.template +++ b/icecast2/stream.liq.template @@ -29,7 +29,7 @@ # # OUTPUT # Pushes to icecast on localhost (same container) at ICECAST_MOUNT, which is -# what nginx exposes at /radio/. fallible=true tells liquidsoap this output +# what Caddy exposes at /radio/. fallible=true tells liquidsoap this output # is allowed to fail and be retried, instead of aborting the script — that is # what makes the `sleep 2` startup race in the entrypoint survivable. # diff --git a/python/Dockerfile b/python/Dockerfile index e6fb9fc..ac626c5 100644 --- a/python/Dockerfile +++ b/python/Dockerfile @@ -11,7 +11,7 @@ # immediately instead of sitting in a buffer — both are standard for # containerised Python and the second one matters for debugging. # -# ROOT_PATH=/py: nginx proxies /py/ and STRIPS the prefix, so the app's routes +# ROOT_PATH=/py: Caddy proxies /py/ and STRIPS the prefix, so the app's routes # are written relative to /. --root-path tells FastAPI it is nonetheless # mounted under a prefix, so the OpenAPI schema and Swagger UI emit correct # /py/... URLs. Without it, /py/docs loads but cannot call anything. @@ -21,7 +21,7 @@ # Both have defaults here so the image runs standalone; docker compose normally # supplies them. # -# EXPOSE 8000 is documentation only — the port is not published; nginx reaches +# EXPOSE 8000 is documentation only — the port is not published; Caddy reaches # it over app-network. # ============================================================================= FROM python:3.12-slim diff --git a/python/README.md b/python/README.md index 3dc9abf..67b014a 100644 --- a/python/README.md +++ b/python/README.md @@ -26,7 +26,7 @@ driven from a plain script. ## Endpoints Paths below are as the service sees them; from a browser prefix everything with -`/py` (see *Behind nginx*). +`/py` (see *Behind Caddy*). | Method | Path | What it does | | --- | --- | --- | @@ -72,9 +72,9 @@ can't be shared), and identical requests are cached for 10 minutes. Routes under `/internal/` (today only the rowing reader) are the only ones in this service that are **not public**. Each spends a paid Claude call and has no auth of its own — the admin check happens in the Go backend, which calls the container -directly (`http://python:8000/...`). Two things keep them internal: nginx +directly (`http://python:8000/...`). Two things keep them internal: Caddy answers `/py/internal/` with a 404, and the route itself 404s any request -carrying the `X-Real-IP` / `X-Forwarded-For` headers nginx adds to everything +carrying the `X-Real-IP` / `X-Forwarded-For` headers Caddy adds to everything it proxies (the Go backend sends neither). Their plumbing is in two places, shared by any route added later: @@ -127,7 +127,7 @@ they see this service's error rather than their own. in `main.py`'s docstring and bump the FastAPI `version`. 3. **Tests** `tests/test_.py`, copied from `test_rowing.py`: fake the client with `monkeypatch.setattr(thing, "_client", ...)`. -4. **Docs**: the endpoint table and a section here. Nothing to do in nginx — +4. **Docs**: the endpoint table and a section here. Nothing to do in Caddy — it already 404s everything under `/py/internal/`. If third-party text goes into the prompt (a web page, an email), say in the @@ -149,19 +149,22 @@ Errors: 502 with a fixed `detail` (`failed to process image`, `empty response from image processor`, `failed to parse image data`) that the Go handler relays to the admin; 503 if `CLAUDE_API_KEY` is unset. -## Behind nginx +## Behind Caddy -`nginx/nginx.conf.template` proxies `/py/` to this container and **strips the +`caddy/routes.caddy` proxies `/py/` to this container and **strips the prefix**, so routes here are written relative to `/`. `--root-path /py` (set on the uvicorn command line via `ROOT_PATH`) is what keeps the generated docs and OpenAPI URLs correct behind that rewrite. -The hotel routes get their own nginx location with `proxy_buffering off` and a -300s read timeout, because otherwise nginx would hold the whole NDJSON stream -until it finished. The app also sends `X-Accel-Buffering: no` as a belt-and- -braces version of the same thing. The internal deadlines in `travelodge.py` -(200s for a search, 240s for a scan) exist to finish *before* that 300s cut, and -return partial results with `summary.truncated = true` instead of dying. +The hotel routes get their own Caddy route with `flush_interval -1` and their +own rate limit, so each NDJSON line reaches the browser as it is written. The +app also sends `X-Accel-Buffering: no`, which Caddy ignores but an nginx-style +proxy would need. The internal deadlines in `travelodge.py` (200s for a search, +240s for a scan) were set to finish before nginx's old 300s cut; Caddy sets no +upstream timeout, but they still bound a run and return partial results with +`summary.truncated = true` instead of dying. Through the tunnel, Cloudflare +gives up on an origin that sends nothing for 100s, which the streaming routes +avoid by writing progress lines. Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, the optional `TFL_APP_KEY` (see below), and `CLAUDE_API_KEY` and `CLAUDE_MODEL` for the internal Claude route. Dev mode mounts `python/app` and runs diff --git a/python/app/main.py b/python/app/main.py index 4569868..ebe675d 100644 --- a/python/app/main.py +++ b/python/app/main.py @@ -1,6 +1,6 @@ """Small Python API service. -Nginx proxies https://www./py/... to this container and strips the +Caddy proxies https://www./py/... to this container and strips the /py prefix, so routes here are defined relative to "/". FastAPI's root_path (set via --root-path on the uvicorn command line) keeps the generated docs at /py/docs working behind the proxy. @@ -14,7 +14,7 @@ Endpoints POST /hotels/search/stream same search, streamed as NDJSON POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON POST /internal/rowing/read read a rowing display photo with Claude - (Go backend only - not reachable through nginx) + (Go backend only - not reachable through Caddy) All the hotel work lives in `travelodge`; this module is the HTTP skin around it - request validation, a response cache, the one-search-at-a-time guard, and @@ -62,7 +62,7 @@ class Greeting(BaseModel): @app.get("/", response_model=Greeting, summary="Service index") def index() -> Greeting: - """Point a curious caller at the docs (which live at /py/docs via nginx).""" + """Point a curious caller at the docs (which live at /py/docs via Caddy).""" return Greeting(message="Python API is running. See /py/docs for the schema.") @@ -558,10 +558,13 @@ def _ndjson(events) -> StreamingResponse: line, with no event-type framing to strip. `exclude_none=True` keeps the lines small, so absent keys must be treated as null by the reader. - X-Accel-Buffering: no is essential - without it nginx buffers the whole - response and the user sees nothing until the search finishes, defeating the - point of streaming. Cache-Control: no-cache stops any intermediary storing - a partial stream. + X-Accel-Buffering: no tells an nginx-style proxy not to buffer the + response; without it the user would see nothing until the search finished, + defeating the point of streaming. Caddy, the edge now, ignores the header + and passes a chunked response on as it is written (its /py/hotels route + also sets flush_interval -1), so the header is insurance for whatever + proxy might sit here next. Cache-Control: no-cache stops any intermediary + storing a partial stream. """ return StreamingResponse( (ev.model_dump_json(exclude_none=True) + "\n" for ev in events), @@ -651,7 +654,7 @@ def hotel_scan_stream(req: HotelScanRequest) -> StreamingResponse: # Internal: the routes the Go backend calls # --------------------------------------------------------------------------- # def _internal_only(request: Request) -> None: - """Refuse a request that arrived through nginx. + """Refuse a request that arrived through the edge proxy (Caddy). Every other route in this service is public, but the internal ones spend a paid Claude call per request and have no auth of their own - the admin @@ -659,10 +662,12 @@ def _internal_only(request: Request) -> None: directly over app-network. Two layers keep the outside world off it, because either alone is one config edit away from being lost: - 1. nginx answers /py/internal/ with a 404 (both templates). - 2. nginx stamps X-Real-IP and X-Forwarded-For on everything it proxies - here, and a client cannot make it omit them; the Go backend sends - neither. So their presence means the request came from outside. + 1. Caddy answers /py/internal/ with a 404 (caddy/routes.caddy, dev and + production alike). + 2. Caddy stamps X-Real-IP and X-Forwarded-For on everything it proxies + here (the `proxy` snippet), and a client cannot make it omit them; + the Go backend sends neither. So their presence means the request + came from outside. 404 rather than 403, so the route is indistinguishable from one that does not exist. @@ -732,7 +737,7 @@ class RowingReadRequest(BaseModel): response_model=rowing.RowingReading, summary="Read time and distance off a rowing machine display", description=( - "Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through nginx. " + "Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through Caddy. " "Sends the image to Claude and returns the three numbers it read. No plausibility checking " "happens here - the caller owns the sanity bounds." ), @@ -743,7 +748,7 @@ def rowing_read(req: RowingReadRequest) -> rowing.RowingReading: A plain `def`, so FastAPI runs it in the threadpool and the blocking Claude call does not stall the event loop the hotel streams are served from. - Responds 404 (came through nginx), 503 (no API key) or 502 (Claude failed + Responds 404 (came through Caddy), 503 (no API key) or 502 (Claude failed or returned something unparseable) by way of `_internal_claude_route`. The 502 detail is one of rowing.read_display's fixed messages, which the Go handler passes on to the admin verbatim. diff --git a/python/app/travelodge.py b/python/app/travelodge.py index 204ea8a..d7d7960 100644 --- a/python/app/travelodge.py +++ b/python/app/travelodge.py @@ -55,7 +55,9 @@ Time budgets Every network path takes an optional `deadline` (a time.monotonic() value). Passing it down instead of using a wall-clock timeout lets a long run degrade gracefully: work already done is returned with summary["truncated"] = True - instead of the whole request dying at the nginx 300s proxy timeout. + instead of the whole request being cut off by a proxy timeout. (nginx cut at + 300s; Caddy sets no upstream timeout, but the budgets below still bound a + run, and Cloudflare gives up on an origin that sends nothing for 100s.) """ import logging @@ -102,8 +104,9 @@ ORIGINS = { # Rough Greater London bounding box for custom "lat,lon" origins. LONDON_BOX = (51.25, 51.75, -0.55, 0.35) # min lat, max lat, min lon, max lon -# Wall-clock budget for one run_search call. Nginx cuts the connection at -# 300s, so stop pricing transport well before that and return what we have. +# Wall-clock budget for one run_search call. Set when nginx cut the connection +# at 300s: stop pricing transport well before that and return what we have. +# Caddy has no such cut, but the budget still keeps a run bounded. SEARCH_DEADLINE_S = 200 # A date-range scan fetches one Travelodge search per candidate night, then diff --git a/python/tests/test_ndjson.py b/python/tests/test_ndjson.py index 6c297f7..6585063 100644 --- a/python/tests/test_ndjson.py +++ b/python/tests/test_ndjson.py @@ -3,7 +3,7 @@ The Vue frontend splits the response on newlines and JSON-parses each line, so the contract under test is: one complete JSON object per line, the documented event names, the right payload key per event kind, `exclude_none` dropping -absent keys, and the framing headers that stop nginx buffering the stream. +absent keys, and the framing headers that stop a buffering proxy holding the stream. No scraping and no network happens here: `_run_events` takes the upstream generator as a callable, so a fake generator stands in for travelodge and the @@ -134,8 +134,8 @@ def test_ndjson_omits_none_fields(): def test_ndjson_headers_defeat_proxy_buffering(): response = main._ndjson(iter([])) assert response.media_type == "application/x-ndjson" - # Without X-Accel-Buffering nginx holds the whole response and the stream - # is pointless. + # Without X-Accel-Buffering an nginx-style proxy holds the whole response + # and the stream is pointless. (Caddy streams it regardless.) assert response.headers["x-accel-buffering"] == "no" assert response.headers["cache-control"] == "no-cache" diff --git a/python/tests/test_rowing.py b/python/tests/test_rowing.py index 66a5b69..1e874cd 100644 --- a/python/tests/test_rowing.py +++ b/python/tests/test_rowing.py @@ -125,8 +125,8 @@ def test_route_returns_reading(fake_claude, http): @pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"]) -def test_route_refuses_requests_proxied_by_nginx(fake_claude, http, header): - """nginx sets these on everything it forwards; the Go backend sets neither.""" +def test_route_refuses_requests_proxied_by_the_edge(fake_claude, http, header): + """Caddy sets these on everything it forwards; the Go backend sets neither.""" res = http.post("/internal/rowing/read", json=BODY, headers={header: "203.0.113.9"}) assert res.status_code == 404 assert fake_claude.calls == [] diff --git a/silverbullet/git-sync.sh b/silverbullet/git-sync.sh index ba07737..a7d6bdc 100755 --- a/silverbullet/git-sync.sh +++ b/silverbullet/git-sync.sh @@ -4,7 +4,7 @@ # SilverBullet writes plain markdown straight into the space folder and has no # concept of git, so this sidecar is what keeps the notes repo moving. It is # deliberately a separate container rather than SilverBullet's own shell backend: -# the editor is protected only by the nginx admin gate, and enabling a shell +# the editor is protected only by Caddy's admin gate, and enabling a shell # backend would hand anyone past that gate command execution inside the container. # # ON-DEMAND SYNC diff --git a/vue/Dockerfile b/vue/Dockerfile index 5065153..eecf293 100644 --- a/vue/Dockerfile +++ b/vue/Dockerfile @@ -2,7 +2,7 @@ # Vue frontend image — builds the SPA. # # THIS IS A BUILD CONTAINER, NOT A SERVER. In production the container runs -# `vite build` into /output (the shared vue_dist volume) and EXITS. nginx then +# `vite build` into /output (the shared vue_dist volume) and EXITS. Caddy then # serves those files. Seeing `vue` as Exited(0) in `docker compose ps` is the # success case, not a failure. The dev override replaces the CMD with the Vite # dev server, and then it does stay running. diff --git a/vue/README.md b/vue/README.md index 9e3bea8..c468d82 100644 --- a/vue/README.md +++ b/vue/README.md @@ -14,7 +14,7 @@ npm install npm run dev ``` -The Vite dev server stands in for nginx and proxies four prefixes. Each target +The Vite dev server stands in for Caddy and proxies four prefixes. Each target is an environment variable, read in `vite.config.js` from the shell or from `vue/.env.local`: @@ -22,11 +22,11 @@ is an environment variable, read in `vite.config.js` from the shell or from | --- | --- | --- | --- | | `/api` | `VITE_PROXY_API` | `http://localhost:8080` | Go backend | | `/gitea` | `VITE_PROXY_GITEA` | `http://localhost:3000` | Gitea | -| `/py` | `VITE_PROXY_PY` | `http://localhost:8000` | FastAPI (the `/py` prefix is stripped, as nginx does in production) | +| `/py` | `VITE_PROXY_PY` | `http://localhost:8000` | FastAPI (the `/py` prefix is stripped, as Caddy does in production) | | `/radio` | `VITE_PROXY_RADIO` | `http://localhost:8000` | Icecast2 | **The defaults are not "where the compose stack is".** The stack publishes only -nginx (80/443), Gitea (3000) and the liquidsoap harbor port to the host; the +Caddy (80/443), Gitea (3000) and the liquidsoap harbor port to the host; the backend, the Python service and Icecast are reachable only inside the Docker network. The defaults are each service's own port, i.e. where it listens when you run it directly on the host (`go run .`, `uvicorn app.main:app`). `/py` and @@ -34,10 +34,10 @@ you run it directly on the host (`go run .`, `uvicorn app.main:app`). `/py` and can be right at a time — normally `/py`, with the radio simply reading as offline. -To use a running compose stack instead, point the prefix at its nginx, e.g. +To use a running compose stack instead, point the prefix at its Caddy, e.g. `VITE_PROXY_API=http://localhost npm run dev`. That works for `/api`, `/gitea` and `/radio`, which are forwarded with the path intact. It does not work for -`/py`, because the proxy strips the prefix nginx routes on — `VITE_PROXY_PY` +`/py`, because the proxy strips the prefix Caddy routes on — `VITE_PROXY_PY` has to be a bare uvicorn. ## Structure @@ -66,10 +66,10 @@ Two layout shells, defined in `src/router/index.js`: | `/` | DefaultLayout | Landing page (statically imported — it's the first paint): a box canvas, page key `index`; the old fixed page is its starter layout, `views/landing/landingLayout.js` | | `/stp` | DefaultLayout | The personal home page: an ordinary canvas page (the `Page` with slug `stp`) served by the catch-all, see "The /stp canvas" below | | `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin`. The login page is everyone's, admin or not | -| `/account`, `/no-access` | DefaultLayout | `views/account/Account.vue`, guarded by `meta.requiresSignIn`: the gated services a non-admin has been granted. `/no-access` is where nginx's permission gate sends a signed-in visitor without the grant | +| `/account`, `/no-access` | DefaultLayout | `views/account/Account.vue`, guarded by `meta.requiresSignIn`: the gated services a non-admin has been granted. `/no-access` is where Caddy's permission gate sends a signed-in visitor without the grant | | `/automata`, `/hotels` | DefaultLayout | | | `/shrines`, `/shrines/*` | DefaultLayout | All canvas pages via the catch-all: `/shrines` is an index whose links are Link boxes placed by hand | -| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there | +| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); Caddy redirects the old `/cv/jobs` and `/cv/leads` there | | `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts | | `:pathMatch(.*)*` | DefaultLayout | `views/canvas/CanvasPage.vue`: an admin-created canvas page if one exists at the path, else the 404 (with a "create a page here" form for admins) | @@ -118,7 +118,7 @@ const data = await gql(`query { ... }`, variables); It POSTs to `/api/graphql` and throws on an error response with no data. Auth rides along in **HTTP-only cookies** set by the Go backend, so nothing here -touches tokens — the request just has to be same-origin (nginx in production, +touches tokens — the request just has to be same-origin (Caddy in production, the Vite proxy in dev). The backend's REST routes go through `src/api.js`, the same idea for plain JSON: @@ -240,7 +240,7 @@ renders any page's boxes. (`Home3.vue`, now legacy), and the backend creates its `Page` row once at start-up (`ensureStpPage` in `backend/services/database.go`), so it can be renamed, hidden or deleted like any other. - The server refuses slugs that an SPA or nginx route would answer first + The server refuses slugs that an SPA or Caddy route would answer first (`validateSlug` in `backend/graph/page_helpers.go`) — add to that list when adding a route. - **Backgrounds.** Each page key can have its own background (`Background` in @@ -357,10 +357,10 @@ renders any page's boxes. - **Dev** (`npm run dev`): Vite serves the SPA and proxies `/api`, `/gitea`, `/radio` and `/py` to the `VITE_PROXY_*` targets (see Development above and - `vite.config.js`). The `/py` proxy strips the prefix, matching what nginx + `vite.config.js`). The `/py` proxy strips the prefix, matching what Caddy does in production. -- **Production** (`npm run build`): `dist/` is built into the nginx container - and served as static files, with nginx doing the same reverse-proxying. +- **Production** (`npm run build`): `dist/` is written into the `vue_dist` + volume and served as static files by Caddy, which does the same reverse-proxying. `npm run build` is a plain `vite build`. It is also the local check that the app still compiles — there is no test runner or linter. @@ -438,7 +438,7 @@ Note that Tailwind's spacing unit is set to **3px** (not the default 4px), so `p npm run build ``` -In production, the built `dist/` is served by Nginx inside a Docker container (see `../Dockerfile`). +In production, the built `dist/` is served by Caddy from the `vue_dist` volume (see `../Dockerfile` and `../../caddy/`). ## Recommended IDE Setup diff --git a/vue/src/graphql.js b/vue/src/graphql.js index 182e23a..223e970 100644 --- a/vue/src/graphql.js +++ b/vue/src/graphql.js @@ -4,7 +4,7 @@ * * Auth rides along in HTTP-only cookies set by the backend, so no token handling * is needed here — axios sends them automatically because the request is - * same-origin (nginx in production, the Vite proxy in dev). + * same-origin (Caddy in production, the Vite proxy in dev). */ import axios from "axios"; diff --git a/vue/src/router/index.js b/vue/src/router/index.js index b2dd379..53da276 100644 --- a/vue/src/router/index.js +++ b/vue/src/router/index.js @@ -46,7 +46,7 @@ const router = createRouter({ }, // A signed-in user's own page: the gated services they have // been granted. /no-access is the same page with a notice, - // where nginx's permission gate sends a refused visitor. + // where Caddy's permission gate sends a refused visitor. { path: "account", name: "account", @@ -105,7 +105,7 @@ const router = createRouter({ component: () => import("@/views/CV/CV.vue"), }, // /cv/jobs and /cv/leads moved to the job tracker app at - // /jobs/; nginx redirects the old paths. + // /jobs/; Caddy redirects the old paths. ], }, ], diff --git a/vue/src/stores/messages.js b/vue/src/stores/messages.js index 2c2162a..b8760ff 100644 --- a/vue/src/stores/messages.js +++ b/vue/src/stores/messages.js @@ -18,7 +18,7 @@ import { useAuthStore } from "@/stores/auth"; /** * Same-origin ws:// or wss:// URL for the chat socket, derived from the page's - * own protocol and host. Nothing is configurable: nginx (prod) and the Vite + * own protocol and host. Nothing is configurable: Caddy (prod) and the Vite * proxy (dev) both serve /api/ws from the same origin as the page, and the * auth cookies only travel if the origin matches. */ @@ -171,7 +171,7 @@ export const useMessagesStore = defineStore("messages", () => { * surface via `lastError`. * * `private` goes to both: the upload is stored under /uploads/private/, - * which nginx gates behind an admin check, and the message is marked + * which Caddy gates behind an admin check, and the message is marked * private. The two must agree. */ async function uploadAndSendFile(file, isPrivate = false) { diff --git a/vue/src/views/account/Account.vue b/vue/src/views/account/Account.vue index 0823d1c..2653005 100644 --- a/vue/src/views/account/Account.vue +++ b/vue/src/views/account/Account.vue @@ -4,13 +4,13 @@ * page for a signed-in account that is not an admin, listing the gated * services it has been granted (backend/services/permissions.go) as links. * - * `/no-access` is where nginx's permission gate sends a signed-in visitor who + * `/no-access` is where Caddy's permission gate sends a signed-in visitor who * lacks the permission (`@auth_forbidden`, with the refused address in * `?path=`). It is this same page with a notice on top, since "what can I * open instead" is the useful answer to "you can't open that". * * The links are plain , not RouterLinks: every service lives in - * another container behind nginx, so it needs a real page load. + * another container behind Caddy, so it needs a real page load. */ import { ref, computed, onMounted } from "vue"; import { useRoute, useRouter } from "vue-router"; diff --git a/vue/src/views/admin/Admin.vue b/vue/src/views/admin/Admin.vue index a40f194..f5b2ed5 100644 --- a/vue/src/views/admin/Admin.vue +++ b/vue/src/views/admin/Admin.vue @@ -98,7 +98,7 @@ async function handleLogout() { {{ section.label }} + SPA (Caddy serves it at /dozzle/ behind the admin check). --> { "/api": env.VITE_PROXY_API, "/gitea": env.VITE_PROXY_GITEA, "/radio": env.VITE_PROXY_RADIO, - // Python API: nginx strips the /py prefix in production, so do the - // same here. That makes the target a bare uvicorn — pointed at nginx - // the request would arrive without the prefix nginx routes on. + // Python API: Caddy strips the /py prefix in production, so do the + // same here. That makes the target a bare uvicorn — pointed at Caddy + // the request would arrive without the prefix Caddy routes on. "/py": { target: env.VITE_PROXY_PY, rewrite: (path) => path.replace(/^\/py/, ""),