Author SHA1 Message Date
adamfandClaude Opus 5.5 b6baf9c1a2 Serve the Partner Radar demo at radar.DOMAIN
Test and deploy / test (push) Successful in 2m36s
Test and deploy / deploy (push) Successful in 44s
Weekly Maintenance / maintenance (push) Successful in 7m17s
Renovate / renovate (push) Successful in 8m7s
A new Caddy site proxies radar.DOMAIN to radar-web:80, the web container of
the adamf/cto stack, which joins app-network from its own compose project.
It has its own rate-limit zones (radar, radar_login) and answers 503
"offline" when that stack is down. The name is added to Caddy's network
aliases and cloudflared's extra_hosts like www.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 15:50:22 +00:00
adamfandClaude Opus 5.5 30d6056bc0 Move the retired nginx and certbot into .deprecated
Test and deploy / test (push) Successful in 1m35s
Test and deploy / deploy (push) Successful in 1m10s
Nothing references nginx/ or certbot/ since the cutover to Caddy (daa2a46),
so they join quartz, hasura and autoheal in .deprecated/, with a README
entry on how to bring them back. The rollback steps in DEPLOYMENT.md §7 now
revert this commit and then the cutover. The host keeps ./certbot/conf (the
last certbot certificate, valid until 2027-01-20) and ./logs/nginx until the
rollback is no longer wanted; .gitignore still covers certbot/conf and
certbot/www for that reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 23:35:33 +00:00
adamfandClaude Opus 5.5 daa2a465fb Cut the edge over from nginx and certbot to Caddy
Test and deploy / test (push) Successful in 3m30s
Test and deploy / deploy (push) Has been cancelled
Caddy takes nginx's place in compose: ports 80/443, the fixed address
172.28.255.251 that cloudflared pins the public names to, the network
aliases, the healthcheck and the autoheal label. nginx and certbot are
removed from compose; Caddy already holds its own certificates in
./caddy/data, obtained while it ran beside nginx. `traffic` now tails
logs/caddy/payloads.log, and the dev override switches Caddy to its dev
sites instead of putting nginx in DEV_MODE.

Docs and comments that described nginx's behaviour now describe Caddy's:
CLAUDE.md, DEPLOYMENT.md (topology, boot paths, TLS, rate limits, runbook
with a rollback, rough edges), the READMEs, .env.example and the comments
in the backend, Python service, Vue source and infra files. nginx/ and
certbot/ stay in the repo as the rollback until this has settled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 23:28:28 +00:00
adamfandClaude Opus 5.5 e09b90afaa Add Caddy beside nginx as the replacement edge
Test and deploy / test (push) Successful in 1m32s
Test and deploy / deploy (push) Successful in 29m5s
caddy/ reproduces nginx's routes, gates, /notes/ privacy denials, uploads
(bucket first, then disk), rate limits, real-IP and headers in one shared
route table, with certificates obtained over DNS-01 in-process instead of by
certbot. Until the cutover it serves nothing public: loopback-only ports
8880/8443, no network aliases, its own address. The image build validates
the prod and dev configs, so a broken Caddyfile stops the deploy before any
container is replaced (`make check-caddy` is the same build).

caddy/edge_test.sh checks the privacy boundary and the gates and prints
everything else for diffing nginx against Caddy before switching over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 22:45:35 +00:00
73 changed files with 1999 additions and 564 deletions
+16 -3
View File
@@ -1,6 +1,6 @@
# .deprecated
STATUS: nothing in here is live. No compose file, nginx template or script
STATUS: nothing in here is live. No compose file, Caddyfile or script
references this directory. It is kept, not deleted, in line with the repo's
"legacy is kept" convention; the full history is also in git.
@@ -34,5 +34,18 @@ effectively root on the host. To bring it back, layer
`docker-compose.autoheal.yml` the same way as above.
Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers
labelled `autoheal=true` (nginx). This copy is the old `all` variant, kept for
reference.
labelled `autoheal=true` (caddy; nginx until 2026-11-17). This copy is the old
`all` variant, kept for reference.
## nginx/ and certbot/
The public edge until 2026-11-17, when Caddy (`caddy/`) replaced both:
`nginx/` is the image (three templates chosen at start by `entrypoint.sh`,
the shared route table, the payload log and security-header includes), and
`certbot/entrypoint.sh` obtained and renewed the certificate that nginx
reloaded through a sentinel file. Their compose services were removed in
`daa2a46`. The last certbot certificate is still in `./certbot/conf` on the
host, valid until 2027-01-20.
To bring them back: revert the commit that moved them here and then `daa2a46`;
DEPLOYMENT.md §7 ("Roll back to nginx") has the commands.
+3 -2
View File
@@ -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=[email protected]
# --- 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
+27 -22
View File
@@ -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,9 +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 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 (.deprecated/, DEPLOYMENT.md §7).
DOMAIN=
EMAIL=
@@ -198,10 +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 certbot's 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. Blank falls back to HTTP-01 on port 80.
# 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) ------------------------------------------
@@ -282,16 +281,22 @@ 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=
# --- Partner Radar (radar.DOMAIN) ----------------------------------------------
# A separate compose project on this host (adamf/cto, `make stpvm`), whose web
# container joins app-network as `radar-web`. Only set this to point
# radar.DOMAIN somewhere else.
# RADAR_UPSTREAM=radar-web:80
# TfL Unified API key (500 req/min); used by the Python hotel finder
TFL_APP_KEY=
@@ -314,7 +319,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
+1 -1
View File
@@ -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.
+4
View File
@@ -1,8 +1,12 @@
icecast2/fallback_music/*
.claude/
!icecast2/fallback_music/.gitkeep
# The retired certbot's data (code in .deprecated/certbot/), still on the
# host as the rollback certificate
certbot/conf
certbot/www
# Caddy's certificates, keys and ACME account (docker-compose.yml)
caddy/data/
backend/token/
jobs-data/
usaco-data/
+9 -9
View File
@@ -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 <zone> <events> <window>`) 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. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7.
## 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 <key>; auth_request /internal/auth/validate;`, see `nginx/nginx_routes.conf.template`) asks `GET /auth/validate/<key>`, 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 <key>` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) asks `GET /auth/validate/<key>`, 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 <key>`. `/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.
+238 -215
View File
@@ -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,87 @@ 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 |
| Partner Radar (adamf/cto, its own compose project) | `radar-web` (alias of that project's `web`, on app-network) | 80 | `radar.<DOMAIN>`, the whole host (its own login, no gate; zones `radar` and `radar_login`). Started from the cto checkout with `make stpvm`; 503 "offline" when that stack 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.<DOMAIN>`.
- **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.<DOMAIN>`, and apex → `www`. The
SPA, the cookies and the CORS rules all assume `www.<DOMAIN>`.
- **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/<f>` 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 +143,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 +156,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 +192,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 +222,79 @@ 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, `<DOMAIN>` and `www.<DOMAIN>`, 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`
`<DOMAIN>` 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, now in `.deprecated/`. The last certbot
certificate is still in `./certbot/conf` on the host as the rollback (§7); it
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.<DOMAIN>`, 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 `<DOMAIN>`
The origin is the public name, not `caddy`, because Caddy carries `<DOMAIN>`
and `www.<DOMAIN>` 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 `<DOMAIN>:2222`, so it maps `<DOMAIN>` to the host gateway
instead, where Gitea publishes that port.
@@ -297,27 +309,30 @@ 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.<DOMAIN>` → `https://www.<DOMAIN>`: the site.
- `<DOMAIN>` → `https://<DOMAIN>`: nginx redirects it to www, and it serves Gitea's registry
- `<DOMAIN>` → `https://<DOMAIN>`: Caddy redirects it to www, and it serves Gitea's registry
at `/v2/`.
- `radar.<DOMAIN>` → `https://radar.<DOMAIN>`: the Partner Radar demo
(Caddy's `radar.{$DOMAIN}` site, `sites/prod.caddy`).
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 `<DOMAIN>/adamf/...` and the
@@ -328,7 +343,7 @@ Setup, once:
127.0.0.1 <DOMAIN>
```
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 +379,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 +412,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 +430,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 +438,50 @@ with `docker compose config`.
Edit `.env` on the host, and recreate only the services that read the variable:
`docker compose up -d <service>`. 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 <zone> <events> <window>`. Each zone is a
**sliding window** keyed on `{client_ip}`: at most `<events>` requests per
`<window>` 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. |
| `radar` | 30 / 1s | all of `radar.<DOMAIN>` | The Partner Radar demo: an abuse ceiling like `api`, in its own zone because it is a different app. |
| `radar_login` | 5 / 1m | `radar.<DOMAIN>/api/auth/login` | Brute-force defence on the demo's login, on top of `radar` and the app's own login throttling. |
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,69 +503,78 @@ 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):
**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:
```
docker compose exec certbot certbot renew --webroot -w /var/www/certbot
docker compose restart nginx
export "$(grep '^DOMAIN=' .env)"
caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
```
Add `--dry-run` to test without burning rate limit.
**Roll back to nginx** (possible while the certbot certificate in
`./certbot/conf` is valid, until 2027-01-20). The old edge is in
`.deprecated/nginx/` and `.deprecated/certbot/`. Revert the commit that moved
it there and then the cutover (`daa2a46`), which restores both directories
and nginx's compose services. Push, or apply it by hand on the host under the
lock so a deploy cannot interleave:
```
git revert --no-edit <the .deprecated move> daa2a46
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.<DOMAIN>/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**:
@@ -564,8 +599,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:
@@ -610,7 +645,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/<path>` 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
@@ -651,26 +686,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
```
---
@@ -679,25 +715,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. **The old edge's host directories are still on stpvm** as the rollback
from the 2026-11-17 cutover: `./certbot/` (the last certbot certificate)
and `./logs/nginx/`, plus the `logs/nginx` stanza in
`/etc/logrotate.d/web_server`. The code is in `.deprecated/`. Once the
rollback is no longer wanted, delete the two directories and the 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.
+15 -3
View File
@@ -13,6 +13,7 @@
# check-python python3 with the venv module
# check-vue Node + `npm install` done in vue/
# check-compose / dev Docker with the compose plugin
# check-caddy Docker
# Nothing here installs a toolchain; a missing one fails that target only.
#
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
@@ -35,7 +36,7 @@ VENV := .venv
# changes and skip the install otherwise.
VENV_STAMP := $(VENV)/.installed
.PHONY: help check check-backend check-python check-vue check-compose generate dev
.PHONY: help check check-backend check-python check-vue check-compose check-caddy generate dev
help:
@echo "Targets:"
@@ -44,11 +45,12 @@ help:
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
@echo " make check-vue vite build of vue/ into a throwaway directory"
@echo " make check-compose validate docker-compose.yml, alone and with the dev override"
@echo " make check-caddy build the Caddy image, which validates caddy/ for prod and dev"
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
@echo " make dev build and run the dev stack (http://localhost)"
# Run with `make -k check` to keep going past the first failing area.
check: check-backend check-python check-vue check-compose
check: check-backend check-python check-vue check-compose check-caddy
check-backend:
cd backend && go vet ./... && go test ./...
@@ -111,11 +113,21 @@ check-compose:
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
# The edge config is validated by the image build itself (the last RUN in
# caddy/Dockerfile runs `caddy validate` for the production and dev sites), so
# this is that build and nothing more. The deploy's `docker compose up
# --build` runs the same build, and a failure there stops before any
# container is replaced. The first build compiles Caddy with its plugins and
# takes a few minutes; later ones reuse that layer unless the Dockerfile
# changes.
check-caddy:
docker build -q -t web_server-caddy:check caddy/
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
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
+19 -22
View File
@@ -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/<DOMAIN>/`, 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 |
+1 -1
View File
@@ -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.
+7 -7
View File
@@ -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
+2 -2
View File
@@ -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.
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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!
+9 -8
View File
@@ -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
+2 -2
View File
@@ -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"
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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)
+5 -5
View File
@@ -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/<key>
// Caddy gates a service on one key by asking GET /auth/validate/<key>
// (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
// <key>` (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
+1 -1
View File
@@ -19,7 +19,7 @@ func TestValidPermission(t *testing.T) {
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
// Keys must be URL-path safe: Caddy splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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.")
}
+10 -10
View File
@@ -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/<name> 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/<name> only ever serves a top-level name anyway.
// hand, and Caddy's /uploads/<name> 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
+6
View File
@@ -0,0 +1,6 @@
**/.git
**/.DS_Store
# The certificate store (private keys) is bind-mounted at runtime, never sent
# to the build.
data
edge_test.sh
+404
View File
@@ -0,0 +1,404 @@
# =============================================================================
# Caddyfile — the public edge: TLS, the SPA, and the reverse proxy in front of
# every other service. Replaced nginx and certbot (now .deprecated/) on
# 2026-11-17.
#
# FILES (all baked into the image by caddy/Dockerfile)
# Caddyfile this file: global options, the snippets every site
# uses, the healthcheck site, and the import that picks
# the dev or production sites.
# routes.caddy the proxy route table, shared by dev and production.
# ADD A NEW PROXIED ROUTE THERE.
# sites/prod.caddy production: http -> https://www, the apex (registry
# and redirect), the www site.
# sites/dev.caddy dev: localhost on http and https, `/` -> Vite.
#
# WHICH SITES ARE LOADED
# CADDY_SITE picks the file (`prod` unless set; docker-compose.dev.yml sets
# `dev`). It is a parse-time {$VAR}, substituted before the Caddyfile is
# read, so it can name the import itself.
#
# TWO KINDS OF VARIABLE
# {$NAME} / {$NAME:default} read from the environment ONCE, when the config
# is parsed. Used for upstream names and the
# domain. They end up in the JSON config Caddy
# autosaves to /config, so never a secret.
# {env.NAME} read per use at runtime, never written into the
# config. Used for the two secrets: the
# Cloudflare DNS token and the receipt token.
# Every variable must be in the caddy service's explicit `environment:`
# list in docker-compose.yml, or it reaches Caddy empty. Note an EMPTY
# variable is not "unset": {$X:default} keeps the empty value. So defaults
# live in that compose list (${X:-default}), which treats both alike, as
# nginx's entrypoint's ${X:-default} did.
#
# WHAT NO LONGER NEEDS DOING (vs nginx)
# - Upstreams are resolved when Caddy dials them, not at startup, so it
# boots with any container missing and 502s until it appears. No
# `resolver` / `set $upstream_*` trick.
# - Certificates are obtained and renewed in-process (sites/prod.caddy), and
# Caddy serves while it does, so there is no bootstrap config, no certbot,
# no reload sentinel.
# - `header` is additive: a route that sets its own headers keeps the site's
# too. No security_headers.conf re-included everywhere.
# - Websocket upgrades, streaming responses and request-body streaming are
# the reverse proxy's defaults.
# =============================================================================
{
# No `email`: the ACME account works without one, Let's Encrypt stopped
# sending expiry notices in 2025, and an `email {$EMAIL}` line with EMAIL
# unset is a parse error that keeps the whole edge from starting.
# rate_limit is a plugin, so it has no place in Caddy's built-in directive
# order. Before basic_auth means before forward_auth too: a gated route
# counts the request before asking the backend about the session, as
# nginx's limit_req (preaccess phase) ran before auth_request (access).
order rate_limit before basic_auth
# Dev's `tls internal` would otherwise try to add Caddy's local CA to the
# container's trust store, which is pointless and logs an error.
skip_install_trust
servers {
# Real client IP behind the Cloudflare tunnel. For connections from
# the cloudflared container, and only those, the client IP is taken
# from Cloudflare's CF-Connecting-IP header. {client_ip} is then the
# visitor everywhere it is used: the rate-limit keys, the access log,
# and the X-Real-IP / X-Forwarded-For sent upstream (see `proxy`).
#
# Pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the subnet. Direct
# visitors on the published 80/443 can arrive from the bridge gateway,
# 172.28.0.1, so trusting the subnet would let anyone choose their own
# IP, and so their own rate-limit bucket, by sending the header.
trusted_proxies static 172.28.255.250
client_ip_headers CF-Connecting-IP
# No HTTP/3: 443/udp is not published and cloudflared does not use it,
# so advertising it (Alt-Svc) would only send browsers on a detour.
protocols h1 h2
}
# ---- Access logs ---------------------------------------------------------
# Every site imports `logging`, which names its access logger `payloads`.
# The two loggers below take that stream; the default logger is told to
# leave it alone, or each request would also be printed unfiltered,
# request body included.
log default {
exclude http.log.access.payloads
}
# 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; 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).
#
# Redaction: any body mentioning a password, token or secret is replaced
# whole, not field by field, because there is no JSON parser here. That
# catches /auth/login, the GraphQL login and change-password mutations and
# the refresh-token call in one rule. Over-matching (a query that merely
# selects a field named *token*) costs a hidden body, never a leak.
# Cookie and Authorization headers are logged as REDACTED by Caddy itself
# (the `log_credentials` server option is off).
log payloads_file {
include http.log.access.payloads
output file /var/log/caddy/payloads.log {
roll_size 50MiB
roll_keep 5
mode 0644
}
format filter {
wrap json
fields {
req_body regexp "(?is)^.*(password|token|secret).*$" "[redacted]"
}
}
}
# The container's stdout, which `docker compose logs caddy` and Dozzle
# show: the same requests cut down to one short line each, without the
# body or headers, like nginx's `compact` format.
log payloads_stdout {
include http.log.access.payloads
output stdout
format filter {
wrap console
fields {
req_body delete
request>headers delete
request>tls delete
resp_headers delete
}
}
}
}
# ---- Snippets ----------------------------------------------------------------
# Defined here, before the site files are imported, so every file can use
# them. `import <snippet> <args...>` fills {args[N]}.
# Inside every reverse_proxy. Caddy already passes Host through and sets
# X-Forwarded-Proto/Host. X-Forwarded-For is overwritten rather than left to
# Caddy's default, which APPENDS the trusted peer: behind the tunnel that is
# "<visitor>, 172.28.255.250", and Gitea (REVERSE_PROXY_LIMIT = 1, so the
# rightmost entry) would log cloudflared for every visitor. With exactly one
# entry, the visitor, every upstream sees what nginx gave it: gin's ClientIP()
# (backend/main.go, trusts 172.28/16), Gitea, and python/app/main.py's
# _internal_only guard, which refuses any request carrying either header.
(proxy) {
header_up X-Real-IP {client_ip}
header_up X-Forwarded-For {client_ip}
}
# import limit <zone> <events> <window>
#
# A sliding window: at most <events> per <window> per client IP, then 429
# (turned into 503 by `errors`). Unlike nginx's leaky bucket there is no
# separate burst, so each zone's <events> is nginx's rate and <window> its
# unit, which keeps the sustained rates exact; the instant allowance comes out
# close to nginx's burst + 1. DEPLOYMENT.md §6 has the table and the reasoning
# behind each zone.
#
# State is shared per ZONE NAME across every route that names it (the plugin
# keeps one pool keyed by name), which is how /api, /py, /jobs, /usaco and
# /tracker share one `api` bucket, as in nginx. So a zone name must always be
# given the same <events> and <window>; a route that wants different numbers
# needs its own zone name (see `receipt`).
(limit) {
rate_limit {
zone {args[0]} {
key {client_ip}
events {args[1]}
window {args[2]}
}
}
}
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/,
# Gitea's history views, /uploads/private/) ----
# forward_auth sends a GET carrying the original request's headers, cookie
# included, to the backend's /auth/validate-admin before the request goes
# anywhere. 2xx lets it through; 401/403 become a redirect to the SPA login.
# This puts the Go backend's session in front of services that have no idea
# it exists. The body is never sent (the method is rewritten to GET), so a
# 2 GB garage-webui upload does not go to the backend twice.
#
# {http.request.orig_uri}, not {uri}: a route's `uri strip_prefix` runs
# BEFORE forward_auth in Caddy's directive order, so {uri} would have lost its
# prefix by the time this redirect is built. The `*` matters too: given only a
# target and a status, `redir` takes a target starting with / as a path
# MATCHER, and the redirect would never fire.
(admin_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate-admin
@denied status 401 403
handle_response @denied {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
}
}
# ---- Permission gate (/receipt/) ----
# import permission_gate <key>
#
# The same mechanism, but asking GET /auth/validate/<key> whether the session
# holds one named permission (backend/services/permissions.go; admins hold
# them all), so a non-admin account granted it in the admin panel gets in.
# 401 (not signed in) goes to the login page; 403 (signed in, not granted)
# goes to a page that says so, since sending a signed-in user to log in again
# only shows them "Already signed in".
#
# On success the backend returns the username in X-Auth-User, copied onto the
# proxied request as X-Remote-User. copy_headers deletes any X-Remote-User the
# client sent before it sets the real one, so the upstream can trust it.
(permission_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate/{args[0]}
copy_headers X-Auth-User>X-Remote-User
@unauthenticated status 401
handle_response @unauthenticated {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
@forbidden status 403
handle_response @forbidden {
redir * /no-access?path={http.request.orig_uri} 302
}
}
}
# Production only (sites/prod.caddy); HSTS on localhost would poison the
# browser for every other localhost project on the machine.
#
# No site-wide CSP here. Gitea (proxied at /gitea/) relies on inline <script>
# blocks its own templates generate, so a shared script-src would need
# 'unsafe-inline', which voids almost all of CSP's value. If a real CSP
# matters again, give the SPA document its own, separate from Gitea.
(security_headers) {
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Strict-Transport-Security "max-age=63072000; includeSubDomains"
}
}
# User-uploaded files are attacker-supplied bytes on our own origin. nosniff
# stops content-type guessing (so backend/services/uploads.go's stored type is
# what the browser goes by), Content-Disposition inline keeps them from being
# treated as downloads, and the locked-down CSP means even an uploaded .html
# can run no script and load no resource. `>` defers each one until the
# response is written, so it also wins over anything Garage sends. (-Server
# and -Via repeat `common`'s, for the error route, which does not run it.)
(upload_headers) {
header {
>X-Content-Type-Options "nosniff"
>Content-Disposition "inline"
>Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'"
-Server
-Via
}
}
# The disk half of /uploads/ (see routes.caddy): hand the request to the
# uploads disk site at the bottom of this file. Used both when Garage answers
# 404/5xx (handle_response) and when it cannot be reached at all (`errors`),
# so it works from the ORIGINAL path, whatever the route had stripped by then.
#
# Why proxy to a second site rather than call file_server here: in an error
# route file_server answers with the ERROR's status, so a file served while
# Garage is down would arrive as a 502 (with the file as its body), and
# forcing 200 instead would also turn its 206 and 304 answers into 200s. A
# proxied response keeps whatever status the disk site gave it.
#
# The headers are imported again because error routes do not inherit the
# deferred ones of the route that failed.
(uploads_disk) {
import upload_headers
rewrite * {http.request.orig_uri.path}
reverse_proxy 127.0.0.1:2080
}
# Error routes, for errors Caddy raises itself (never for an upstream's own
# error response, which is passed through untouched). Any error none of these
# handles is answered with its own status and an empty body.
(errors) {
# rate_limit's 429. Answered as 503, the status nginx's limit_req used,
# because vue/src/views/hotels/hotelsStream.js tells the two apart: 503 is
# "too many searches from your address", while a 429 is the Python
# service's own "someone else is searching right now".
handle_errors 429 {
respond "Too many requests from your address. Wait a moment and retry." 503
}
# An upstream that could not be reached or timed out. Three routes turn that
# into something better than a bare 502, each keyed on a variable its
# route sets (error routes keep the request's vars, and a variable cannot
# be spoofed the way a path can be dressed up):
# uploads_fallback Garage is down: serve the file from disk instead.
# receipt_upstream set only once the permission gate has passed, so a
# backend outage is not reported as the printer's.
# radar_upstream the Partner Radar stack (radar.DOMAIN) is down.
handle_errors 502 504 {
@uploads_fallback vars uploads_fallback yes
handle @uploads_fallback {
import uploads_disk
}
@receipt_offline vars receipt_upstream yes
handle @receipt_offline {
respond "The receipt printer machine is offline." 503
}
@radar_offline vars radar_upstream yes
handle @radar_offline {
respond "Partner Radar is offline." 503
}
}
}
# The access log, and the request body on it. {http.request.body} buffers the
# body in memory to log it, so it is only taken when the client declared a
# length under 100 KB and the route is not an upload path: big and chunked
# bodies are logged without one. nginx did the equivalent: bodies over its
# 64k buffer went to a temp file and logged empty.
(logging) {
log payloads
@small_body {
# Up to five digits, spelt out because a {1,5} would read as a
# placeholder.
header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
}
# `<` (early: taken before the request is proxied) must be explicit.
# Without it 2.11 takes the body early as documented, but then takes it a
# second time after the proxy has read it, logging an empty string.
log_append @small_body <req_body {http.request.body}
}
# Compression, for the types nginx's gzip_types listed. An explicit list so
# that streamed responses (application/x-ndjson from /py/hotels/*, Dozzle's
# text/event-stream, icecast's audio) are never held back to fill a
# compression buffer.
(encode) {
encode zstd gzip {
minimum_length 256
match {
header Content-Type text/html*
header Content-Type text/plain*
header Content-Type text/css*
header Content-Type text/javascript*
header Content-Type application/javascript*
header Content-Type application/json*
header Content-Type application/xml*
header Content-Type image/svg+xml*
}
}
}
(common) {
import logging
import errors
import encode
# Caddy's own `Server: Caddy` and an upstream's (icecast sends one), and
# the `Via: 1.1 Caddy` its reverse proxy adds: nginx sent neither.
header {
-Server
-Via
}
}
# ---- Container healthcheck ---------------------------------------------------
# The target of the healthcheck in docker-compose.yml, which the `autoheal`
# container acts on. Answered by Caddy itself, so it measures whether the
# server is serving and nothing upstream. Plain HTTP on :80, addressed by IP
# so it matches no real site; not logged, or it would put a line in the
# payload log every 30 s.
http://127.0.0.1 {
respond /caddy-health 204
respond 404
}
# ---- Uploads disk site -------------------------------------------------------
# The shared `uploads` volume (mounted at /srv/uploads), served to this
# container only (bound to the loopback; nothing publishes 2080). Reached by
# `uploads_disk` when Garage has no copy of a file; see that snippet for why
# it is a site of its own. Unlogged: the request was logged as it arrived.
#
# private/ is refused here as well as gated upstream. A request is routed by
# its cleaned, lower-cased path, so anything that could reach private/ goes to
# the gated /uploads/private/ route long before this; the refusal is the
# second lock, should that route ever be reordered.
http://:2080 {
bind 127.0.0.1
@private path /uploads/private /uploads/private/*
handle @private {
respond 404
}
handle /uploads/* {
root * /srv
file_server
}
respond 404
}
import sites/{$CADDY_SITE:prod}.caddy
+66
View File
@@ -0,0 +1,66 @@
# =============================================================================
# caddy image — the public edge. Caddy with two plugins, plus this
# directory's config, checked while the image is built.
#
# WHY A CUSTOM BUILD
# Stock Caddy has neither of these, and the config needs both:
# caddy-dns/cloudflare DNS-01 certificates through the Cloudflare API
# (sites/prod.caddy), since the router forwards
# nothing to obtain them over HTTP.
# mholt/caddy-ratelimit the `rate_limit` directive (the `limit` snippet
# in the Caddyfile).
# xcaddy compiles them in. The cloudflare plugin is pinned to a release;
# caddy-ratelimit has had one tagged release (v0.1.0, 2024) and is pinned
# to a commit, so Renovate leaves it alone and it is bumped by hand.
#
# BASE: caddy:2.11.9, the builder and the runtime from the same release
# (the builder's xcaddy builds the CADDY_VERSION its image sets). Both
# tags are bumped together. Official images are multi-arch.
#
# THE CONFIG IS VALIDATED AT BUILD TIME
# The last RUN parses and provisions the config with `caddy validate`, for
# the production sites and the dev ones, against placeholder values for
# every variable the config reads. A config that would not load therefore
# fails the image build, and a failed build aborts `docker compose up
# --build` BEFORE any container is replaced, so the running edge keeps
# serving. `make check-caddy` is the same build. The placeholders exist
# only for that RUN; the real values come from the container's
# environment (docker-compose.yml).
#
# NO ENTRYPOINT. The base image's CMD runs
# `caddy run --config /etc/caddy/Caddyfile --adapter caddyfile`, which is all
# that is needed: Caddy reads the environment itself, and obtains and renews
# its own certificates.
# =============================================================================
FROM caddy:2.11.9-builder AS builder
RUN xcaddy build \
--with github.com/caddy-dns/[email protected] \
--with github.com/mholt/caddy-ratelimit@5625512f24f6f59d6f64fb3aafe5eecff0b286db
FROM caddy:2.11.9
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile routes.caddy /etc/caddy/
COPY sites/ /etc/caddy/sites/
# Mount points (docker-compose.yml). Created so Caddy still starts without
# them: the log directory especially, since a log file that cannot be opened
# stops the config loading.
RUN mkdir -p /var/log/caddy /srv/www /srv/uploads
# Validation writes Caddy's data and the payload log, so it is pointed at a
# throwaway directory and the log is removed afterwards, leaving the image as
# it was.
RUN set -e; \
for site in prod dev; do \
echo "caddy validate (CADDY_SITE=$site)"; \
env XDG_DATA_HOME=/tmp/validate XDG_CONFIG_HOME=/tmp/validate \
CADDY_SITE=$site DOMAIN=example.com EMAIL=[email protected] \
BACKEND_HOST=backend BACKEND_PORT=8080 BACKEND_ENDPOINT=/api \
ICECAST_HOST=icecast2 ICECAST_PORT=8000 \
GITEA_HOST=gitea GITEA_PORT=3000 \
SILVERBULLET_HOST=silverbullet SILVERBULLET_PORT=3000 \
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_PORT=3000 \
PYTHON_HOST=python PYTHON_PORT=8000 \
RECEIPT_WEB_UPSTREAM=127.0.0.1:9 RECEIPT_WEB_TOKEN=validate \
CLOUDFLARE_DNS_API_TOKEN=validate-placeholder-token-0000000000000 \
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile; \
done; \
rm -rf /tmp/validate /var/log/caddy/*
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env bash
# =============================================================================
# edge_test.sh — what the public edge does with a fixed set of requests.
#
# WHAT IT DOES
# Sends each request below to the edge and prints one line per request
# (status and Location, or one response header). Two kinds of line:
# ok / FAIL the privacy boundary and the gates, which have a fixed right
# answer: the /notes/ denials, /py/internal/, every gated
# prefix. Any FAIL makes the exit status 1.
# show / hdr everything else (redirects, headers, carve-outs, uploads),
# whose answer depends on the upstream's data. Compare two runs
# instead (below).
#
# USAGE
# caddy/edge_test.sh <base-url> [curl options...]
# base-url the www origin, e.g. https://www.example.com
# curl options added to every request: --resolve to reach a given
# container, -k for dev's internal CA.
# Environment, all optional:
# EDGE_APEX the apex origin (production only): adds the apex cases.
# EDGE_HTTP the plain-http apex origin (production only), e.g.
# http://example.com: adds the http -> https case.
# EDGE_COOKIE an admin session's Cookie header value: adds the
# signed-in cases (each gated prefix must then NOT redirect
# to the login).
# EDGE_UPLOAD the name of a file under /uploads/ that exists.
#
# On stpvm, pin the hostname to this machine, or curl goes out over the
# internet and back (and hangs):
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
# Dev stack:
# caddy/edge_test.sh https://localhost -k
#
# 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
# /py/internal/, which never gets past the edge.
# =============================================================================
set -u
if [ $# -lt 1 ]; then
echo "usage: $0 <base-url> [curl options...]" >&2
exit 2
fi
BASE=${1%/}
shift
CURL_OPTS=("$@")
FAILED=0
# The www host, without scheme or port.
BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')
# "<status> <location>" for one request. Arguments after the URL are extra
# curl options (method, headers, --path-as-is). A redirect to the www host is
# shown as its path alone: nginx sends an absolute Location built from its
# own port, Caddy a relative one, and either way the browser lands on the
# same page.
probe() {
local url=$1 out
shift
out=$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{redirect_url}' \
"${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null) || out=ERR
printf '%s' "$out" | sed -E "s#^([0-9]+) [a-z]+://$BASE_HOST(:[0-9]+)?/#\\1 /#"
}
# The first value of one response header, or "-".
header_of() {
local name=$1 url=$2 value
shift 2
value=$(curl -sS -o /dev/null -D - --max-time 15 "${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null |
tr -d '\r' | grep -i "^$name:" | head -n 1 | cut -d: -f2- | sed 's/^ //')
printf '%s' "${value:--}"
}
# must <status> <location prefix, or -> <label> <path> [curl options]
must() {
local want_status=$1 want_loc=$2 label=$3 path=$4 got status loc ok=yes
shift 4
got=$(probe "$BASE$path" "$@")
status=${got%% *}
loc=${got#* }
[ "$status" = "$want_status" ] || ok=no
if [ "$want_loc" != "-" ] && [ "${loc#"$want_loc"}" = "$loc" ]; then
ok=no
fi
if [ $ok = yes ]; then
printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got"
else
printf 'FAIL %-12s %-58s %s (want %s %s)\n' "$label" "$path" "$got" "$want_status" "$want_loc"
FAILED=1
fi
}
# not_login <label> <path> [curl options]: anything but a redirect to the login.
not_login() {
local label=$1 path=$2 got
shift 2
got=$(probe "$BASE$path" "$@")
case $got in
ERR | "302 /admin/login"*)
printf 'FAIL %-12s %-58s %s (want: let through)\n' "$label" "$path" "$got"
FAILED=1 ;;
*) printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got" ;;
esac
}
# show <label> <url> [curl options]
show() {
local label=$1 url=$2
shift 2
printf 'show %-12s %-58s %s\n' "$label" "${url#"$BASE"}" "$(probe "$url" "$@")"
}
# hdr <url> <header...>
hdr() {
local url=$1 h
shift
for h in "$@"; do
printf 'hdr %-12s %-58s %s\n' "$h" "${url#"$BASE"}" "$(header_of "$h" "$url")"
done
}
LOGIN="/admin/login?redirect="
echo "# privacy boundary: must be 404"
for p in \
/notes/private/x /notes/Private/x /notes/a/private/x /notes/private \
/notes/templates/t /notes/.fs/private/x.md /notes/.fs/a/private/x.md \
/notes/.fs/.git/HEAD /notes/a/.obsidian/workspace.json /notes/a/.git/config \
/notes/.revisions/x.md /notes/private%2Fx /notes/%70rivate/x; do
must 404 - notes "$p"
done
must 404 - notes /notes/a/../private/x --path-as-is
must 404 - notes /notes/a//private/x --path-as-is
must 404 - py-internal /py/internal/rowing/read -X POST
must 404 - py-internal /py/internal/rowing/read
must 404 - py-internal /py/x/../internal/rowing/read --path-as-is -X POST
must 404 - py-internal /py//internal/rowing/read --path-as-is -X POST
echo "# admin gate, signed out: must redirect to the login, with the original URI"
for p in \
/sb/ /sb/index.html /jobs/ /jobs/api/graphql /tracker/ /tracker/dashboard \
/dozzle/ /garage/ /radio/admin/stats.xsl /uploads/private/x.png \
/gitea/adamf/web_server/commit/0000000 /gitea/adamf/web_server/src/commit/0000000/README.md \
/gitea/adamf/web_server/archive/main.tar.gz /gitea/adamf/web_server/compare/main...x \
/gitea/adamf/web_server/blame/commit/0000000/README.md \
"/jobs/leads?x=1"; do
must 302 "$LOGIN$p" gate "$p"
done
must 302 "${LOGIN}/uploads/x/../private/x.png" gate /uploads/x/../private/x.png --path-as-is
show gate "$BASE/SB/"
must 302 "${LOGIN}/receipt/" permission /receipt/
if [ -n "${EDGE_COOKIE:-}" ]; then
echo "# admin gate, signed in: must be let through"
for p in /sb/ /jobs/ /tracker/ /dozzle/ /garage/ /radio/admin/stats.xsl \
/gitea/adamf/web_server/commit/0000000 /receipt/; do
not_login gate "$p" -H "Cookie: $EDGE_COOKIE"
done
fi
echo "# carve-outs and public routes (status depends on the upstream)"
for p in /jobs/api/capture /jobs/job-capture.user.js /tracker/api/v1/events \
/tracker/tracker.user.js /tracker/readyz /usaco/ /notes/ /gitea/ \
/gitea/adamf/web_server/src/branch/main/README.md /radio/status.xsl \
/py/ /py/docs /api/ /api/me /; do
show public "$BASE$p"
done
echo "# bare prefixes and moved URLs"
for p in /api /radio /dozzle /garage /gitea /notes /sb /py /jobs /usaco \
/tracker /receipt /cv/jobs /cv/leads /job-capture.user.js "/gitea?x=1"; do
show redirect "$BASE$p"
done
echo "# SPA"
for p in /admin /architecture /some-canvas-page /assets/does-not-exist.js; do
show spa "$BASE$p"
done
hdr "$BASE/" Content-Type Strict-Transport-Security X-Frame-Options \
X-Content-Type-Options Referrer-Policy Content-Security-Policy Server
hdr "$BASE/api/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/gitea/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/assets/does-not-exist.js" Cache-Control
hdr "$BASE/img/stamps/mine.gif" Access-Control-Allow-Origin Cache-Control
echo "# uploads"
show uploads "$BASE/uploads/does-not-exist.png"
hdr "$BASE/uploads/does-not-exist.png" X-Content-Type-Options Content-Security-Policy
if [ -n "${EDGE_UPLOAD:-}" ]; then
show uploads "$BASE/uploads/$EDGE_UPLOAD"
show uploads "$BASE/uploads/$EDGE_UPLOAD" -H "Range: bytes=0-9"
hdr "$BASE/uploads/$EDGE_UPLOAD" Content-Type X-Content-Type-Options \
Content-Disposition Content-Security-Policy Strict-Transport-Security
fi
if [ -n "${EDGE_APEX:-}" ]; then
APEX=${EDGE_APEX%/}
echo "# apex (production)"
show apex "$APEX/x?y=1"
show apex "$APEX/v2/"
hdr "$APEX/x" Strict-Transport-Security
fi
if [ -n "${EDGE_HTTP:-}" ]; then
echo "# plain http (production)"
show http "${EDGE_HTTP%/}/x?y=1"
fi
echo "# result: $([ $FAILED = 0 ] && echo all MUST cases passed || echo SOME MUST CASES FAILED)"
exit $FAILED
+452
View File
@@ -0,0 +1,452 @@
# =============================================================================
# routes.caddy — the PROXY ROUTE TABLE shared by production and dev. Add a new
# proxied route HERE, once.
#
# WHO IMPORTS IT
# sites/prod.caddy (the www site) and sites/dev.caddy, each inside a
# `route { ... }` block, followed by that site's own `/` handler (the built
# SPA in production, the Vite dev server in dev). Everything else that
# differs between the two (TLS, security headers, static-asset caching, the
# apex) is in the site files.
#
# ORDER IS LITERAL: THE FIRST MATCHING handle WINS
# Inside `route`, Caddy keeps directives in the order written, and `handle`
# blocks are mutually exclusive. So this file is read top to bottom like a
# firewall list: denials first, then the specific routes, each carve-out
# ahead of the gated prefix it is carved out of, then the catch-alls.
# (nginx's longest-prefix / regex-in-file-order / ^~ rules are gone.)
#
# HOW PATHS ARE MATCHED
# `path` matchers are case-insensitive and see the decoded, cleaned path
# (`..` resolved, `//` merged), so /SB/, /notes/a/../private/x or
# /uploads/%70rivate/x cannot slip past a rule. `path_regexp` sees the
# decoded, cleaned path too but is case-sensitive, hence `(?i)` where case
# matters. caddy/edge_test.sh checks these against the live edge.
#
# PATTERNS THAT REPEAT BELOW
# - `uri strip_prefix /x`: the public URL carries a prefix (/api, /radio,
# /gitea, /py, /tracker, /receipt) but the upstream serves from /. Apps
# told their own base path (SilverBullet, the job tracker, usaco, Dozzle,
# garage-webui) keep it.
# - `import proxy` in every reverse_proxy: the forwarding headers (see the
# snippet in Caddyfile).
# - `import limit <zone> ...`: see the snippet; DEPLOYMENT.md §6 for the
# numbers.
# - `import admin_gate` / `import permission_gate <key>`: the session check
# against the backend. Some of these services have no auth of their own,
# so a gated route that loses its import is open to the internet.
# - Upstream read timeouts are not set anywhere: Caddy has none by default,
# so a long hotel search, an email sync or a log tail is never cut off by
# the proxy. (Cloudflare still gives up on an origin that sends nothing
# for 100 s; see DEPLOYMENT.md.)
#
# Upstream names come from the environment ({$BACKEND_HOST} etc.; see the
# caddy service in docker-compose.yml). The job tracker, activity tracker,
# usaco, Dozzle and Garage containers have fixed names there, so they are
# written literally.
# =============================================================================
# Request bodies: 50 MB everywhere except garage-webui, which takes video
# uploads and sets its own 2 GB below. (An outer limit cannot be raised by an
# inner one, so the exception has to be carved out here.) The backend caps
# uploads at 10 MB itself; this is the ceiling for everything else.
@body_default not path /garage/*
request_body @body_default {
max_size 50MB
}
# ---- Denials -----------------------------------------------------------------
# /py/internal/: routes the Go backend calls directly over app-network (the
# rowing photo reader, which spends a paid Claude call and has no auth of its
# own). Never proxied. The Python side also refuses anything carrying the
# X-Real-IP / X-Forwarded-For headers `proxy` sets, as a second layer.
handle /py/internal/* {
respond 404
}
# PUBLIC notes viewer privacy boundary. /notes/ is a second, read-only
# SilverBullet over the vault /sb/ edits, and SB_SPACE_IGNORE only hides
# paths from its file LIST. Everything else serves them (all verified against
# 2.11.0 with curl):
# /notes/.fs/private/x.md raw file, straight off disk
# /notes/private/x the page URL: the server pre-renders the
# note's content into the HTML shell
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
# version of every private note ever
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a private/
# folder at ANY depth, so the block must too.
#
# 1. private/ or templates/ as any path segment, page URL or /.fs/. (?i) so
# Private/ is caught; (/|$) so the folder itself matches.
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The first
# segment is exempt because that is where SilverBullet's own endpoints
# live (/.fs, /.config, /.client, /.events ...). Nothing the client
# legitimately loads has a dot-segment deeper than that.
# 3. Revisions are read from the vault's own .git, i.e. the full history of
# every file INCLUDING private/ and anything ever deleted.
# SB_REVISIONS=disabled already turns this off upstream; this is the
# second lock in case that env var is ever dropped.
# Keep the folder list in step with SB_SPACE_IGNORE on silverbullet-public.
# 404 rather than 403 so the response does not confirm a private path exists.
@notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$)
handle @notes_private {
respond 404
}
@notes_dot path_regexp ^/notes/.+/\.
handle @notes_dot {
respond 404
}
handle /notes/.revisions* {
respond 404
}
# ---- Bare prefixes and moved URLs ----------------------------------------------
# So a user typing /gitea without the slash lands correctly. Exact paths: unlike
# nginx's prefix locations, /gitea-something is not caught and is left to the
# SPA (where an admin-created canvas page with that slug now works).
redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301
redir /radio /radio/ 301
redir /dozzle /dozzle/ 301
redir /garage /garage/ 301
redir /gitea /gitea/ 301
redir /notes /notes/ 301
redir /sb /sb/ 301
redir /py /py/ 301
redir /jobs /jobs/ 301
redir /usaco /usaco/ 301
redir /tracker /tracker/ 301
redir /receipt /receipt/ 301
# Where the job tracker used to be. The SPA routes were client-side, so these
# only catch bookmarks and typed URLs. The userscript's old @updateURL lands
# on the third, which is how installed copies find version 2.0.0 and its new
# API base.
redir /cv/jobs /jobs/ 301
redir /cv/leads /jobs/leads 301
redir /job-capture.user.js /jobs/job-capture.user.js 301
# ---- Backend API ---------------------------------------------------------------
# Live chat / activity feed websocket. Deliberately NOT rate limited: a
# websocket is one long-lived request, and a limit here would drop reconnect
# storms, not abuse.
handle {$BACKEND_ENDPOINT}/ws* {
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# Brute-force defence on password auth, on top of the backend's own 5/min.
handle {$BACKEND_ENDPOINT}/auth/login* {
import limit login 5 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/uploads* {
import limit upload 30 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# Tighter than the REST catch-all, because one GraphQL query can be
# arbitrarily expensive to resolve.
handle {$BACKEND_ENDPOINT}/graphql* {
import limit graphql 10 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/* {
import limit api 30 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# ---- Admin-gated services ------------------------------------------------------
# Dozzle: live view of every container's logs, including the `traffic`
# container's request-body log. It reads the Docker socket, so it is
# effectively root on the host: admin only. DOZZLE_BASE=/dozzle makes it serve
# under the prefix itself. Its log tails are server-sent events, which Caddy
# streams without buffering.
handle /dozzle/* {
import admin_gate
reverse_proxy dozzle:8080 {
import proxy
}
}
# garage-webui: buckets, keys and a file browser for the Garage object store.
# It holds Garage's admin token, so admin only, and its own login is left
# unset (one login, not two). BASE_PATH=/garage makes it serve under the
# prefix. 2 GB so videos can be uploaded through it; the body streams through
# rather than landing on disk first.
handle /garage/* {
import admin_gate
request_body {
max_size 2GB
}
reverse_proxy garage-webui:3909 {
import proxy
}
}
# The icecast ADMIN UI is a full station-control surface (kick sources, change
# metadata) protected only by the icecast admin password. Ahead of /radio/*,
# so listener traffic (the mount, status.xsl) is untouched.
handle /radio/admin/* {
import admin_gate
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
# Gitea's history views and archives. A crawler swarm (129k requests from
# 103k IPs over 2026-10-18/19, so per-IP rate limits are useless) walks every
# file at every commit, and those pages are the expensive ones: diffs, blame,
# tarballs. 89% of its requests were these shapes. People browsing the code
# use the branch views (src/branch/..., commits/branch/...), which stay
# public, so the CV's repo links still work. Gitea's own
# REQUIRE_SIGNIN_VIEW=expensive would also block src/branch, hence doing it
# here. Ahead of /gitea/*.
@gitea_history path_regexp ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/)
handle @gitea_history {
import admin_gate
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes. NO
# prefix strip: it is a PWA told its own base path via SB_URL_PREFIX=/sb, and
# builds its service-worker scope and asset URLs from it. Strip the prefix and
# the app loads a blank page with no error in the log.
handle /sb/* {
import admin_gate
reverse_proxy {$SILVERBULLET_HOST}:{$SILVERBULLET_PORT} {
import proxy
}
}
# ---- Public services -----------------------------------------------------------
handle /radio/* {
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
handle /gitea/* {
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# The public notes viewer, behind the denials at the top of this file. No
# prefix strip, for the same reason as /sb/ (SB_URL_PREFIX=/notes).
handle /notes/* {
reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} {
import proxy
}
}
# /py/hotels/search[/stream] and /py/hotels/scan/stream: public, minutes-long
# upstream calls to Travelodge/TfL with a single search slot on the Python
# side, so this zone is really concurrency protection. flush_interval -1
# passes each NDJSON progress line on as it arrives (chunked responses are
# flushed anyway; this makes it explicit). `encode` never touches
# application/x-ndjson.
@hotels path_regexp ^/py/hotels/(search|scan)
handle @hotels {
import limit hotel_search 3 1m
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
flush_interval -1
}
}
handle /py/* {
import limit api 30 1s
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
}
}
# ---- Job tracker (/jobs/) ----
# Its own container (the adamf/job-tracker repo), which serves its SPA and its
# API from the same prefix, NOT stripped: the app is built to live at /jobs/.
# Gated like /sb/ (the app checks the session itself too), with two
# exceptions ahead of it that a session cookie can never reach:
# - the capture API, called by the userscript from job sites' origins with
# the capture bearer token rather than cookies; the app's
# CaptureTokenMiddleware guards it;
# - the userscript itself: userscript managers fetch its @updateURL without
# the session, and it holds no secrets (the token is entered after
# install).
handle /jobs/api/capture* {
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/job-capture.user.js {
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/* {
import admin_gate
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
# ---- USACO practice log (/usaco/) ----
# Its own container (the usaco repo's site/), shaped like /jobs/: SPA and API
# under one prefix that is NOT stripped, and no gate, because most of it is
# public and the app checks the session itself for the admin's edits. Gitea's
# push webhook does not come through here: it calls the container directly
# on the Docker network.
handle /usaco/* {
import limit api 30 1s
reverse_proxy usaco:8080 {
import proxy
}
}
# ---- Activity tracker (/tracker/) ----
# Its own container (the adamf/ccp repo): an ingest API for device collectors,
# which send batches of events with a per-device bearer key, plus a dashboard
# and setup page. Gated like /sb/ (the app also checks the session itself),
# with two exceptions ahead of it: the API, which collectors call with bearer
# keys and no cookies (the app guards each route, by device key, admin
# session or either), and the public userscript. Unlike /jobs/ the prefix IS
# stripped: the server serves /api/v1/... and /readyz from /. Collectors must
# use the www host: the apex 301 would turn their POSTs into GETs. Health Auto
# Export bodies can be several MB; the 50 MB default above covers them.
handle /tracker/api/v1/* {
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/tracker.user.js {
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/* {
import admin_gate
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
# ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi (not in
# this stack: that machine reaches the printer on the home LAN), reached over
# Tailscale by IP. A page for printing a note or an uploaded image, plus its
# API. Behind the permission gate on `receipt`, so an account granted it in
# the admin panel can print without being an admin; the prefix IS stripped.
# The server trusts nothing without X-Receipt-Token, which only this proxy
# adds (header_up replaces any copy the client sent), and is told who is
# printing in X-Remote-User, which the gate sets.
#
# A `route`, so the steps run in the order written: receipt_upstream is set
# only after the gate has passed, so `errors` reports "printer offline" for a
# failed dial to stppi and not for a backend outage during the auth check.
# Its own zone, not `api`: a zone name must always carry the same numbers.
# 17 MB: the server caps uploads at 16 MB, plus room for the multipart
# framing around one.
handle /receipt/* {
route {
import limit receipt 10 1s
request_body {
max_size 17MB
}
import permission_gate receipt
vars receipt_upstream yes
uri strip_prefix /receipt
reverse_proxy {$RECEIPT_WEB_UPSTREAM} {
import proxy
header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN}
# Caddy's default, spelt out: when stppi is off, fail fast and
# let `errors` answer.
transport http {
dial_timeout 3s
}
}
}
}
# ---- Uploads (/uploads/) ----
# PRIVATE attachments (admin-only): files on *private* chat messages, which
# the backend always writes to disk, at uploads/private/. Ahead of the public
# route below, and matched on the cleaned, lower-cased path, so no spelling of
# a path into private/ reaches the ungated one.
handle /uploads/private/* {
import admin_gate
import upload_headers
root * /srv
file_server
}
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the Garage
# bucket's website endpoint, which serves the bucket anonymously and picks it
# by the Host header (garage/garage.toml: s3_web). The bucket is reachable
# only over app-network, so this is the only public way in. If Garage has no
# such file (404), errors (5xx), or cannot be reached at all (a dial error,
# caught by `errors` through the uploads_fallback variable), the file is
# served from the shared `uploads` volume instead (`uploads_disk`). That
# volume holds uploads from before Garage and anything the backend wrote
# there because Garage refused it (backend/services/uploads.go). So the bucket
# is the source of truth (deleting a file in garage-webui unpublishes it
# unless a disk copy exists), while a Garage outage only costs files that are
# nowhere else. dial_timeout 2s: Garage is on the same bridge, so a slow
# connect means it is down; fall back quickly. Range requests pass through
# either way, so video seeks.
handle /uploads/* {
import upload_headers
vars uploads_fallback yes
uri strip_prefix /uploads
reverse_proxy garage:3902 {
import proxy
header_up Host uploads.web.garage
transport http {
dial_timeout 2s
}
@not_in_bucket status 404 5xx
handle_response @not_in_bucket {
import uploads_disk
}
}
}
+32
View File
@@ -0,0 +1,32 @@
# =============================================================================
# sites/dev.caddy — LOCAL DEVELOPMENT sites. Imported by the Caddyfile when
# CADDY_SITE=dev, which only docker-compose.dev.yml sets.
#
# HOW IT DIFFERS FROM sites/prod.caddy
# - `/` is proxied to the Vite dev server at vue:5173 instead of serving the
# built SPA. Its HMR websocket needs nothing extra.
# - http AND https both serve the full site, with no redirects, so
# http://localhost just works. Listing the http:// addresses is what
# stops Caddy adding its automatic http -> https redirect.
# - TLS is `tls internal`: a certificate from Caddy's own local CA, kept in
# ./caddy/data. Browsers warn until that CA is trusted, which is expected.
# - No security headers: HSTS on localhost would poison the browser for
# every other localhost project on the machine.
# - No static-asset caching: Vite serves those, and long cache lifetimes
# would defeat hot reload.
# Everything else, every proxied route, gate, denial and rate limit, is the
# same routes.caddy as production.
# =============================================================================
http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} {
tls internal
import common
route {
import ../routes.caddy
handle {
reverse_proxy vue:5173
}
}
}
+179
View File
@@ -0,0 +1,179 @@
# =============================================================================
# sites/prod.caddy — PRODUCTION sites. Imported by the Caddyfile unless
# CADDY_SITE says otherwise.
#
# FOUR SITES
# 1. http:// apex + www -> 301 to https://www.DOMAIN.
# 2. https:// apex -> Gitea's registry at /v2/, else 301 to www, so
# there is exactly one canonical origin (cookies,
# CORS and the SPA all assume www).
# 3. https:// www -> the real site.
# (4. the healthcheck site, http://127.0.0.1, is in the Caddyfile.)
#
# CERTIFICATES
# Caddy obtains one for each name over DNS-01 through the Cloudflare API
# (`prod_tls`), keeps them in /data (./caddy/data on the host), and renews
# each when a third of its lifetime is left, in-process, with no reload.
# DNS-01 because the router forwards nothing: behind the tunnel no ACME
# server can reach :80 or :443. The token needs Zone -> Zone -> Read and
# Zone -> DNS -> Edit on this zone; see .env.example. Until the first
# certificate arrives (about a minute on a fresh ./caddy/data) the TLS
# handshake fails, so the tunnel, which verifies it, serves 502s.
#
# resolvers: on app-network, DOMAIN is a network alias for this very
# container, so Docker's DNS would answer the plugin's zone lookup itself
# and the order fails with "expected 1 zone, got 0". Asking Cloudflare's
# public resolvers sees the real zone.
# =============================================================================
(prod_tls) {
tls {
dns cloudflare {env.CLOUDFLARE_DNS_API_TOKEN}
resolvers 1.1.1.1 1.0.0.1
}
}
# Spelt out rather than left to Caddy's automatic redirect, which goes to the
# same host: http://apex would then take two hops (https://apex, then www).
http://{$DOMAIN}, http://www.{$DOMAIN} {
import logging
header -Server
redir https://www.{$DOMAIN}{uri} 301
}
{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
# Gitea's container registry, which publishes images such as
# DOMAIN/adamf/job-tracker. Docker always talks to /v2/ at the root of
# the host, whatever Gitea's ROOT_URL says, and Gitea advertises its
# token endpoint at https://DOMAIN/v2/token: on the apex, not under
# /gitea/ and not on www. So the apex serves /v2/ itself rather than
# redirecting it; a redirect on a blob upload is not something every
# Docker client follows. No request_body limit (routes.caddy's 50 MB
# is not imported here): image layers are far larger, and Caddy
# streams them to Gitea as they arrive.
handle /v2/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
redir https://www.{$DOMAIN}{uri} 301
}
}
www.{$DOMAIN} {
import prod_tls
import common
import security_headers
# ---- Static asset caching ----
# Each matcher also requires the file to exist (`file`), so only a real
# file is marked cacheable: a 404 for a hash the browser asks for before
# the new build lands must never be cached for a year as `immutable`.
# (nginx's add_header without `always` skipped error responses the same
# way.)
# Vite hashed assets: a new build has new names, so these never change.
@hashed {
path /assets/*
file {
root /srv/www
}
}
header @hashed Cache-Control "public, max-age=31536000, immutable"
@fonts {
path /fonts/*
file {
root /srv/www
}
}
header @fonts Cache-Control "public, max-age=2592000"
@week {
path /img/* /sound/*
file {
root /srv/www
}
}
header @week Cache-Control "public, max-age=604800"
# This GIF is a "web stamp" other people's sites hot-link, so it needs a
# CORS header. It is a public, deliberately hot-linkable image and nothing
# here is credentialed, so `*` is safe.
header /img/stamps/mine.gif Access-Control-Allow-Origin "*"
route {
import ../routes.caddy
# Static directories: a missing file is a 404, never the SPA's
# index.html. A stale page asking for an old asset hash then gets an
# honest error rather than HTML served as JavaScript.
@static path /assets/* /fonts/* /img/* /sound/*
handle @static {
root * /srv/www
file_server
}
# The built SPA (the vue_dist volume). Serve the file if it exists,
# otherwise hand index.html to the browser so Vue Router can resolve
# the path client-side: that is what makes deep links like /admin or
# a canvas page's /<slug> work on refresh.
handle {
root * /srv/www
try_files {path} {path}/ /index.html
file_server
}
}
}
# ---- Partner Radar (radar.DOMAIN) ----
# The adamf/cto "Partner Radar" demo: its own docker compose project on this
# host (`make stpvm` there), whose `web` container (its own Caddy, serving the
# React app and proxying its API) joins app-network as `radar-web`. A
# subdomain, not a /radar/ path, because the app assumes it owns `/` and its
# session cookie then stays apart from www's.
#
# No admin gate: the app has its own login and accounts. No security_headers
# either: the app's Caddy sends its own, and www's CSP would block the React
# app. Two zones of its own (see DEPLOYMENT.md §6): `radar` on every request,
# and `radar_login` on top of it for the login endpoint. radar_upstream lets
# `errors` answer "offline" when the stack is down instead of a bare 502.
(radar_proxy) {
reverse_proxy {$RADAR_UPSTREAM} {
import proxy
# Caddy's default, spelt out: when the stack is down, fail fast and
# let `errors` answer.
transport http {
dial_timeout 3s
}
}
}
radar.{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
import limit radar 30 1s
request_body {
max_size 10MB
}
vars radar_upstream yes
handle /api/auth/login {
route {
import limit radar_login 5 1m
import radar_proxy
}
}
handle {
import radar_proxy
}
}
}
+16 -26
View File
@@ -12,15 +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 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`.
# =============================================================================
@@ -28,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
@@ -55,17 +55,12 @@ 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:
caddy:
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
# 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
# source bind mount below so editing python/app/ restarts uvicorn.
@@ -84,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
+126 -122
View File
@@ -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,9 +85,14 @@ 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
# the image's VOLUME does not leave an anonymous volume behind on every
# recreate. The certificates are in ./caddy/data, not here.
caddy_config:
services:
# One-shot build container, NOT a long-running service. `vite build` writes
@@ -104,50 +110,68 @@ 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.
# 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;
# both are in .deprecated/ (DEPLOYMENT.md §7 has the rollback).
#
# 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:
# 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'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.
#
# NO depends_on: Caddy resolves an upstream when it dials it, so it starts
# with any of them missing (502 until it appears), and there is no Vue
# build to wait for: the SPA is files in vue_dist, served as they appear.
caddy:
build:
context: ./nginx
context: ./caddy
dockerfile: Dockerfile
container_name: nginx
env_file: ./.env
container_name: caddy
restart: always
depends_on:
- vue
- backend
- icecast2
- gitea
- silverbullet
- silverbullet-public
- python
- jobs
- activity-tracker
- dozzle
environment:
- DOMAIN=${DOMAIN}
- BACKEND_HOST=${BACKEND_HOST}
- BACKEND_PORT=${BACKEND_PORT}
- BACKEND_ENDPOINT=${BACKEND_ENDPOINT}
- ICECAST_HOST=${ICECAST_HOST}
- ICECAST_PORT=${ICECAST_PORT}
- GITEA_HOST=${GITEA_HOST}
- GITEA_PORT=${GITEA_PORT}
- SILVERBULLET_HOST=${SILVERBULLET_HOST:-silverbullet}
- SILVERBULLET_PORT=${SILVERBULLET_PORT:-3000}
- SILVERBULLET_PUBLIC_HOST=${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}
- SILVERBULLET_PUBLIC_PORT=${SILVERBULLET_PUBLIC_PORT:-3000}
- PYTHON_HOST=${PYTHON_HOST:-python}
- PYTHON_PORT=${PYTHON_PORT:-8000}
# A dead port by default, so /receipt/ reads "offline".
- RECEIPT_WEB_UPSTREAM=${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}
- RECEIPT_WEB_TOKEN=${RECEIPT_WEB_TOKEN:-}
# Partner Radar (radar.DOMAIN): the adamf/cto stack's `web` container,
# which joins app-network under this alias (its docker-compose.stpvm.yml).
# While that stack is down the name does not resolve and radar.DOMAIN
# answers "offline".
- RADAR_UPSTREAM=${RADAR_UPSTREAM:-radar-web:80}
# Zone -> Zone -> Read and Zone -> DNS -> Edit; see .env.example.
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
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
# TLS with no extra dashboard settings (`https://caddy` would fail the
# name check). Any other container that calls the public site now
# reaches nginx directly instead of hairpinning through the internet.
# reaches Caddy directly instead of hairpinning through the internet.
aliases:
- ${DOMAIN}
- www.${DOMAIN}
- radar.${DOMAIN}
# Fixed for cloudflared's extra_hosts (see there): an alias only
# exists while nginx is running, and this address is pinned to the
# 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
@@ -155,28 +179,28 @@ services:
- 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 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 (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:/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.
- vue_dist:/srv/www:ro
# 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
# 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", "curl", "-fsS", "--max-time", "5", "-o", "/dev/null", "http://127.0.0.1/nginx-health"]
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/caddy-health"]
interval: 30s
timeout: 10s
retries: 3
@@ -184,40 +208,19 @@ services:
labels:
- autoheal=true
# 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
# 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.
#
@@ -231,16 +234,17 @@ 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"
- "www.${DOMAIN}:172.28.255.251"
- "radar.${DOMAIN}:172.28.255.251"
networks:
app-network:
ipv4_address: 172.28.255.250
@@ -278,7 +282,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.
@@ -336,12 +340,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:
@@ -360,7 +364,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).
#
@@ -378,7 +382,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.
#
@@ -413,14 +417,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
@@ -437,13 +441,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/
@@ -458,17 +462,17 @@ 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:
image: alpine/git:v2.54.0
image: alpine/git:v2.49.1
container_name: "${SILVERBULLET_GIT_HOST:-silverbullet-git}"
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.
@@ -494,7 +498,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 /.
@@ -502,7 +506,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:
@@ -534,10 +538,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
@@ -682,7 +686,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.
@@ -700,9 +704,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:
@@ -712,10 +716,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
@@ -736,7 +740,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
@@ -762,16 +766,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).
@@ -797,9 +801,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.
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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: "<bucket><root_domain>", so nginx's /uploads/ location
# Host header: "<bucket><root_domain>", 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.
+2 -2
View File
@@ -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
+5 -4
View File
@@ -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.
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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.
#
+2 -2
View File
@@ -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
+15 -12
View File
@@ -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_<thing>.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
+19 -14
View File
@@ -1,6 +1,6 @@
"""Small Python API service.
Nginx proxies https://www.<DOMAIN>/py/... to this container and strips the
Caddy proxies https://www.<DOMAIN>/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.
+6 -3
View File
@@ -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
+3 -3
View File
@@ -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"
+2 -2
View File
@@ -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 == []
+18 -1
View File
@@ -14,7 +14,8 @@
// pip_requirements python/requirements.txt, requirements-dev.txt
// dockerfile every */Dockerfile FROM line
// docker-compose every image: in docker-compose*.yml
// custom (below) the images deploy.yaml and renovate.yaml `docker run`
// custom (below) the images deploy.yaml and renovate.yaml `docker run`,
// and the Caddy plugins caddy/Dockerfile compiles in
//
// NOTHING IS AUTOMERGED, on purpose: a merge to main IS a deploy. Each
// Renovate branch is pushed to Gitea, so deploy.yaml's `test` job runs on it
@@ -50,6 +51,15 @@
matchStrings: ["(?<depName>golang|python|renovate/renovate):(?<currentValue>[0-9][\\w.-]*)"],
datasourceTemplate: "docker",
},
{
// The Caddy plugins compiled in by caddy/Dockerfile's `xcaddy build
// --with <module>@<version>`. Only versions starting with v match, so
// caddy-ratelimit, pinned to a commit, is left for a hand bump.
customType: "regex",
managerFilePatterns: ["/^caddy/Dockerfile$/"],
matchStrings: ["--with (?<depName>[\\w./-]+)@(?<currentValue>v[0-9][\\w.-]*)"],
datasourceTemplate: "go",
},
],
packageRules: [
@@ -103,6 +113,13 @@
matchPackageNames: ["python"],
groupName: "Python image",
},
// caddy/Dockerfile's builder and runtime images must be the same release
// (the builder compiles the version its image sets), so one PR moves
// both, along with the plugins.
{
matchFileNames: ["caddy/Dockerfile"],
groupName: "Caddy",
},
// gqlgen's runtime and gqlparser are versioned together. If a bump breaks
// the build, regenerate (`go run github.com/99designs/gqlgen generate`)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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.
+13 -13
View File
@@ -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
+1 -1
View File
@@ -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";
+2 -2
View File
@@ -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.
],
},
],
+2 -2
View File
@@ -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) {
+2 -2
View File
@@ -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 <a href>, 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";
+2 -2
View File
@@ -98,7 +98,7 @@ async function handleLogout() {
{{ section.label }}
</button>
<!-- Logs and incoming request bodies live in Dozzle, outside the
SPA (nginx serves it at /dozzle/ behind the admin check). -->
SPA (Caddy serves it at /dozzle/ behind the admin check). -->
<a
class="admin-nav-link no-underline"
href="/dozzle/"
@@ -108,7 +108,7 @@ async function handleLogout() {
Logs ↗
</a>
<!-- The receipt printer's page is served from stppi, which reaches
the printer on the home LAN; nginx proxies /receipt/ there over
the printer on the home LAN; Caddy proxies /receipt/ there over
Tailscale behind the `receipt` permission gate. -->
<a
class="admin-nav-link no-underline"
+3 -3
View File
@@ -6,7 +6,7 @@
* (a non-admin would only bounce off /admin's guard back to here).
*
* The `?redirect=` is set by two different gates: the SPA router guard
* (`meta.requiresAdmin`) and nginx's `auth_request` gate in front of the
* (`meta.requiresAdmin`) and Caddy's `forward_auth` gate in front of the
* proxied containers (/notes/, /sb/, /receipt/). The latter means the
* destination is frequently NOT a Vue route, so see goTo() below.
*
@@ -34,12 +34,12 @@ const errorMsg = ref("");
// Send the browser to `dest`, choosing SPA navigation vs. a real page load.
//
// nginx bounces /notes/, /sb/, /receipt/ and the like here when the session
// Caddy bounces /notes/, /sb/, /receipt/ and the like here when the session
// is missing; those paths belong to other containers, so router.push() would just
// match the catch-all 404 route and never leave the SPA. Resolving the path
// first tells us which it is: the catch-all matches everything, so landing on
// the route named "404" means no real Vue route exists and the browser needs a
// full document request for nginx to proxy it.
// full document request for Caddy to proxy it.
//
// `dest` comes from the query string, so it is only followed when it is a
// site-relative path — a leading "//" or a scheme would be an open redirect.
+1 -1
View File
@@ -6,7 +6,7 @@
* site's 404 — with, for an admin, a form to create a page right here.
*
* Static routes always win, which is why the server refuses slugs under the
* SPA's and nginx's own paths (validateSlug in backend/graph/page_helpers.go).
* SPA's and Caddy's own paths (validateSlug in backend/graph/page_helpers.go).
*
* An adminOnly page answers null to anyone else, so to them it is simply a
* 404.
+1 -1
View File
@@ -7,7 +7,7 @@
* in as literal values, read from the live page so a re-themed layout
* (CVLayout re-points the tokens) would carry through.
* - Load our fonts. Without allow-same-origin its origin is opaque ("null"),
* which makes /fonts/*.woff2 a cross-origin font load that nginx and the
* which makes /fonts/*.woff2 a cross-origin font load that Caddy and the
* Vite dev server would both refuse without CORS headers. Instead the page
* fetches the two files (28 KB) once, same-origin, and inlines them as
* data: URLs.
+1 -1
View File
@@ -58,7 +58,7 @@ export async function runStream(url, body, { signal, onEvent }) {
try {
payload = await res.json();
} catch {
/* non-JSON body (e.g. nginx error page) */
/* non-JSON body (e.g. an error page from the edge) */
}
throw new Error(describeError(res.status, payload));
}
+8 -8
View File
@@ -7,11 +7,11 @@ import vueDevTools from "vite-plugin-vue-devtools";
// Dev-server proxy targets (frontend-only `npm run dev`).
//
// In production, and in the full compose stack, nginx does this routing. The
// In production, and in the full compose stack, Caddy does this routing. The
// Vite dev server has to stand in for it, which means reaching each service
// FROM THE HOST — and the compose stack publishes almost none of them:
//
// published by docker-compose.yml: nginx (80/443), gitea (3000 + 2222 ssh),
// published by docker-compose.yml: caddy (80/443), gitea (3000 + 2222 ssh),
// the liquidsoap harbor port
// NOT published: backend (8080), python (8000),
// icecast (8000), db, silverbullet
@@ -37,9 +37,9 @@ import vueDevTools from "vite-plugin-vue-devtools";
// VITE_PROXY_RADIO Icecast default http://localhost:8000
//
// To borrow a running compose stack instead of running services on the host,
// point API / GITEA / RADIO at its nginx (e.g. VITE_PROXY_API=http://localhost):
// those three are forwarded with their path intact, which is what nginx
// expects. VITE_PROXY_PY cannot be pointed at nginx — see the rewrite below.
// point API / GITEA / RADIO at its Caddy (e.g. VITE_PROXY_API=http://localhost):
// those three are forwarded with their path intact, which is what Caddy
// expects. VITE_PROXY_PY cannot be pointed at Caddy — see the rewrite below.
const DEFAULT_PROXY = {
VITE_PROXY_API: "http://localhost:8080",
VITE_PROXY_GITEA: "http://localhost:3000",
@@ -76,9 +76,9 @@ export default defineConfig(({ mode }) => {
"/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/, ""),