Cut the edge over from nginx and certbot to Caddy
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]>
This commit is contained in:
@@ -119,12 +119,13 @@ LIQUIDSOAP_HARBOR_PORT=8001
|
|||||||
|
|
||||||
# --- TLS / identity ----------------------------------------------------------
|
# --- TLS / identity ----------------------------------------------------------
|
||||||
# DOMAIN is also the auth cookie's domain, so it must be the host the browser
|
# 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
|
DOMAIN=localhost
|
||||||
EMAIL=[email protected]
|
EMAIL=[email protected]
|
||||||
|
|
||||||
# --- Cloudflare Tunnel -------------------------------------------------------
|
# --- 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_TUNNEL_TOKEN=dev-dummy-tunnel-token
|
||||||
CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token
|
CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token
|
||||||
|
|
||||||
|
|||||||
+21
-26
@@ -7,8 +7,7 @@
|
|||||||
# it parses the file, before any container exists. This is how container
|
# it parses the file, before any container exists. This is how container
|
||||||
# names and published ports are built.
|
# names and published ports are built.
|
||||||
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
||||||
# variables inside that container. nginx, backend, db, icecast2,
|
# variables inside that container. backend, db and icecast2 do this.
|
||||||
# certbot and gitea all do this.
|
|
||||||
# The `python` and `jobs` services deliberately do neither wholesale — each
|
# The `python` and `jobs` services deliberately do neither wholesale — each
|
||||||
# uses an explicit `environment:` allow-list, so neither sees the site's
|
# uses an explicit `environment:` allow-list, so neither sees the site's
|
||||||
# database password, the JWT secret, or any key it does not use.
|
# database password, the JWT secret, or any key it does not use.
|
||||||
@@ -54,7 +53,7 @@ POSTGRES_TRACKER_USER=tracker
|
|||||||
POSTGRES_TRACKER_PASSWORD=
|
POSTGRES_TRACKER_PASSWORD=
|
||||||
|
|
||||||
# --- Gitea -------------------------------------------------------------------
|
# --- 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
|
# 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
|
# committed app.ini.template can keep those fields blank. Generate each as a
|
||||||
# long random hex string.
|
# long random hex string.
|
||||||
@@ -125,14 +124,10 @@ ADZUNA_APP_ID=
|
|||||||
ADZUNA_APP_KEY=
|
ADZUNA_APP_KEY=
|
||||||
REED_API_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) ---------------------------------------------------
|
# --- SilverBullet (notes) ---------------------------------------------------
|
||||||
# Two instances over the same vault: the admin-only editor at /sb/, and the
|
# 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
|
# 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.
|
# blank.
|
||||||
SILVERBULLET_HOST=silverbullet
|
SILVERBULLET_HOST=silverbullet
|
||||||
SILVERBULLET_PORT=3000
|
SILVERBULLET_PORT=3000
|
||||||
@@ -142,8 +137,8 @@ SILVERBULLET_PUBLIC_PORT=3000
|
|||||||
SILVERBULLET_GIT_INTERVAL=
|
SILVERBULLET_GIT_INTERVAL=
|
||||||
|
|
||||||
# --- Go backend --------------------------------------------------------------
|
# --- Go backend --------------------------------------------------------------
|
||||||
# BACKEND_HOST is the container name and the nginx upstream.
|
# BACKEND_HOST is the container name and the Caddy upstream.
|
||||||
# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then
|
# BACKEND_ENDPOINT is the public URL prefix Caddy mounts the API at and then
|
||||||
# strips; the Vue app's GraphQL client assumes /api.
|
# strips; the Vue app's GraphQL client assumes /api.
|
||||||
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
|
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
|
||||||
# everyone out.
|
# everyone out.
|
||||||
@@ -173,7 +168,7 @@ SPOTIFY_AUTH_STATE=
|
|||||||
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
|
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
|
||||||
# with it, and a live-broadcasting client authenticates to the liquidsoap
|
# with it, and a live-broadcasting client authenticates to the liquidsoap
|
||||||
# harbor port with it. Anyone holding it can take over the stream.
|
# 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_SOURCE_PASSWORD=
|
||||||
ICECAST_RELAY_PASSWORD=
|
ICECAST_RELAY_PASSWORD=
|
||||||
ICECAST_ADMIN_USER=
|
ICECAST_ADMIN_USER=
|
||||||
@@ -185,10 +180,11 @@ LIQUIDSOAP_HARBOR_MOUNT=/live
|
|||||||
LIQUIDSOAP_HARBOR_PORT=8001
|
LIQUIDSOAP_HARBOR_PORT=8001
|
||||||
|
|
||||||
# --- TLS / identity ----------------------------------------------------------
|
# --- TLS / identity ----------------------------------------------------------
|
||||||
# DOMAIN is the APEX domain with no scheme and no www; certbot requests both
|
# DOMAIN is the APEX domain with no scheme and no www; Caddy gets a
|
||||||
# it and www.DOMAIN on one certificate, and nginx canonicalises to www.
|
# certificate for it and for www.DOMAIN, and canonicalises to www.
|
||||||
# EMAIL is the Let's Encrypt account address for certbot. Caddy registers
|
# EMAIL was certbot's Let's Encrypt account address. Nothing reads it since
|
||||||
# its ACME account without one (Let's Encrypt no longer sends expiry notices).
|
# the move to Caddy, which registers its ACME account without one; it stays
|
||||||
|
# for the nginx/certbot rollback (DEPLOYMENT.md §7).
|
||||||
DOMAIN=
|
DOMAIN=
|
||||||
EMAIL=
|
EMAIL=
|
||||||
|
|
||||||
@@ -199,13 +195,12 @@ EMAIL=
|
|||||||
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
|
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
|
||||||
# the container restarting with an error and the site reachable directly.
|
# the container restarting with an error and the site reachable directly.
|
||||||
CLOUDFLARE_TUNNEL_TOKEN=
|
CLOUDFLARE_TUNNEL_TOKEN=
|
||||||
# Cloudflare API token for the DNS-01 challenge (My Profile -> API Tokens ->
|
# Cloudflare API token for Caddy's DNS-01 challenge (caddy/sites/prod.caddy):
|
||||||
# Create Token -> "Edit zone DNS", limited to this zone). Set, the certificate
|
# My Profile -> API Tokens -> Create Token -> "Edit zone DNS", limited to this
|
||||||
# renews without any inbound port, so the router's 80/443 forwards can close.
|
# zone, then add Zone -> Zone -> Read on the same zone (the template only has
|
||||||
# certbot: blank falls back to HTTP-01 on port 80.
|
# DNS -> Edit). Certificates are issued and renewed with no inbound port, so
|
||||||
# Caddy (caddy/sites/prod.caddy) has no fallback and also needs Zone -> Zone
|
# the router forwards nothing. Required in production: Caddy has no HTTP
|
||||||
# -> Read on the same zone, so add that permission to the token. Changing it
|
# challenge to fall back to. Changing it needs `docker compose up -d caddy`.
|
||||||
# needs `docker compose up -d caddy`.
|
|
||||||
CLOUDFLARE_DNS_API_TOKEN=
|
CLOUDFLARE_DNS_API_TOKEN=
|
||||||
|
|
||||||
# --- Third-party API keys (backend) ------------------------------------------
|
# --- Third-party API keys (backend) ------------------------------------------
|
||||||
@@ -286,14 +281,14 @@ TRACKER_TZ=Europe/London
|
|||||||
|
|
||||||
# --- Receipt printer (/receipt/) ---------------------------------------------
|
# --- Receipt printer (/receipt/) ---------------------------------------------
|
||||||
# Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi,
|
# 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.
|
# Tailscale.
|
||||||
# host:port of that server, by Tailscale IP. Blank points nowhere and
|
# host:port of that server, by Tailscale IP. Blank points nowhere and
|
||||||
# /receipt/ answers "offline".
|
# /receipt/ answers "offline".
|
||||||
RECEIPT_WEB_UPSTREAM=100.107.152.119:8765
|
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
|
# 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=
|
RECEIPT_WEB_TOKEN=
|
||||||
|
|
||||||
# TfL Unified API key (500 req/min); used by the Python hotel finder
|
# TfL Unified API key (500 req/min); used by the Python hotel finder
|
||||||
@@ -318,7 +313,7 @@ S3_SECRET_ACCESS_KEY=
|
|||||||
# Blank keeps uploads on disk. Set to http://garage:3900 (after running
|
# 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
|
# 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
|
# 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=
|
S3_ENDPOINT=
|
||||||
# Optional; these defaults match garage.toml and bootstrap.sh.
|
# Optional; these defaults match garage.toml and bootstrap.sh.
|
||||||
S3_REGION=garage
|
S3_REGION=garage
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
# The same host-mode act_runner as deploy.yaml, so (as there) nothing but
|
# 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.
|
# 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
|
# --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:
|
# the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same reason:
|
||||||
# without it Renovate clones from the URL Gitea advertises, which is
|
# without it Renovate clones from the URL Gitea advertises, which is
|
||||||
# ROOT_URL — the public https://…/gitea/ path.
|
# ROOT_URL — the public https://…/gitea/ path.
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
make check
|
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)
|
### 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
|
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)
|
### 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.
|
**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. `nginx/` and `certbot/` are the pre-cutover edge, kept only as the rollback.
|
||||||
|
|
||||||
## Backend Structure
|
## 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).
|
- **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`.
|
- **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`.
|
- **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.
|
- **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.
|
- **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.
|
- **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
|
## 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.
|
- **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.
|
- **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.
|
- **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.
|
||||||
|
|||||||
+229
-244
@@ -2,18 +2,18 @@
|
|||||||
|
|
||||||
How this site is put together and how to operate it. Application code is
|
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
|
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,
|
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
|
reached over Tailscale as `stpvm.tailf20278.ts.net`; until 2026-10-15 it was
|
||||||
the Raspberry Pi `stppi`), as Docker containers on one bridge
|
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
|
## 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
|
3000/2222, and the liquidsoap harbor port. Everything else is internal. Web
|
||||||
traffic can also come in through the Cloudflare tunnel (`cloudflared`), which
|
traffic can also come in through the Cloudflare tunnel (`cloudflared`), which
|
||||||
dials out and publishes no port; see "Cloudflare Tunnel" in §3.
|
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
|
:80 :443| :3000 / :2222 :8001
|
||||||
v v v
|
v v v
|
||||||
+--------------+ +--------+ +-------------+
|
+--------------+ +--------+ +-------------+
|
||||||
| nginx | | gitea | | liquidsoap |
|
| caddy | | gitea | | liquidsoap |
|
||||||
| (TLS, SPA, | | (git + | | harbor |
|
| (TLS, SPA, | | (git + | | harbor |
|
||||||
| reverse | | CI) | | (live DJ) |
|
| reverse | | CI) | | (live DJ) |
|
||||||
| proxy) | +--------+ +------+------+
|
| proxy) | +--------+ +------+------+
|
||||||
@@ -45,74 +45,86 @@ backend icecast2 gitea sb sb-pub python | |
|
|||||||
| db | postgres:16
|
| db | postgres:16
|
||||||
+------+ (app database + gitea database)
|
+------+ (app database + gitea database)
|
||||||
|
|
||||||
vue one-shot build container -> writes vue_dist volume -> nginx serves it
|
vue one-shot build container -> writes vue_dist volume -> caddy serves it
|
||||||
certbot no ports; shares ./certbot/conf and ./certbot/www with nginx
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Who listens where
|
### Who listens where
|
||||||
|
|
||||||
| Service | Container name | Internal port | Public route | Published to host |
|
| 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 |
|
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
|
||||||
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
|
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
|
||||||
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | 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-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
|
||||||
| silverbullet-git | n/a | n/a | none (timer loop) | no |
|
| silverbullet-git | n/a | n/a | none (timer loop) | no |
|
||||||
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | 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 |
|
| 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 nginx `auth_request`; `/api/v1/` bearer/app-checked) | 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** |
|
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
|
||||||
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
|
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
|
||||||
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
|
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
|
||||||
| certbot | `certbot` | — | — | no |
|
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of Caddy, via Cloudflare | no (outbound only) |
|
||||||
| 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 Caddy `forward_auth`; reads the Docker socket) | no |
|
||||||
| 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 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 |
|
||||||
| 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 |
|
|
||||||
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | 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 (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
|
Container names come from `.env`, and Caddy builds its upstreams from the same
|
||||||
variables. **Renaming a `*_HOST` value renames the container and repoints nginx
|
variables (passed through the caddy service's `environment:` list). **Renaming
|
||||||
in one step — never change one without the other.**
|
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
|
The config is `caddy/Caddyfile` (global options and snippets), `caddy/routes.caddy`
|
||||||
cookies and the CORS rules all assume `www.<DOMAIN>`.
|
(every proxied route, shared by dev and production) and `caddy/sites/`
|
||||||
- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/py` are stripped
|
(`prod.caddy`, `dev.caddy`). Each file's header explains it.
|
||||||
— 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
|
- **Canonical host.** `http://` → `https://www.<DOMAIN>`, and apex → `www`. The
|
||||||
prefix serves a blank page with nothing in the log.
|
SPA, the cookies and the CORS rules all assume `www.<DOMAIN>`.
|
||||||
by a `rewrite ... break` before proxying; each upstream serves from `/`.
|
- **Route order is literal.** `routes.caddy` is one ordered list inside a
|
||||||
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
|
`route` block, and the first matching `handle` wins: denials first, then each
|
||||||
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
|
carve-out ahead of the gated prefix it is carved out of. A new route goes in
|
||||||
backend down (502s until it appears) instead of refusing to start.
|
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
|
- **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
|
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
|
||||||
branch views stay public) are
|
branch views stay public) are
|
||||||
protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure
|
protected by `forward_auth` to the backend's `/auth/validate-admin` (the
|
||||||
redirects to the SPA login. Most of these services have no auth of their own at that path; 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
|
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`.
|
`/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
|
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
|
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
|
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.
|
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
|
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
|
||||||
keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of
|
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
|
file _list_; direct `/.fs/` fetches and server-rendered page URLs still serve
|
||||||
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
|
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
|
adding it to the deny regex publishes it. `caddy/edge_test.sh` checks these
|
||||||
comment above `location /notes/` in `nginx_routes.conf.template`.
|
denials against a running edge.
|
||||||
- **Uploads: the bucket first, then disk.** `/uploads/<f>` is fetched from
|
- **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
|
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
|
`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;
|
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"
|
a Garage outage only affects files that exist nowhere else. See "Garage"
|
||||||
@@ -130,14 +142,12 @@ docker compose up --build
|
|||||||
```
|
```
|
||||||
|
|
||||||
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
|
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
|
||||||
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
|
2. `caddy` starts with the image's own command (`caddy run` on
|
||||||
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
|
`/etc/caddy/Caddyfile`). `CADDY_SITE` is unset, so it loads
|
||||||
- renders `nginx.conf.template` if the cert is there, else
|
`sites/prod.caddy`. It serves at once: the SPA is whatever is in `vue_dist`,
|
||||||
`nginx_setup.conf.template`;
|
and upstreams that are not up yet are 502s. If `./caddy/data` holds no
|
||||||
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
|
certificate it obtains one first (§3), and TLS fails for those seconds.
|
||||||
nginx either way.
|
3. Everything else comes up in parallel; `depends_on` here is the plain list
|
||||||
3. `certbot` obtains or confirms the certificate, then loops renewing.
|
|
||||||
4. Everything else comes up in parallel; `depends_on` here is the plain list
|
|
||||||
form, which waits only for _start_, not readiness.
|
form, which waits only for _start_, not readiness.
|
||||||
|
|
||||||
On the host this is triggered automatically by `.gitea/workflows/deploy.yaml`,
|
On the host this is triggered automatically by `.gitea/workflows/deploy.yaml`,
|
||||||
@@ -145,9 +155,10 @@ which has two jobs:
|
|||||||
|
|
||||||
- **`test`** runs on every push to any branch. It exports the pushed commit
|
- **`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
|
(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
|
`golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build and
|
||||||
not repeated here: the image build in the deploy step does it, and a failed
|
the Caddy config check are not repeated here: the image builds in the deploy
|
||||||
build leaves the old containers running.
|
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
|
- **`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
|
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`,
|
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
|
||||||
@@ -180,21 +191,24 @@ rather than be passed with `--env-file`, because several services read
|
|||||||
volume created with them, and as in production only `POSTGRES_DB` is created
|
volume created with them, and as in production only `POSTGRES_DB` is created
|
||||||
automatically.
|
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
|
- **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
|
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
|
image's installed deps are not hidden by the bind mount. You don't need
|
||||||
`node_modules` on the host.
|
`node_modules` on the host.
|
||||||
- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a
|
- **caddy** — `CADDY_SITE=dev`, which loads `caddy/sites/dev.caddy`: `/`
|
||||||
`CN=localhost` certificate (once, kept in `certbot/conf`) and render
|
proxies to the Vite dev server, both `:80` and `:443` serve the whole site,
|
||||||
`nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and
|
no HSTS or other security headers, no HTTP→HTTPS redirect. HTTPS uses a
|
||||||
`:443` serve the whole site, no HSTS, no HTTP→HTTPS redirect.
|
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
|
- **backend** — `DEV_MODE`, GraphQL playground and introspection on, a localhost
|
||||||
Spotify redirect URI, and **`SEED_DB=true`**.
|
Spotify redirect URI, and **`SEED_DB=true`**.
|
||||||
- **python** — `uvicorn --reload` with `python/app` bind-mounted.
|
- **python** — `uvicorn --reload` with `python/app` bind-mounted.
|
||||||
- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt
|
- **jobs** — seeded, with the GraphQL playground on.
|
||||||
cannot validate localhost anyway.
|
- **cloudflared** — put in the `disabled` profile, so it never starts: a dev
|
||||||
|
stack must never join the production tunnel.
|
||||||
|
|
||||||
Visit `http://localhost`.
|
Visit `http://localhost`.
|
||||||
|
|
||||||
@@ -207,82 +221,78 @@ Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. TLS: first issuance and renewal
|
## 3. TLS: certificates
|
||||||
|
|
||||||
### The chicken-and-egg
|
Caddy obtains and renews its own certificates (`prod_tls` in
|
||||||
|
`caddy/sites/prod.caddy`): one per name, `<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
|
**First run on a new host or domain.** Set `CLOUDFLARE_DNS_API_TOKEN` (the
|
||||||
`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that
|
token needs **Zone → Zone → Read** and **Zone → DNS → Edit** on this zone; see
|
||||||
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.
|
`.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
|
docker compose logs caddy | grep -E 'obtaining certificate|certificate obtained|error'
|
||||||
`/.well-known/acme-challenge/` from `/var/www/certbot` and 404s everything else,
|
```
|
||||||
so a half-configured site is never partially exposed.
|
|
||||||
|
|
||||||
**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.`
|
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
|
||||||
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.
|
|
||||||
|
|
||||||
### 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
|
**Losing `./caddy/data`** costs only a re-issue on the next start. Let's
|
||||||
until the cert is inside its 30-day window, so this is well within Let's Encrypt
|
Encrypt allows five certificates for the same name a week, so do not make a
|
||||||
rate limits — it just means the window is checked twice a day. Certs are valid 90
|
habit of it.
|
||||||
days, so renewal lands around day 60.
|
|
||||||
|
|
||||||
**Validation method.** With `CLOUDFLARE_DNS_API_TOKEN` set, certbot proves
|
Until 2026-11-17 this was certbot plus a bootstrap nginx config, a reload
|
||||||
control of the domain by creating a `_acme-challenge` TXT record through the
|
sentinel and a watcher loop. `certbot/` and its `./certbot/conf` stay on the
|
||||||
Cloudflare API (DNS-01), so renewal needs no inbound port at all. That is
|
host as the rollback (§7); that certificate expires on 2027-01-20.
|
||||||
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.
|
|
||||||
|
|
||||||
### Cloudflare Tunnel
|
### Cloudflare Tunnel
|
||||||
|
|
||||||
The `cloudflared` container holds an outbound connection to Cloudflare and
|
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
|
_remotely managed_ tunnel: the only thing in this repo is the token
|
||||||
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
|
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
|
||||||
origin settings live in the dashboard.
|
origin settings live in the dashboard.
|
||||||
|
|
||||||
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
|
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
|
||||||
terminates the visitor's TLS at its edge, and cloudflared opens a second TLS
|
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
|
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
|
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`).
|
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
|
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
|
against a name it covers. `https://caddy` would fail that check and need No
|
||||||
TLS Verify. The flip side: **an expired certificate now takes the tunnel down
|
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.
|
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
|
An alias only exists while Caddy is running, so cloudflared also pins both
|
||||||
names to nginx's fixed address (`172.28.255.251`) with `extra_hosts`. Without
|
names to Caddy'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
|
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
|
falls through to public DNS, resolves to Cloudflare itself, and visitors see
|
||||||
Cloudflare error 1000 instead of a 502.
|
Cloudflare error 1000 instead of a 502.
|
||||||
|
|
||||||
The aliases have a side effect for anything else on `app-network` that uses
|
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
|
Gitea's SSH on `<DOMAIN>:2222`, so it maps `<DOMAIN>` to the host gateway
|
||||||
instead, where Gitea publishes that port.
|
instead, where Gitea publishes that port.
|
||||||
|
|
||||||
@@ -297,27 +307,28 @@ Setup, once:
|
|||||||
4. Add a public hostname per name, each with service `HTTPS` and its own
|
4. Add a public hostname per name, each with service `HTTPS` and its own
|
||||||
name as the URL, and no other settings:
|
name as the URL, and no other settings:
|
||||||
- `www.<DOMAIN>` → `https://www.<DOMAIN>`: the site.
|
- `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/`.
|
at `/v2/`.
|
||||||
Creating each hostname replaces the existing A record for that name with
|
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
|
a CNAME to the tunnel. **That is the cutover**: until then the tunnel
|
||||||
carries nothing.
|
carries nothing.
|
||||||
|
|
||||||
5. Create a Cloudflare API token (My Profile → API Tokens → "Edit zone
|
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
|
DNS", this zone only), add **Zone → Zone → Read** to it, and set it as
|
||||||
then renews over DNS-01 (see Renewal above) and needs no inbound port.
|
`CLOUDFLARE_DNS_API_TOKEN`. Caddy then obtains and renews over DNS-01
|
||||||
6. On the host, point the apex at nginx locally (next section).
|
(§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
|
7. Close the router's 80 and 443 forwards. Once 5 and 6 are done nothing
|
||||||
depends on them.
|
depends on them.
|
||||||
|
|
||||||
#### What the tunnel does not carry, and where it goes instead
|
#### What the tunnel does not carry, and where it goes instead
|
||||||
|
|
||||||
- **Certificate renewal.** Over DNS-01 with `CLOUDFLARE_DNS_API_TOKEN` set;
|
- **Certificate renewal.** Over DNS-01 only: Caddy is given no HTTP
|
||||||
without it certbot falls back to HTTP-01, which needs port 80 forwarded.
|
challenge to fall back to, so without a working `CLOUDFLARE_DNS_API_TOKEN`
|
||||||
The certificate matters behind the tunnel: cloudflared verifies it, as
|
nothing is issued or renewed. The certificate matters behind the tunnel:
|
||||||
do the registry path below and any direct LAN access. A fresh machine with no
|
cloudflared verifies it, as do the registry path below and any direct LAN
|
||||||
certificate at all boots the setup config (§3), which serves nothing over
|
access. A fresh machine with no certificate serves nothing over 443 until
|
||||||
443, so the tunnel carries nothing until the first issuance.
|
the first issuance (§3), so the tunnel carries nothing for those seconds.
|
||||||
- **Registry pushes and pulls on the host.** Cloudflare caps request bodies at
|
- **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
|
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
|
tunnel fails. The runner on the host pushes to `<DOMAIN>/adamf/...` and the
|
||||||
@@ -328,7 +339,7 @@ Setup, once:
|
|||||||
127.0.0.1 <DOMAIN>
|
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
|
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
|
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
|
that wants the public site. Pushing from another machine still goes
|
||||||
@@ -364,24 +375,25 @@ Setup, once:
|
|||||||
| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) |
|
| `garage_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 |
|
| `garage_data` | The bucket's object bytes | Every upload stored in Garage |
|
||||||
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
|
| `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
|
**Bind mounts** — live in the repo checkout on the host, survive everything short
|
||||||
of deleting the directory:
|
of deleting the directory:
|
||||||
|
|
||||||
| Path | Holds | Notes |
|
| Path | Holds | Notes |
|
||||||
| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
||||||
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
|
| `./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/www` | ACME challenge webroot | Transient by nature |
|
| `./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. |
|
| `./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. |
|
| `./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/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 |
|
| `./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 |
|
| `./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 |
|
| `${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
|
**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.
|
are all regenerated.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -396,11 +408,11 @@ Two distinct mechanisms read it, and services use both:
|
|||||||
- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse
|
- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse
|
||||||
time. Builds container names and published ports.
|
time. Builds container names and published ports.
|
||||||
- **`env_file: ./.env`** — injects the whole file into the container. Used by
|
- **`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
|
`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own
|
||||||
convention for overriding `app.ini` keys), and `python` receives an explicit
|
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`,
|
the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`,
|
||||||
which picks the model). The Python service
|
which picks the model). The Python service
|
||||||
makes the site's one Claude call (the rowing photo reader); the `jobs` container
|
makes the site's one Claude call (the rowing photo reader); the `jobs` container
|
||||||
@@ -414,7 +426,7 @@ to be added to its allow-list as well as
|
|||||||
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's
|
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's
|
||||||
`.env` (often with dev values) never reaches production by accident.
|
`.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
|
which for a password field means _no password_. After editing `.env`, confirm
|
||||||
with `docker compose config`.
|
with `docker compose config`.
|
||||||
|
|
||||||
@@ -422,40 +434,48 @@ with `docker compose config`.
|
|||||||
|
|
||||||
Edit `.env` on the host, and recreate only the services that read the variable:
|
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,
|
`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
|
## 6. Rate limits
|
||||||
|
|
||||||
Defined once per config in the `http` block, applied per location. Keyed on
|
The `rate_limit` directive comes from the `mholt/caddy-ratelimit` plugin
|
||||||
`$binary_remote_addr` — the client IP in packed form, so each entry is ~64 bytes
|
(compiled in by `caddy/Dockerfile`) and is applied per route through the
|
||||||
and a `10m` zone holds roughly 160k IPs. `10m` is a safe round number, not a
|
`limit` snippet: `import limit <zone> <events> <window>`. Each zone is a
|
||||||
tuned value.
|
**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
|
A refused request gets **503**, not the plugin's 429: `handle_errors 429` in
|
||||||
request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead
|
the Caddyfile rewrites it, because `vue/src/views/hotels/hotelsStream.js`
|
||||||
of that drip, and `nodelay` (used everywhere here) serves those N immediately.
|
tells a rate-limit 503 ("too many searches from your address") apart from the
|
||||||
So the effective behaviour is _"N instant requests, then throttled to the drip
|
Python service's own 429 ("someone else is searching").
|
||||||
rate"_. Anything beyond the burst gets an immediate **503**.
|
|
||||||
|
|
||||||
| Zone | Rate | Burst | Applied to | Why |
|
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
|
||||||
| `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. |
|
name must always be given the same numbers. A route that wants different ones
|
||||||
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
|
gets its own zone, as `/receipt/` does.
|
||||||
| `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. |
|
| Zone | Limit | Applied to | Why |
|
||||||
| `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. |
|
| -------------- | --------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `login` | 5 / 1m | `/api/auth/login` | Brute-force defence, on top of the backend's own 5/min. A human mistyping gets five tries a minute; a credential-stuffing script gets nothing useful. |
|
||||||
|
| `api` | 30 / 1s | `/api/`, `/py/`, `/jobs/`, `/usaco/`, `/tracker/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
|
||||||
|
| `graphql` | 10 / 1s | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. Dev has it too now. |
|
||||||
|
| `upload` | 30 / 1m | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
|
||||||
|
| `hotel_search` | 3 / 1m | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
|
||||||
|
| `receipt` | 10 / 1s | `/receipt/` | Prints are slow and physical; ten a second is far above any real use. |
|
||||||
|
|
||||||
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
|
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
|
||||||
request, and a limit there would drop reconnect storms rather than abuse.
|
request, and a limit there would drop reconnect storms rather than abuse.
|
||||||
|
|
||||||
These zones key on `$remote_addr`. For tunnel traffic nginx rewrites that
|
`{client_ip}` is the visitor's address only because of `trusted_proxies` and
|
||||||
from Cloudflare's `CF-Connecting-IP` header (`set_real_ip_from` /
|
`client_ip_headers CF-Connecting-IP` in the Caddyfile's global options, which
|
||||||
`real_ip_header` in `nginx.conf.template`), trusting the header only from
|
trust that header from cloudflared's fixed address alone. **If that address
|
||||||
cloudflared's fixed address. **If that address changes in
|
changes in `docker-compose.yml` without the Caddyfile, every tunnel visitor
|
||||||
`docker-compose.yml` without the nginx line, every tunnel visitor shares
|
shares cloudflared's one bucket**, and the login limit locks everyone out
|
||||||
cloudflared's one bucket**, and the login limit locks everyone out together.
|
together.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -477,99 +497,76 @@ git pull && docker compose up -d --build --remove-orphans
|
|||||||
docker compose up -d --build backend
|
docker compose up -d --build backend
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: editing `certbot/entrypoint.sh` needs no rebuild (it is bind-mounted over
|
**Apply a Caddy config change.** Everything in `caddy/` is copied into the
|
||||||
the stock image's entrypoint) — just `docker compose restart certbot`. Editing
|
image, so a change needs a rebuild, which also validates it (the Dockerfile's
|
||||||
an nginx **template** does need a rebuild, since templates are `COPY`'d into the
|
last step runs `caddy validate` for the production and dev sites, and a
|
||||||
image.
|
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,
|
||||||
**Apply a new nginx config / pick up a renewed certificate:**
|
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
|
make check-caddy # on a laptop, before pushing
|
||||||
docker compose restart nginx # certificate changed
|
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
|
||||||
docker compose exec certbot certbot renew --webroot -w /var/www/certbot
|
`Cookie` header value as `EDGE_COOKIE` to cover the signed-in cases. On the
|
||||||
docker compose restart nginx
|
host, pin the name to the machine or curl goes out over the internet:
|
||||||
```
|
|
||||||
|
|
||||||
Add `--dry-run` to test without burning rate limit.
|
|
||||||
|
|
||||||
**Caddy beside nginx (the edge migration, in progress).** `caddy/` is the
|
|
||||||
replacement for `nginx/` and certbot. Until the cutover the `caddy` container
|
|
||||||
runs next to nginx and serves nothing public: it listens on the host's
|
|
||||||
loopback only (`127.0.0.1:8880` http, `127.0.0.1:8443` https), has no network
|
|
||||||
aliases, and gets its own certificates over DNS-01 into `./caddy/data`. That
|
|
||||||
needs `CLOUDFLARE_DNS_API_TOKEN` to carry **Zone → Zone → Read** as well as
|
|
||||||
DNS → Edit (certbot only needed the second); without it Caddy logs failed
|
|
||||||
orders and the public site is unaffected. Watch the first issuance with:
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose logs -f caddy | grep -i -E 'certificate|error'
|
|
||||||
```
|
|
||||||
|
|
||||||
Then compare the two edges request by request (the script's header explains
|
|
||||||
the output; pass an admin session's cookie as `EDGE_COOKIE` to cover the
|
|
||||||
signed-in cases too):
|
|
||||||
|
|
||||||
```
|
```
|
||||||
export "$(grep '^DOMAIN=' .env)"
|
export "$(grep '^DOMAIN=' .env)"
|
||||||
caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >nginx.txt
|
caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
|
||||||
caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >caddy.txt
|
|
||||||
diff nginx.txt caddy.txt
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The expected differences: `Server: nginx` is gone, the gates match paths
|
**Roll back to nginx** (until `nginx/` and `certbot/` are removed; the certbot
|
||||||
case-insensitively (so `/SB/` is gated instead of falling to the SPA), and
|
certificate in `./certbot/conf` is valid until 2027-01-20). `git revert` the
|
||||||
`X-Frame-Options`/`Cache-Control` come out in a different order or combined.
|
cutover commit and push, or by hand on the host, under the lock so a deploy
|
||||||
A Caddyfile change is checked by `make check-caddy`, the same image build the
|
cannot interleave:
|
||||||
deploy runs, which validates the production and dev configs.
|
|
||||||
|
```
|
||||||
|
git revert --no-edit <cutover commit>
|
||||||
|
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:**
|
**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 logs --tail=200 backend
|
||||||
docker compose ps # note: `vue` Exited(0) is correct
|
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
|
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
|
||||||
login required).
|
login required).
|
||||||
|
|
||||||
**Incoming request bodies.** nginx writes one JSON line per request, body
|
**Incoming request bodies.** Caddy writes one JSON line per request, body
|
||||||
included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The
|
included, to `logs/caddy/payloads.log` (the `payloads_file` logger and the
|
||||||
`traffic` container tails it, so in Dozzle pick **traffic** and each request
|
`logging` snippet in `caddy/Caddyfile`). The `traffic` container tails it, so
|
||||||
renders as fields you can search. From a shell:
|
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")'
|
tail -f logs/caddy/payloads.log | jq 'select(.request.method=="POST")'
|
||||||
jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log
|
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]`
|
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
|
||||||
(that covers every login and the refresh call). Bodies over 64 KB, i.e.
|
(that covers every login and the refresh call), and `Cookie`/`Authorization`
|
||||||
uploads, are logged with an empty `body`, and responses are never logged.
|
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
|
Caddy rotates the file itself (50 MiB, five old files kept), and `tail -F`
|
||||||
`/etc/logrotate.d/web_server`:
|
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.
|
||||||
/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.
|
|
||||||
|
|
||||||
**Reset the database** — destructive; wipes the app database **and Gitea's**:
|
**Reset the database** — destructive; wipes the app database **and Gitea's**:
|
||||||
|
|
||||||
@@ -594,8 +591,8 @@ or not set up:
|
|||||||
|
|
||||||
- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to
|
- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to
|
||||||
disk (with a log line) whenever Garage refuses a write;
|
disk (with a log line) whenever Garage refuses a write;
|
||||||
- nginx serves `/uploads/` from Garage and falls back to the volume when
|
- Caddy serves `/uploads/` from Garage and falls back to the volume when
|
||||||
Garage has no such file or is unreachable, and it boots without the
|
Garage has no such file or is unreachable, and it starts without the
|
||||||
`garage` container.
|
`garage` container.
|
||||||
|
|
||||||
Turning it on:
|
Turning it on:
|
||||||
@@ -640,7 +637,7 @@ to drop Garage entirely, first copy them back
|
|||||||
**Managing files:** garage-webui at `/garage/` (site admin login). Files
|
**Managing files:** garage-webui at `/garage/` (site admin login). Files
|
||||||
uploaded there are public at `/uploads/<path>` and skip the backend's type
|
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
|
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.
|
**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
|
Back up `garage_meta` and `garage_data` together (meta without data, or the
|
||||||
@@ -681,26 +678,27 @@ icecast source password. liquidsoap pre-empts the fallback playlist immediately
|
|||||||
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
|
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
|
||||||
(`reload_mode="watch"`) with no restart.
|
(`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
|
`unhealthy` but never acts on it; `restart: always` only brings back a process
|
||||||
that exits. The `autoheal` container restarts anything labelled
|
that exits. The `autoheal` container restarts anything labelled
|
||||||
`autoheal=true`, which today is just nginx (its healthcheck fetches
|
`autoheal=true`, which today is just caddy (its healthcheck fetches
|
||||||
`/nginx-health` on :80 every 30s; three misses, about 90s, and it is
|
`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
|
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
|
label, so for them `unhealthy` is only visible in `docker ps`. Add the label to
|
||||||
cover another service.
|
cover another service.
|
||||||
|
|
||||||
**Site down but every container `Up`.** That is what a stalled nginx worker
|
**Site down but every container `Up`.** That is what a stalled edge looks
|
||||||
looks like (2026-10-19: 4.6 hours, every tunnel request a `TLS handshake
|
like (2026-10-19, under nginx: 4.6 hours, every tunnel request a `TLS
|
||||||
timeout` in `docker logs cloudflared`, and the Cloudflare dashboard still
|
handshake timeout` in `docker logs cloudflared`, and the Cloudflare dashboard
|
||||||
showing the tunnel healthy, since that only covers the tunnel's own link). The
|
still showing the tunnel healthy, since that only covers the tunnel's own
|
||||||
healthcheck should now catch it. If it recurs, capture the stuck worker before
|
link). The healthcheck should catch it. If it happens, capture what Caddy is
|
||||||
restarting, since a restart destroys the only evidence of why:
|
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 inspect caddy --format '{{.State.Health.Status}}'
|
||||||
docker top nginx -o pid,stat,wchan:30,etime,cmd # what each worker is waiting in
|
docker compose exec caddy wget -q -O - 'http://localhost:2019/debug/pprof/goroutine?debug=2' > caddy-goroutines.txt
|
||||||
docker compose restart nginx
|
docker compose restart caddy
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -709,25 +707,12 @@ docker compose restart nginx
|
|||||||
|
|
||||||
Documented, not fixed — each would change deploy behaviour.
|
Documented, not fixed — each would change deploy behaviour.
|
||||||
|
|
||||||
1. **Renewed certificates are not served until nginx restarts.** No
|
1. **`nginx/`, `certbot/` and their host directories are still here** as the
|
||||||
`--deploy-hook` in `certbot/entrypoint.sh`. Fix: add
|
rollback from the 2026-11-17 cutover. Once Caddy has run for a couple of
|
||||||
`--deploy-hook "touch /var/www/certbot/.reloadme"` plus a watcher, or give
|
weeks: move `nginx/` and `certbot/` to `.deprecated/`, then delete
|
||||||
certbot the docker socket to send nginx a `HUP`.
|
`./certbot/` and `./logs/nginx/` on the host and the `logs/nginx` logrotate
|
||||||
2. **First TLS issuance needs a manual `docker compose restart nginx`.** The
|
stanza.
|
||||||
entrypoint only re-evaluates cert presence at container start.
|
2. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be
|
||||||
3. **`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
|
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
|
shadowed by an explicit file mount — fragile. Deleting it would be safe but
|
||||||
is a file removal.
|
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.
|
|
||||||
|
|||||||
@@ -128,6 +128,6 @@ check-caddy:
|
|||||||
generate:
|
generate:
|
||||||
cd backend && go run github.com/99designs/gqlgen 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:
|
dev:
|
||||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||||
|
|||||||
@@ -15,11 +15,11 @@ After hearing all the hype on LinkedIn and feeling the pressure to keep up a hig
|
|||||||
|
|
||||||
## Architecture
|
## 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)
|
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)
|
backend (8080) ── Go API (GraphQL + REST)
|
||||||
db (5432) ── PostgreSQL 16
|
db (5432) ── PostgreSQL 16
|
||||||
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
|
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-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
|
||||||
silverbullet-git ── Commits/pushes notes edits to the notes repo
|
silverbullet-git ── Commits/pushes notes edits to the notes repo
|
||||||
python (8000) ── Python API (FastAPI)
|
python (8000) ── Python API (FastAPI)
|
||||||
certbot ── SSL Certificate Management (disabled in dev)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Tech Stack
|
## Tech Stack
|
||||||
@@ -39,7 +38,7 @@ certbot ── SSL Certificate Management (disabled in dev)
|
|||||||
|
|
||||||
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
|
**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
|
## Features
|
||||||
|
|
||||||
@@ -56,7 +55,7 @@ certbot ── SSL Certificate Management (disabled in dev)
|
|||||||
- Printable CV with role-specific sections
|
- Printable CV with role-specific sections
|
||||||
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
|
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
|
||||||
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
|
- 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
|
- Landing page with animated stamps section
|
||||||
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
||||||
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
|
- 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 |
|
| POST | `/api/auth/refresh` | Refresh token |
|
||||||
| GET | `/api/auth/check` | Check token validity |
|
| GET | `/api/auth/check` | Check token validity |
|
||||||
| POST | `/api/auth/logout` | Logout |
|
| 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.
|
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) |
|
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
|
||||||
|
|
||||||
### Nginx Proxy Routes
|
### Proxy Routes (Caddy)
|
||||||
|
|
||||||
| Route | Target | Notes |
|
| 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`) |
|
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
|
||||||
| `/uploads` | local alias | User-uploaded files |
|
| `/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
|
### 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
|
editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at
|
||||||
`/notes/` with `SB_READ_ONLY`
|
`/notes/` with `SB_READ_ONLY`
|
||||||
3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off
|
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")
|
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)
|
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`
|
1. Set `DOMAIN` and `CLOUDFLARE_DNS_API_TOKEN` in `.env` (the token needs Zone → Zone → Read and Zone → DNS → Edit on the zone)
|
||||||
2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/`
|
2. `docker compose up -d`. Caddy serves immediately and fetches both certificates (apex and www) into `./caddy/data` within seconds
|
||||||
3. Certbot requests a certificate via `certbot certonly --webroot`
|
3. Renewal is automatic and needs no restart
|
||||||
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
|
|
||||||
|
|
||||||
**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
|
### Icecast Radio
|
||||||
|
|
||||||
@@ -309,9 +306,9 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
|||||||
|
|
||||||
This:
|
This:
|
||||||
|
|
||||||
- Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.)
|
- 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
|
||||||
- Generates a self-signed certificate for localhost
|
- Uses a localhost certificate from Caddy's local CA
|
||||||
- Disables certbot
|
- Disables the Cloudflare tunnel
|
||||||
- Seeds the database with test data (`SEED_DB=true`)
|
- Seeds the database with test data (`SEED_DB=true`)
|
||||||
- Enables GraphQL playground and introspection
|
- Enables GraphQL playground and introspection
|
||||||
|
|
||||||
@@ -331,7 +328,7 @@ Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets defaul
|
|||||||
make check
|
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.
|
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 |
|
| `.env` | See setup section above |
|
||||||
| `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
|
| `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 |
|
| `backend/token/` | Created automatically by Docker volume mount |
|
||||||
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file |
|
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file |
|
||||||
| `gitea-runner/act_runner` | Download from Gitea releases |
|
| `gitea-runner/act_runner` | Download from Gitea releases |
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@
|
|||||||
# would fail certificate verification without a trust store.
|
# would fail certificate verification without a trust store.
|
||||||
#
|
#
|
||||||
# EXPOSE 8080 is documentation only; the port is never published to the host.
|
# 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
|
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
|
||||||
# amd64 (a dev laptop) with no platform pin.
|
# amd64 (a dev laptop) with no platform pin.
|
||||||
|
|||||||
+7
-7
@@ -1,11 +1,11 @@
|
|||||||
# Backend
|
# 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
|
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
|
||||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
|
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.
|
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
|
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
||||||
sees it.
|
sees it.
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ graph/ GraphQL layer
|
|||||||
|
|
||||||
## Request lifecycle
|
## 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.
|
proxies to this service.
|
||||||
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
|
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
|
||||||
that `ClientIP()` — which the login rate limiter keys on — cannot be
|
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
|
and will transparently refresh, so returning admins are recognised without a
|
||||||
visible re-login.
|
visible re-login.
|
||||||
- `GET /auth/validate/:permission` is the same for one named permission
|
- `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
|
*permission gate*, which lets a non-admin account into one service — the
|
||||||
receipt printer at `/receipt/` — without making it an admin. Grantable keys
|
receipt printer at `/receipt/` — without making it an admin. Grantable keys
|
||||||
are the registry `services.PermissionTypes` (`services/permissions.go`);
|
are the registry `services.PermissionTypes` (`services/permissions.go`);
|
||||||
@@ -73,7 +73,7 @@ graph/ GraphQL layer
|
|||||||
Users tab (`setUserPermissions`). Admins pass every permission check. The
|
Users tab (`setUserPermissions`). Admins pass every permission check. The
|
||||||
check reads the user row, not the token, so a grant or revoke applies on
|
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
|
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
|
- 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
|
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
|
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
|
`/jobs/` is a separate app with its own Claude calls.) It reaches the
|
||||||
internal routes directly over the Docker network
|
internal routes directly over the Docker network
|
||||||
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
|
(`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 |
|
| 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
|
to show them. Public files go to the Garage bucket wrapped in
|
||||||
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
|
`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
|
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
|
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
|
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
|
admin-only `GET /uploads`, for the canvas's upload picker) returns the union
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-
|
|||||||
const maxSlugLen = 100
|
const maxSlugLen = 100
|
||||||
|
|
||||||
// reservedFirstSegments are paths a page could never be reached at, because
|
// reservedFirstSegments are paths a page could never be reached at, because
|
||||||
// nginx or one of the SPA's own routes answers them first (see
|
// Caddy 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/routes.caddy and vue/src/router/index.js), plus the
|
||||||
// landing page's key "index", whose boxes a page of the same slug would
|
// landing page's key "index", whose boxes a page of the same slug would
|
||||||
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
|
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
|
||||||
// pages under it and the home page /stp are all canvas pages.
|
// pages under it and the home page /stp are all canvas pages.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ func TestValidateSlug(t *testing.T) {
|
|||||||
{"shrines", true}, // the index is a canvas page too
|
{"shrines", true}, // the index is a canvas page too
|
||||||
{"shrines/demoman", true}, // no longer an SPA route
|
{"shrines/demoman", true}, // no longer an SPA route
|
||||||
{"admin/pages", false}, // under 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
|
{"stp", true}, // the home page is a canvas page too
|
||||||
{"stp2", false}, // an SPA route
|
{"stp2", false}, // an SPA route
|
||||||
{"index", false}, // the landing canvas's key
|
{"index", false}, // the landing canvas's key
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ type User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# One grantable service, from services.PermissionTypes: `key` is what is
|
# 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 {
|
type PermissionType {
|
||||||
key: String!
|
key: String!
|
||||||
label: String!
|
label: String!
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
|
// 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
|
// 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
|
// answers with a bare status code and no body: 200 admin, 403 authenticated
|
||||||
// but not admin, 401 not 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
|
// gate (see services/permissions.go). Same bare-status contract and refresh
|
||||||
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
|
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
|
||||||
// permission, 401 not signed in — plus 404 for a key that is not in
|
// 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.
|
// 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
|
// 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
|
// allow receives the access token's claims, or nil when the caller was
|
||||||
// identified from the refresh token (which carries no authorisation claims).
|
// 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
|
// On 200 the username goes back in X-Auth-User, which Caddy's forward_auth
|
||||||
// auth_request_set and hand to the service behind the gate, so that service
|
// copies onto the proxied request (as X-Remote-User for /receipt/), so the
|
||||||
// knows who is using it without having accounts of its own.
|
// 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) {
|
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
|
||||||
accessToken, err := ctx.Cookie("access_token")
|
accessToken, err := ctx.Cookie("access_token")
|
||||||
if err == nil {
|
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
|
// Login backs POST /auth/login. The user object it returns omits the password
|
||||||
// because models.User tags that field `json:"-"`.
|
// because models.User tags that field `json:"-"`.
|
||||||
func (store *Store) Login(ctx *gin.Context) {
|
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
|
// ctx.ClientIP is only trustworthy because main.go pins the trusted
|
||||||
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
|
// 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()) {
|
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
|
||||||
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ type ExtractedRowingData struct {
|
|||||||
Distance uint64 `json:"distance"`
|
Distance uint64 `json:"distance"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// rowingReadPath is the Python route. It is internal: nginx refuses
|
// rowingReadPath is the Python route. It is internal: Caddy refuses
|
||||||
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
|
// /py/internal/ and the route itself refuses anything Caddy forwarded, so the
|
||||||
// only way in is the direct container-to-container call services.CallPython
|
// only way in is the direct container-to-container call services.CallPython
|
||||||
// makes.
|
// makes.
|
||||||
const rowingReadPath = "/internal/rowing/read"
|
const rowingReadPath = "/internal/rowing/read"
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func TestReadRowingDisplayRequestAndReply(t *testing.T) {
|
|||||||
var forwarded bool
|
var forwarded bool
|
||||||
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
|
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
path = r.URL.Path
|
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.
|
// answers 404, so this call must never carry them.
|
||||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||||
|
|||||||
@@ -255,7 +255,7 @@ func TestRequestIsAdmin(t *testing.T) {
|
|||||||
// --- Permission gate ------------------------------------------------------
|
// --- Permission gate ------------------------------------------------------
|
||||||
|
|
||||||
// An unknown key must be refused before any session lookup (Store has no DB
|
// 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.
|
// location shows up as a 404 rather than as a missing grant.
|
||||||
func TestValidatePermissionUnknownKey(t *testing.T) {
|
func TestValidatePermissionUnknownKey(t *testing.T) {
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ type Store struct {
|
|||||||
LoginLimiter *services.RateLimiter
|
LoginLimiter *services.RateLimiter
|
||||||
|
|
||||||
// Base URL of the Python service on the Docker network, no trailing
|
// 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).
|
// services.CallPython: reading a rowing display photo (handle_rowing.go).
|
||||||
PythonURL string
|
PythonURL string
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -50,7 +50,7 @@ func main() {
|
|||||||
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
|
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
|
||||||
r.Use(gin.Recovery())
|
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
|
// 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
|
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
|
||||||
// defined in docker-compose.yml.
|
// defined in docker-compose.yml.
|
||||||
@@ -115,7 +115,7 @@ func main() {
|
|||||||
steamID := os.Getenv("STEAM_ID")
|
steamID := os.Getenv("STEAM_ID")
|
||||||
|
|
||||||
// PYTHON SERVICE
|
// 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
|
// /internal/ Claude route (services/python_call.go). The defaults
|
||||||
// mirror docker-compose.yml, where both variables are optional.
|
// mirror docker-compose.yml, where both variables are optional.
|
||||||
pythonHost := os.Getenv("PYTHON_HOST")
|
pythonHost := os.Getenv("PYTHON_HOST")
|
||||||
@@ -145,7 +145,7 @@ func main() {
|
|||||||
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
|
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
|
||||||
|
|
||||||
// 5 login attempts per IP per minute, applied by both the REST handler
|
// 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)
|
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}
|
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
|
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||||
// the Gin context, so the order in the admin group matters.
|
// 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)
|
protected := r.Group("/", store.AuthMiddlewear)
|
||||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||||
|
|
||||||
|
|||||||
@@ -10,17 +10,17 @@ import (
|
|||||||
// service (the receipt printer, say) without being made an admin.
|
// service (the receipt printer, say) without being made an admin.
|
||||||
//
|
//
|
||||||
// A permission is a key from PermissionTypes stored in models.User.Permissions.
|
// 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
|
// (handlers.Store.ValidatePermission); admins pass every such check, so
|
||||||
// moving a service from the admin gate to a permission gate never locks an
|
// 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.
|
// admin out. Services that are not listed here stay admin-only.
|
||||||
//
|
//
|
||||||
// Adding a grantable service is one entry below plus swapping that location's
|
// Adding a grantable service is one entry below plus swapping its route in
|
||||||
// nginx gate from /internal/auth/admin-validate to the permission gate (see
|
// caddy/routes.caddy from `import admin_gate` to `import permission_gate
|
||||||
// "Permission gate" in nginx/nginx_routes.conf.template).
|
// <key>` (the snippet is in caddy/Caddyfile).
|
||||||
|
|
||||||
// PermissionType describes one grantable service. Key is what is stored and
|
// 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.
|
// the signed-in user's /account list of links.
|
||||||
type PermissionType struct {
|
type PermissionType struct {
|
||||||
Key string
|
Key string
|
||||||
|
|||||||
@@ -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) {
|
func TestPermissionKeysArePathSafe(t *testing.T) {
|
||||||
seen := map[string]bool{}
|
seen := map[string]bool{}
|
||||||
for _, p := range PermissionTypes {
|
for _, p := range PermissionTypes {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
// (handlers/handle_rowing.go); the job posting reader, email classifier and
|
// (handlers/handle_rowing.go); the job posting reader, email classifier and
|
||||||
// lead scorer went with the job tracker to its own repo.
|
// 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
|
// /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
|
// header, so the only way in is this direct container-to-container call. That
|
||||||
// is why the request below sets nothing but Content-Type.
|
// is why the request below sets nothing but Content-Type.
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func TestCallPythonRequestAndReply(t *testing.T) {
|
|||||||
)
|
)
|
||||||
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
|
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.
|
// answer 404, so the helper must never send them.
|
||||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
|
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
|
||||||
// string (in practice the client IP). It is process-local: restarting the
|
// string (in practice the client IP). It is process-local: restarting the
|
||||||
// backend clears every window, and a multi-replica deployment would limit
|
// 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.
|
// front of this, so this layer is a second line of defence, not the only one.
|
||||||
type RateLimiter struct {
|
type RateLimiter struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
// site owner scanning the log for "who is using my site". Two goals:
|
// 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:
|
// 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`,
|
// admin page hit), the front end's own polling (`/auth/refresh_token`,
|
||||||
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
|
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
|
||||||
// a single terse line, or dropped entirely when repeated in a short
|
// 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
|
// logQuietDrop lists paths whose 2xx responses are dropped outright. These
|
||||||
// are all heartbeat-style endpoints: identical every few seconds, no signal.
|
// are all heartbeat-style endpoints: identical every few seconds, no signal.
|
||||||
var logQuietDrop = map[string]bool{
|
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/refresh": true, // front-end token refresh
|
||||||
"/auth/check": true, // front-end session check
|
"/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)
|
fmt.Sprintf("%.0f%s", float64(latency), unit), marker)
|
||||||
|
|
||||||
// Visitor traffic gets the IP appended — the "who". Infrastructure
|
// 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.
|
// implied and is left lean.
|
||||||
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
|
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
|
||||||
line += " " + 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
|
// 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.
|
// that appear are either forwarded-from-humans or the ingress itself.
|
||||||
func logIsInterestingClient(ip string) bool {
|
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.")
|
return !startsWith(ip, "172.28.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-10
@@ -34,26 +34,26 @@ import (
|
|||||||
//
|
//
|
||||||
// WHERE FILES GO
|
// WHERE FILES GO
|
||||||
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
|
// 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
|
// 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
|
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
|
||||||
// the only store.
|
// the only store.
|
||||||
// Private files (admin-only chat attachments) always go to the volume, under
|
// 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.
|
// 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.
|
// 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.
|
// 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
|
// 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
|
const MaxUploadSize = 10 << 20 // 10MB
|
||||||
|
|
||||||
// UploadType describes one allowed file extension.
|
// UploadType describes one allowed file extension.
|
||||||
type UploadType struct {
|
type UploadType struct {
|
||||||
// ContentType is stored with the file and served back with it. Garage
|
// 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.
|
// `nosniff`, so a wrong type means the file doesn't display.
|
||||||
ContentType string
|
ContentType string
|
||||||
// SniffPrefix is what http.DetectContentType must report for the file's
|
// SniffPrefix is what http.DetectContentType must report for the file's
|
||||||
@@ -100,7 +100,7 @@ type Uploads struct {
|
|||||||
private FileStore
|
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 (
|
const (
|
||||||
publicURLPrefix = "/uploads/"
|
publicURLPrefix = "/uploads/"
|
||||||
privateURLPrefix = "/uploads/private/"
|
privateURLPrefix = "/uploads/private/"
|
||||||
@@ -238,7 +238,7 @@ type FileStore interface {
|
|||||||
type DiskFileStore struct{ Dir string }
|
type DiskFileStore struct{ Dir string }
|
||||||
|
|
||||||
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
|
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 {
|
if err := os.MkdirAll(d.Dir, 0755); err != nil {
|
||||||
return err
|
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
|
// 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
|
// 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) {
|
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
|
||||||
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
|
||||||
defer cancel()
|
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
|
// 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
|
// looks in both places), so a Garage outage costs a log line rather than
|
||||||
// broken uploads.
|
// broken uploads.
|
||||||
type FallbackFileStore struct {
|
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)
|
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
|
// 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,
|
// 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
|
// with the primary's details. A primary that can't list is logged and the
|
||||||
|
|||||||
+2
-2
@@ -89,8 +89,8 @@
|
|||||||
|
|
||||||
# The payload log: one JSON line per request, body included (log_append
|
# The payload log: one JSON line per request, body included (log_append
|
||||||
# in `logging`), for seeing what actually arrives at the edge.
|
# in `logging`), for seeing what actually arrives at the edge.
|
||||||
# logs/caddy/ on the host; from the cutover the `traffic` container tails
|
# logs/caddy/ on the host; the `traffic` container tails it so Dozzle
|
||||||
# it so Dozzle shows it as its own stream. Caddy rotates it itself, and
|
# 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
|
# `tail -F` follows the rotation. 0644 so `jq` on the host can read it
|
||||||
# unprivileged (Caddy's default is 0600).
|
# unprivileged (Caddy's default is 0600).
|
||||||
#
|
#
|
||||||
|
|||||||
+7
-5
@@ -32,11 +32,13 @@
|
|||||||
# Dev stack:
|
# Dev stack:
|
||||||
# caddy/edge_test.sh https://localhost -k
|
# caddy/edge_test.sh https://localhost -k
|
||||||
#
|
#
|
||||||
# COMPARING TWO EDGES (the nginx -> Caddy cutover)
|
# COMPARING TWO EDGES
|
||||||
# Run it against each and diff the output:
|
# Run it against each and diff the output. This is how Caddy was checked
|
||||||
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >nginx.txt
|
# against nginx before the 2026-11-17 cutover (Caddy on 8443 beside nginx),
|
||||||
# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >caddy.txt
|
# and how a big change to caddy/ can be checked against the running edge:
|
||||||
# diff nginx.txt caddy.txt
|
# 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.
|
# Every remaining difference should be one that was intended.
|
||||||
#
|
#
|
||||||
# NOTHING HERE WRITES. Every request is a GET, apart from one POST to
|
# NOTHING HERE WRITES. Every request is a GET, apart from one POST to
|
||||||
|
|||||||
+14
-31
@@ -12,17 +12,15 @@
|
|||||||
# - vue : one-shot `vite build` becomes the long-running Vite dev server
|
# - vue : one-shot `vite build` becomes the long-running Vite dev server
|
||||||
# with the source bind-mounted for hot reload.
|
# with the source bind-mounted for hot reload.
|
||||||
# - backend : dev flags on, including database seeding.
|
# - backend : dev flags on, including database seeding.
|
||||||
# - nginx : DEV_MODE=true, which makes its entrypoint render
|
# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy instead of
|
||||||
# nginx_dev.conf.template and self-sign a localhost certificate.
|
# the production sites: no redirects, no security headers, a
|
||||||
# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy. Until the
|
# certificate from Caddy's own local CA, `/` proxied to Vite.
|
||||||
# cutover it runs beside nginx, on 127.0.0.1:8880 / :8443.
|
|
||||||
# - python : uvicorn --reload with the app source bind-mounted.
|
# - python : uvicorn --reload with the app source bind-mounted.
|
||||||
# - certbot : disabled entirely.
|
|
||||||
# - cloudflared : disabled entirely.
|
# - cloudflared : disabled entirely.
|
||||||
#
|
#
|
||||||
# HOW TO REACH IT
|
# HOW TO REACH IT
|
||||||
# http://localhost (HTTPS also works on :443 with the self-signed cert, which
|
# http://localhost (HTTPS also works on :443 with the local-CA certificate,
|
||||||
# the browser will warn about — that is expected).
|
# which the browser will warn about — that is expected).
|
||||||
#
|
#
|
||||||
# NOT USED ON THE PI. The deploy workflow runs plain `docker compose up`.
|
# NOT USED ON THE PI. The deploy workflow runs plain `docker compose up`.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -30,7 +28,7 @@
|
|||||||
services:
|
services:
|
||||||
vue:
|
vue:
|
||||||
# Replaces the one-shot `vite build`: the container now stays up serving
|
# 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"]
|
command: ["npm", "run", "dev"]
|
||||||
volumes:
|
volumes:
|
||||||
- ./vue:/app
|
- ./vue:/app
|
||||||
@@ -57,21 +55,11 @@ services:
|
|||||||
# because dev uses a throwaway local dbdata volume; it is NEVER set
|
# because dev uses a throwaway local dbdata volume; it is NEVER set
|
||||||
# in production — seeding a live database would inject fake content.
|
# in production — seeding a live database would inject fake content.
|
||||||
- SEED_DB=true
|
- SEED_DB=true
|
||||||
nginx:
|
|
||||||
environment:
|
|
||||||
# The single switch that selects nginx_dev.conf.template and the
|
|
||||||
# self-signed localhost certificate. See nginx/entrypoint.sh.
|
|
||||||
- DEV_MODE=true
|
|
||||||
# Same mapping as the base file; restated because compose replaces the
|
|
||||||
# `ports` list rather than merging it, so omitting it here would be fine
|
|
||||||
# but restating it makes the dev surface explicit.
|
|
||||||
ports:
|
|
||||||
- 80:80
|
|
||||||
- 443:443
|
|
||||||
caddy:
|
caddy:
|
||||||
environment:
|
environment:
|
||||||
# Loads caddy/sites/dev.caddy instead of the production sites:
|
# The single switch that loads caddy/sites/dev.caddy instead of
|
||||||
# localhost on http and https, `tls internal`, `/` -> Vite.
|
# the production sites: localhost on http and https, `tls
|
||||||
|
# internal`, `/` -> Vite.
|
||||||
- CADDY_SITE=dev
|
- CADDY_SITE=dev
|
||||||
python:
|
python:
|
||||||
# Same command as the Dockerfile's CMD plus --reload, paired with the
|
# Same command as the Dockerfile's CMD plus --reload, paired with the
|
||||||
@@ -91,17 +79,12 @@ services:
|
|||||||
- GQL_PLAYGROUND=true
|
- GQL_PLAYGROUND=true
|
||||||
- GQL_INTROSPECTION=true
|
- GQL_INTROSPECTION=true
|
||||||
- MSGRAPH_REDIRECT_URI=https://localhost/jobs/api/email/callback
|
- MSGRAPH_REDIRECT_URI=https://localhost/jobs/api/email/callback
|
||||||
certbot:
|
cloudflared:
|
||||||
# Profiles are opt-in: a service with a profile is only started when
|
# Profiles are opt-in: a service with a profile is only started when
|
||||||
# that profile is explicitly requested. Nothing ever requests
|
# that profile is explicitly requested. Nothing ever requests
|
||||||
# "disabled", so this is the idiomatic way to switch a service off in an
|
# "disabled", so this is the idiomatic way to switch a service off in
|
||||||
# override file. Dev gets TLS from nginx's self-signed cert instead, and
|
# an override file. A dev stack must never join the production tunnel:
|
||||||
# Let's Encrypt could not validate localhost anyway.
|
# Cloudflare would load-balance real visitors onto this machine's
|
||||||
profiles:
|
# seeded database.
|
||||||
- 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.
|
|
||||||
profiles:
|
profiles:
|
||||||
- disabled
|
- disabled
|
||||||
|
|||||||
+90
-174
@@ -27,24 +27,25 @@
|
|||||||
# inline defaults.
|
# inline defaults.
|
||||||
#
|
#
|
||||||
# NAMING CONVENTION / WHY container_name IS SET FROM env
|
# NAMING CONVENTION / WHY container_name IS SET FROM env
|
||||||
# Service discovery is by container name on app-network. nginx builds its
|
# Service discovery is by container name on app-network. Caddy builds its
|
||||||
# upstreams from the same ${*_HOST} variables (nginx/entrypoint.sh), so
|
# upstreams from the same ${*_HOST} variables (the caddy service's
|
||||||
# naming the containers from .env keeps the proxy and the containers in sync
|
# environment list), so naming the containers from .env keeps the proxy and
|
||||||
# from one source of truth. Renaming a *_HOST value renames the container AND
|
# the containers in sync from one source of truth. Renaming a *_HOST value
|
||||||
# repoints nginx at it — do not change one without the other.
|
# renames the container AND repoints Caddy at it — do not change one without
|
||||||
|
# the other.
|
||||||
#
|
#
|
||||||
# WHAT IS PUBLISHED TO THE HOST
|
# 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
|
# port. Everything else is reachable only from inside app-network, which is
|
||||||
# why the backend, db, silverbullet and python have no `ports:` — they are
|
# 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.
|
# also arrive through the `cloudflared` tunnel, which publishes nothing.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
# One flat bridge network; every service resolves every other by container
|
# 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
|
# name via docker's embedded DNS at 127.0.0.11 (Caddy resolves an upstream
|
||||||
# `resolver` there). The subnet is pinned explicitly so it cannot collide
|
# 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.
|
# with the Pi's LAN range or wander between compose versions.
|
||||||
app-network:
|
app-network:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
@@ -63,7 +64,7 @@ networks:
|
|||||||
# Named volumes below survive `docker compose down` and container rebuilds;
|
# Named volumes below survive `docker compose down` and container rebuilds;
|
||||||
# they are only destroyed by `docker compose down -v` or an explicit
|
# they are only destroyed by `docker compose down -v` or an explicit
|
||||||
# `docker volume rm`. Bind mounts (./gitea/data, ./backend/token, ./logs,
|
# `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
|
# short of deleting the directory. Anything inside a container's own
|
||||||
# filesystem is ephemeral and gone on rebuild.
|
# filesystem is ephemeral and gone on rebuild.
|
||||||
volumes:
|
volumes:
|
||||||
@@ -71,10 +72,10 @@ volumes:
|
|||||||
# Deleting this wipes posts, users, messages and every git repo's metadata.
|
# Deleting this wipes posts, users, messages and every git repo's metadata.
|
||||||
dbdata:
|
dbdata:
|
||||||
# File upload — PERSISTENT. Written by the backend at /backend/uploads,
|
# 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
|
# uploads without proxying through the Go process. Since Garage, it holds
|
||||||
# private attachments (always), the uploads from before the bucket, and any
|
# 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/ from the bucket first and only then from here.
|
||||||
uploads:
|
uploads:
|
||||||
# Garage object store — PERSISTENT, both. garage_meta is the metadata DB
|
# Garage object store — PERSISTENT, both. garage_meta is the metadata DB
|
||||||
@@ -84,8 +85,8 @@ volumes:
|
|||||||
garage_meta:
|
garage_meta:
|
||||||
garage_data:
|
garage_data:
|
||||||
# Vue build — EPHEMERAL in spirit but a named volume for handoff: the
|
# 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
|
# one-shot `vue` container writes the built SPA here and exits; Caddy mounts
|
||||||
# it at /etc/nginx/html and serves it. Repopulated on every rebuild.
|
# it at /srv/www and serves it. Repopulated on every rebuild.
|
||||||
vue_dist:
|
vue_dist:
|
||||||
# Caddy's /config: the JSON it autosaves on each config load. Nothing in it
|
# 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
|
# is needed across restarts (the Caddyfile is the source); named only so
|
||||||
@@ -109,103 +110,17 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
|
|
||||||
# The only public entrypoint. Terminates TLS, serves the SPA, reverse-proxies
|
# The only public entrypoint: Caddy (caddy/Caddyfile). Terminates TLS,
|
||||||
# everything else. Its config is chosen at container start — see
|
# serves the SPA, reverse-proxies everything else, and obtains and renews
|
||||||
# nginx/entrypoint.sh for the DEV_MODE / cert-present / bootstrap decision.
|
# 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;
|
||||||
# START ORDERING: these `depends_on` entries are the plain list form, which
|
# nginx/ and certbot/ stay in the repo until that has settled, as the
|
||||||
# only waits for each container to be *created and started*, NOT for it to be
|
# rollback.
|
||||||
# ready or healthy. That is deliberate — nginx's `resolver 127.0.0.11` means
|
|
||||||
# upstreams are resolved per-request, so a late-starting backend produces a
|
|
||||||
# temporary 502 rather than a failed nginx boot. The one ordering nginx
|
|
||||||
# genuinely cares about (the Vue build finishing) is handled by the polling
|
|
||||||
# loop in its entrypoint, because depends_on cannot express "wait for a
|
|
||||||
# one-shot container to exit successfully" here.
|
|
||||||
nginx:
|
|
||||||
build:
|
|
||||||
context: ./nginx
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
container_name: nginx
|
|
||||||
env_file: ./.env
|
|
||||||
restart: always
|
|
||||||
depends_on:
|
|
||||||
- vue
|
|
||||||
- backend
|
|
||||||
- icecast2
|
|
||||||
- gitea
|
|
||||||
- silverbullet
|
|
||||||
- silverbullet-public
|
|
||||||
- python
|
|
||||||
- jobs
|
|
||||||
- activity-tracker
|
|
||||||
- dozzle
|
|
||||||
networks:
|
|
||||||
app-network:
|
|
||||||
# The site's public names, resolving to this container for everything
|
|
||||||
# on app-network. They exist for cloudflared: its tunnel origin is
|
|
||||||
# https://www.DOMAIN, which lands here over the bridge with a name the
|
|
||||||
# Let's Encrypt certificate actually covers, so the tunnel verifies
|
|
||||||
# TLS with no extra dashboard settings (`https://nginx` would fail the
|
|
||||||
# name check). Any other container that calls the public site now
|
|
||||||
# reaches nginx directly instead of hairpinning through the internet.
|
|
||||||
aliases:
|
|
||||||
- ${DOMAIN}
|
|
||||||
- www.${DOMAIN}
|
|
||||||
# Fixed for cloudflared's extra_hosts (see there): an alias only
|
|
||||||
# exists while nginx is running, and this address is pinned to the
|
|
||||||
# same names for when it is not. Top of the /16 beside cloudflared's,
|
|
||||||
# away from docker's dynamic allocations.
|
|
||||||
ipv4_address: 172.28.255.251
|
|
||||||
ports:
|
|
||||||
- 80:80
|
|
||||||
- 443:443
|
|
||||||
volumes:
|
|
||||||
# Shared with certbot: the cert store nginx reads and certbot writes.
|
|
||||||
# PERSISTENT, and private key material — gitignored, never commit.
|
|
||||||
- ./certbot/conf:/etc/letsencrypt
|
|
||||||
# Shared with certbot: the ACME HTTP-01 challenge webroot. certbot drops
|
|
||||||
# tokens in, nginx serves them on port 80.
|
|
||||||
- ./certbot/www:/var/www/certbot
|
|
||||||
- uploads:/uploads
|
|
||||||
# The SPA written by the one-shot `vue` container.
|
|
||||||
- vue_dist:/etc/nginx/html
|
|
||||||
# The JSON request-body log (nginx/payload_log.conf), kept on the host so
|
|
||||||
# it survives rebuilds and the `traffic` container can tail it. Grows
|
|
||||||
# without bound unless rotated — see DEPLOYMENT.md.
|
|
||||||
- ./logs/nginx:/var/log/nginx/payloads
|
|
||||||
# restart: always only acts when nginx's master exits. On 2026-10-19 the
|
|
||||||
# worker stalled while the master lived, and the site was down 4.6 hours
|
|
||||||
# with the container "Up". /nginx-health is answered by a worker, so a
|
|
||||||
# stall shows here; Docker only marks it unhealthy, and the `autoheal`
|
|
||||||
# label is what gets it restarted (see the autoheal service). Plain HTTP
|
|
||||||
# on :80 so it also passes in the first-boot setup config, which has no
|
|
||||||
# :443; the workers that serve :80 are the ones serving TLS.
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "curl", "-fsS", "--max-time", "5", "-o", "/dev/null", "http://127.0.0.1/nginx-health"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
start_period: 30s
|
|
||||||
labels:
|
|
||||||
- autoheal=true
|
|
||||||
|
|
||||||
# The replacement edge (caddy/Caddyfile), RUNNING BESIDE nginx until the
|
|
||||||
# cutover. While it does:
|
|
||||||
# - it is reachable only from this host, on 127.0.0.1:8880 (http) and
|
|
||||||
# 127.0.0.1:8443 (https), so the public site is still nginx;
|
|
||||||
# - it holds no network aliases and a fixed address of its own, so nothing
|
|
||||||
# on app-network (cloudflared included) is sent to it;
|
|
||||||
# - it obtains its certificates over DNS-01 into ./caddy/data, which needs
|
|
||||||
# no inbound port, so they are ready before it takes over;
|
|
||||||
# - autoheal ignores it.
|
|
||||||
# Compare the two with caddy/edge_test.sh (its header has the commands).
|
|
||||||
# The cutover gives it nginx's ports, aliases, address and autoheal label,
|
|
||||||
# and removes nginx and certbot.
|
|
||||||
#
|
#
|
||||||
# ENVIRONMENT: an explicit list, not the whole .env, so the edge never sees
|
# 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
|
# 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
|
# must be added here, or it reaches Caddy empty. The ${X:-default} forms
|
||||||
# are the defaults nginx/entrypoint.sh gave the optional services; they live
|
# are the defaults nginx's entrypoint gave the optional services; they live
|
||||||
# here because Caddy's own {$X:default} keeps a variable that is set but
|
# here because Caddy's own {$X:default} keeps a variable that is set but
|
||||||
# empty, which is how a blank line in .env arrives.
|
# empty, which is how a blank line in .env arrives.
|
||||||
#
|
#
|
||||||
@@ -240,66 +155,67 @@ services:
|
|||||||
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
|
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
|
||||||
networks:
|
networks:
|
||||||
app-network:
|
app-network:
|
||||||
# Beside nginx's .251 and cloudflared's .250. Becomes .251 at the
|
# The site's public names, resolving to this container for everything
|
||||||
# cutover.
|
# on app-network. They exist for cloudflared: its tunnel origin is
|
||||||
ipv4_address: 172.28.255.252
|
# https://www.DOMAIN, which lands here over the bridge with a name the
|
||||||
|
# Let's Encrypt certificate actually covers, so the tunnel verifies
|
||||||
|
# TLS with no extra dashboard settings (`https://caddy` would fail the
|
||||||
|
# name check). Any other container that calls the public site now
|
||||||
|
# reaches Caddy directly instead of hairpinning through the internet.
|
||||||
|
aliases:
|
||||||
|
- ${DOMAIN}
|
||||||
|
- www.${DOMAIN}
|
||||||
|
# Fixed for cloudflared's extra_hosts (see there): an alias only
|
||||||
|
# exists while Caddy is running, and this address is pinned to the
|
||||||
|
# same names for when it is not. Top of the /16 beside cloudflared's,
|
||||||
|
# away from docker's dynamic allocations.
|
||||||
|
ipv4_address: 172.28.255.251
|
||||||
ports:
|
ports:
|
||||||
- 127.0.0.1:8880:80
|
- 80:80
|
||||||
- 127.0.0.1:8443:443
|
- 443:443
|
||||||
volumes:
|
volumes:
|
||||||
# The certificates, their keys and the ACME account. PERSISTENT and
|
# The certificates, their keys and the ACME account. PERSISTENT and
|
||||||
# private key material: gitignored, never commit. Losing it only costs
|
# private key material: gitignored, never commit. Losing it only costs
|
||||||
# a re-issue on the next start (about a minute over DNS-01).
|
# a re-issue on the next start (seconds over DNS-01), during which the
|
||||||
|
# tunnel, which verifies the certificate, serves 502s.
|
||||||
- ./caddy/data:/data
|
- ./caddy/data:/data
|
||||||
- caddy_config:/config
|
- caddy_config:/config
|
||||||
- uploads:/srv/uploads:ro
|
- uploads:/srv/uploads:ro
|
||||||
# The SPA written by the one-shot `vue` container.
|
# The SPA written by the one-shot `vue` container.
|
||||||
- vue_dist:/srv/www:ro
|
- vue_dist:/srv/www:ro
|
||||||
# The JSON request-body log, tailed by `traffic` after the cutover.
|
# The JSON request-body log, kept on the host so it survives rebuilds
|
||||||
|
# and the `traffic` container can tail it. Caddy rotates it itself
|
||||||
|
# (50 MiB, five files kept).
|
||||||
- ./logs/caddy:/var/log/caddy
|
- ./logs/caddy:/var/log/caddy
|
||||||
# Answered by Caddy itself (http://127.0.0.1 in the Caddyfile). The image
|
# restart: always only acts when the process exits. On 2026-10-19 nginx's
|
||||||
# has busybox wget, not curl.
|
# 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:
|
healthcheck:
|
||||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/caddy-health"]
|
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/caddy-health"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 10s
|
timeout: 10s
|
||||||
retries: 3
|
retries: 3
|
||||||
start_period: 30s
|
start_period: 30s
|
||||||
|
labels:
|
||||||
# Obtains the cert once, then renews every 12h forever. Disabled in dev via
|
- autoheal=true
|
||||||
# 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,
|
# 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
|
# 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
|
# forwards can be closed. The tunnel is "remotely managed": its public
|
||||||
# hostnames and origin settings live in the Cloudflare dashboard, and this
|
# hostnames and origin settings live in the Cloudflare dashboard, and this
|
||||||
# container only needs the token. The routing set up there (DEPLOYMENT.md,
|
# container only needs the token. The routing set up there (DEPLOYMENT.md,
|
||||||
# "Cloudflare Tunnel") is https://www.DOMAIN, which nginx's network aliases
|
# "Cloudflare Tunnel") is https://www.DOMAIN, which Caddy's network aliases
|
||||||
# resolve to nginx itself, so the certificate verifies; nginx's config,
|
# resolve to Caddy itself, so the certificate verifies; Caddy's config,
|
||||||
# redirects and security headers apply to tunnel traffic exactly as to
|
# redirects and security headers apply to tunnel traffic exactly as to
|
||||||
# direct traffic, and both paths work side by side.
|
# direct traffic, and both paths work side by side.
|
||||||
#
|
#
|
||||||
# Fixed address so nginx can trust the CF-Connecting-IP header from this
|
# Fixed address so Caddy can trust the CF-Connecting-IP header from this
|
||||||
# container and no other (set_real_ip_from in nginx.conf.template). It sits
|
# 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
|
# at the top of the /16 because docker hands out dynamic addresses from the
|
||||||
# bottom; the two must change together.
|
# bottom; the two must change together.
|
||||||
#
|
#
|
||||||
@@ -313,12 +229,12 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
|
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
|
||||||
depends_on:
|
depends_on:
|
||||||
- nginx
|
- caddy
|
||||||
# Pins the tunnel origin's names to nginx's fixed address. nginx's aliases
|
# 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
|
# 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
|
# 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
|
# 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.
|
# now a refused connection, which cloudflared reports as a plain 502.
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "${DOMAIN}:172.28.255.251"
|
- "${DOMAIN}:172.28.255.251"
|
||||||
@@ -360,7 +276,7 @@ services:
|
|||||||
# read-only into silverbullet-public (the /notes/ site).
|
# read-only into silverbullet-public (the /notes/ site).
|
||||||
- ${OBSIDIAN_DIR}:/backend/notes
|
- ${OBSIDIAN_DIR}:/backend/notes
|
||||||
- ./logs:/backend/logs
|
- ./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
|
- uploads:/backend/uploads
|
||||||
# Shared with icecast2, which plays these as the radio fallback playlist;
|
# Shared with icecast2, which plays these as the radio fallback playlist;
|
||||||
# the backend reads them to report what is queued.
|
# the backend reads them to report what is queued.
|
||||||
@@ -418,12 +334,12 @@ services:
|
|||||||
# listeners connect to, proxied at /radio/) and liquidsoap (the source that
|
# listeners connect to, proxied at /radio/) and liquidsoap (the source that
|
||||||
# feeds it). See icecast2/entrypoint.sh.
|
# 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
|
# 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
|
# (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
|
# name now that the public domain resolves to Cloudflare, with the icecast
|
||||||
# source password and pre-empts the fallback playlist. It is NOT proxied
|
# 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
|
# Note the host:container mapping uses the same variable on both sides, so
|
||||||
# the published port always matches what liquidsoap actually binds.
|
# the published port always matches what liquidsoap actually binds.
|
||||||
icecast2:
|
icecast2:
|
||||||
@@ -442,7 +358,7 @@ services:
|
|||||||
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
||||||
|
|
||||||
# Browser-based editor for the vault, so notes are editable from a phone.
|
# 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,
|
# a SECOND, read-only SilverBullet over the same folder (silverbullet-public,
|
||||||
# below).
|
# below).
|
||||||
#
|
#
|
||||||
@@ -460,7 +376,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
SB_PORT: "${SILVERBULLET_PORT:-3000}"
|
SB_PORT: "${SILVERBULLET_PORT:-3000}"
|
||||||
# The app builds its service-worker scope and asset URLs from this, which
|
# 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
|
SB_URL_PREFIX: /sb
|
||||||
# Only .obsidian: it is editor config and plugin JS, not notes.
|
# Only .obsidian: it is editor config and plugin JS, not notes.
|
||||||
#
|
#
|
||||||
@@ -495,14 +411,14 @@ services:
|
|||||||
# URL /notes/private/x (server-rendered with the
|
# URL /notes/private/x (server-rendered with the
|
||||||
# note's content), nor /.fs/.git/ — SilverBullet
|
# note's content), nor /.fs/.git/ — SilverBullet
|
||||||
# only applies it to listing (checked in 2.11.0).
|
# 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
|
# nested dot-folder under /notes/; this is what
|
||||||
# actually closes those holes. Keep its folder list
|
# actually closes those holes. Keep its folder list
|
||||||
# in step with the one below.
|
# in step with the one below.
|
||||||
# 3. SB_REVISIONS the default ("unmanaged") serves history from the
|
# 3. SB_REVISIONS the default ("unmanaged") serves history from the
|
||||||
# vault's own .git, i.e. every version of every file
|
# vault's own .git, i.e. every version of every file
|
||||||
# including private/ and deleted ones. Disabled here,
|
# 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
|
# 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
|
# /.proxy endpoint (otherwise an open fetch proxy). The :ro mount is a second
|
||||||
@@ -519,13 +435,13 @@ services:
|
|||||||
- app-network
|
- app-network
|
||||||
environment:
|
environment:
|
||||||
SB_PORT: "${SILVERBULLET_PUBLIC_PORT:-3000}"
|
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_URL_PREFIX: /notes
|
||||||
SB_READ_ONLY: "true"
|
SB_READ_ONLY: "true"
|
||||||
SB_REVISIONS: disabled
|
SB_REVISIONS: disabled
|
||||||
# Newline separated (commas are silently ignored). Gitignore semantics,
|
# Newline separated (commas are silently ignored). Gitignore semantics,
|
||||||
# so these match at any depth. Must match the folder list in the
|
# 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.
|
# hidden from the list but still publicly fetchable.
|
||||||
SB_SPACE_IGNORE: |
|
SB_SPACE_IGNORE: |
|
||||||
private/
|
private/
|
||||||
@@ -540,7 +456,7 @@ services:
|
|||||||
# writes, and pulls what Obsidian pushes from elsewhere.
|
# writes, and pulls what Obsidian pushes from elsewhere.
|
||||||
#
|
#
|
||||||
# WHY A SEPARATE CONTAINER and not SilverBullet's own shell backend: enabling
|
# 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
|
# 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.
|
# gate is the only thing protecting it, so the blast radius stays here.
|
||||||
silverbullet-git:
|
silverbullet-git:
|
||||||
@@ -549,8 +465,8 @@ services:
|
|||||||
restart: always
|
restart: always
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
# The vault's remotes are ssh://git@DOMAIN:2222/..., but nginx's network
|
# The vault's remotes are ssh://git@DOMAIN:2222/..., but Caddy's network
|
||||||
# aliases make DOMAIN resolve to nginx on app-network, which has no :2222,
|
# 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
|
# 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
|
# this sends DOMAIN back to the host, where gitea publishes 2222. The name
|
||||||
# is unchanged, so known_hosts still matches.
|
# is unchanged, so known_hosts still matches.
|
||||||
@@ -576,7 +492,7 @@ services:
|
|||||||
# ssh will not run for a uid with no passwd entry; see the file's comment.
|
# ssh will not run for a uid with no passwd entry; see the file's comment.
|
||||||
- ./silverbullet/passwd:/etc/passwd:ro
|
- ./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
|
# 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
|
# OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own
|
||||||
# routes are written relative to /.
|
# routes are written relative to /.
|
||||||
@@ -584,7 +500,7 @@ services:
|
|||||||
# than `env_file: ./.env` — it only gets the variables it needs and never
|
# than `env_file: ./.env` — it only gets the variables it needs and never
|
||||||
# sees the database password, Spotify secrets, or the other API keys.
|
# 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
|
# 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.
|
# makes its Claude call here.
|
||||||
python:
|
python:
|
||||||
build:
|
build:
|
||||||
@@ -616,10 +532,10 @@ services:
|
|||||||
# database role of its own. A variable the tracker reads must be added to
|
# database role of its own. A variable the tracker reads must be added to
|
||||||
# the list below as well as .env.example.
|
# 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
|
# bearer-token capture API and the userscript), and the tracker checks
|
||||||
# again itself: AUTH_VALIDATE_URL is the backend's validate-admin route
|
# 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.
|
# cookies on each admin request.
|
||||||
#
|
#
|
||||||
# ./jobs-data holds the Microsoft Graph session and the capture token. The
|
# ./jobs-data holds the Microsoft Graph session and the capture token. The
|
||||||
@@ -764,7 +680,7 @@ services:
|
|||||||
# Two kinds of auth. Collectors send per-device bearer keys, made on the
|
# 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's /tracker/setup page or with `docker exec activity-tracker
|
||||||
# tracker apikey create`. The dashboard and setup pages have no login of
|
# 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
|
# /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
|
# AUTH_VALIDATE_URL (the backend's validate-admin) with the visitor's
|
||||||
# cookies and sends anyone else to /admin/login.
|
# cookies and sends anyone else to /admin/login.
|
||||||
@@ -782,9 +698,9 @@ services:
|
|||||||
- TRACKER_TZ=${TRACKER_TZ:-}
|
- TRACKER_TZ=${TRACKER_TZ:-}
|
||||||
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
|
- 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,
|
# 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
|
# 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.
|
# backlog on restart, which stays in the file on the host.
|
||||||
traffic:
|
traffic:
|
||||||
@@ -794,10 +710,10 @@ services:
|
|||||||
command: ["tail", "-n0", "-F", "/logs/payloads.log"]
|
command: ["tail", "-n0", "-F", "/logs/payloads.log"]
|
||||||
network_mode: none
|
network_mode: none
|
||||||
volumes:
|
volumes:
|
||||||
- ./logs/nginx:/logs:ro
|
- ./logs/caddy:/logs:ro
|
||||||
|
|
||||||
# Dozzle: a live, searchable web view of every container's logs, served at
|
# 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.
|
# `traffic` container is the one to watch for incoming request bodies.
|
||||||
#
|
#
|
||||||
# The Docker socket is mounted :ro, but that only stops the file being
|
# The Docker socket is mounted :ro, but that only stops the file being
|
||||||
@@ -818,7 +734,7 @@ services:
|
|||||||
|
|
||||||
# Restarts any container labelled autoheal=true once Docker marks it
|
# Restarts any container labelled autoheal=true once Docker marks it
|
||||||
# unhealthy, which Docker itself never does (restart policies only see the
|
# 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.
|
# 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
|
# It needs the Docker socket read-write to restart things, which is root on
|
||||||
@@ -844,16 +760,16 @@ services:
|
|||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
|
||||||
# S3-compatible object store holding public uploads (the `uploads` bucket).
|
# 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
|
# serves /uploads/ from it anonymously on :3902, falling back to the
|
||||||
# `uploads` volume; garage-webui manages it via :3903. Nothing is published
|
# `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
|
# to the host. Config is garage/garage.toml (no secrets in it); the two
|
||||||
# secrets come from .env through the explicit list below.
|
# secrets come from .env through the explicit list below.
|
||||||
#
|
#
|
||||||
# Nothing depends on this container being up. nginx is deliberately NOT
|
# Nothing depends on this container being up. Caddy is deliberately NOT
|
||||||
# given it in depends_on: its upstream is a variable, so a missing or
|
# given it in depends_on: it resolves garage when it dials it, so a missing
|
||||||
# crash-looping garage only makes bucket-only files 404 (everything on the
|
# or crash-looping garage only makes bucket-only files 404 (everything on
|
||||||
# volume is still served), never nginx's boot; and the backend falls back
|
# the volume is still served), never Caddy's start; and the backend falls back
|
||||||
# to the volume when a write fails.
|
# to the volume when a write fails.
|
||||||
#
|
#
|
||||||
# FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access).
|
# FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access).
|
||||||
@@ -879,9 +795,9 @@ services:
|
|||||||
retries: 3
|
retries: 3
|
||||||
start_period: 10s
|
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
|
# 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
|
# 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
|
# its port. It reads the s3/web settings from garage.toml; the token comes
|
||||||
# from .env instead, since the file has none.
|
# from .env instead, since the file has none.
|
||||||
|
|||||||
+1
-1
@@ -25,7 +25,7 @@
|
|||||||
# with the same credentials and the backend needs no change.
|
# with the same credentials and the backend needs no change.
|
||||||
# 4. Grants that key read+write on the bucket. garage-webui also browses
|
# 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.
|
# 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.
|
# /uploads/ from, anonymously.
|
||||||
#
|
#
|
||||||
# ENV / .env
|
# ENV / .env
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@
|
|||||||
# garage/bootstrap.sh imports); garage-webui browses through it.
|
# garage/bootstrap.sh imports); garage-webui browses through it.
|
||||||
# 3901 RPC between Garage nodes. Only this node talks to itself.
|
# 3901 RPC between Garage nodes. Only this node talks to itself.
|
||||||
# 3902 Website endpoint. Serves a bucket ANONYMOUSLY, choosing it from the
|
# 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
|
# sends `Host: uploads.web.garage`. Only buckets that bootstrap.sh
|
||||||
# opened with `garage bucket website --allow` are served.
|
# opened with `garage bucket website --allow` are served.
|
||||||
# 3903 Admin API, used by garage-webui and authenticated by admin_token.
|
# 3903 Admin API, used by garage-webui and authenticated by admin_token.
|
||||||
|
|||||||
+2
-2
@@ -20,8 +20,8 @@
|
|||||||
# rather than retrying, so the loop polls (forever, by design — there is no
|
# rather than retrying, so the loop polls (forever, by design — there is no
|
||||||
# sensible timeout when the answer is "wait longer") until Gitea responds.
|
# sensible timeout when the answer is "wait longer") until Gitea responds.
|
||||||
# It targets localhost:3000, the port docker-compose.yml publishes directly,
|
# It targets localhost:3000, the port docker-compose.yml publishes directly,
|
||||||
# NOT the public /gitea/ path through nginx — so the runner keeps working
|
# NOT the public /gitea/ path through Caddy — so the runner keeps working
|
||||||
# even while TLS or nginx is broken.
|
# even while TLS or Caddy is broken.
|
||||||
#
|
#
|
||||||
# THE REGISTRATION TOKEN (one-shot, and easy to get wrong)
|
# THE REGISTRATION TOKEN (one-shot, and easy to get wrong)
|
||||||
# GITEA_RUNNER_REGISTRATION_TOKEN comes from ./.env and is generated in the
|
# GITEA_RUNNER_REGISTRATION_TOKEN comes from ./.env and is generated in the
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
; Gitea generates one itself on first run and writes it into the live app.ini.
|
; Gitea generates one itself on first run and writes it into the live app.ini.
|
||||||
;
|
;
|
||||||
; SETTINGS WORTH KNOWING
|
; 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.
|
; 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
|
; 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.
|
; 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
|
; MagicDNS name, not the public domain: SSH
|
||||||
; (22 and 2222) is not forwarded by the router, so the SSH clone URL Gitea
|
; (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
|
; 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
|
; 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
|
; X-Forwarded-For, i.e. our Caddy, so Gitea logs real client IPs. Caddy
|
||||||
; only safe because nginx is the sole edge.
|
; 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.
|
; INSTALL_LOCK = true skips the first-run web installer.
|
||||||
; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up.
|
; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up.
|
||||||
; OFFLINE_MODE = true — no calls out to gravatar/CDNs.
|
; OFFLINE_MODE = true — no calls out to gravatar/CDNs.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
#
|
#
|
||||||
# WHAT IT DOES
|
# WHAT IT DOES
|
||||||
# This one container holds two cooperating daemons:
|
# 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.
|
# proxies /radio/ to it.
|
||||||
# liquidsoap - the *source*: it decides what audio to play and pushes a
|
# liquidsoap - the *source*: it decides what audio to play and pushes a
|
||||||
# single MP3 stream into icecast's mount point.
|
# single MP3 stream into icecast's mount point.
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
#
|
#
|
||||||
# THE TEMPLATING STEP
|
# THE TEMPLATING STEP
|
||||||
# Both configs are rendered by bare `envsubst` (no allow-list) because unlike
|
# 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,
|
# 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
|
# so an unrestricted envsubst is safe here. NOTE the consequence: any
|
||||||
# referenced variable that is unset silently becomes an empty string, which
|
# referenced variable that is unset silently becomes an empty string, which
|
||||||
|
|||||||
@@ -29,7 +29,7 @@
|
|||||||
#
|
#
|
||||||
# OUTPUT
|
# OUTPUT
|
||||||
# Pushes to icecast on localhost (same container) at ICECAST_MOUNT, which is
|
# 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
|
# 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.
|
# what makes the `sleep 2` startup race in the entrypoint survivable.
|
||||||
#
|
#
|
||||||
|
|||||||
+2
-2
@@ -11,7 +11,7 @@
|
|||||||
# immediately instead of sitting in a buffer — both are standard for
|
# immediately instead of sitting in a buffer — both are standard for
|
||||||
# containerised Python and the second one matters for debugging.
|
# 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
|
# are written relative to /. --root-path tells FastAPI it is nonetheless
|
||||||
# mounted under a prefix, so the OpenAPI schema and Swagger UI emit correct
|
# mounted under a prefix, so the OpenAPI schema and Swagger UI emit correct
|
||||||
# /py/... URLs. Without it, /py/docs loads but cannot call anything.
|
# /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
|
# Both have defaults here so the image runs standalone; docker compose normally
|
||||||
# supplies them.
|
# 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.
|
# it over app-network.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
FROM python:3.12-slim
|
FROM python:3.12-slim
|
||||||
|
|||||||
+15
-12
@@ -26,7 +26,7 @@ driven from a plain script.
|
|||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
Paths below are as the service sees them; from a browser prefix everything with
|
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 |
|
| 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
|
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
|
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
|
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
|
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).
|
it proxies (the Go backend sends neither).
|
||||||
|
|
||||||
Their plumbing is in two places, shared by any route added later:
|
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`.
|
in `main.py`'s docstring and bump the FastAPI `version`.
|
||||||
3. **Tests** `tests/test_<thing>.py`, copied from `test_rowing.py`: fake the
|
3. **Tests** `tests/test_<thing>.py`, copied from `test_rowing.py`: fake the
|
||||||
client with `monkeypatch.setattr(thing, "_client", ...)`.
|
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/`.
|
it already 404s everything under `/py/internal/`.
|
||||||
|
|
||||||
If third-party text goes into the prompt (a web page, an email), say in the
|
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
|
from image processor`, `failed to parse image data`) that the Go handler
|
||||||
relays to the admin; 503 if `CLAUDE_API_KEY` is unset.
|
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
|
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
|
the uvicorn command line via `ROOT_PATH`) is what keeps the generated docs and
|
||||||
OpenAPI URLs correct behind that rewrite.
|
OpenAPI URLs correct behind that rewrite.
|
||||||
|
|
||||||
The hotel routes get their own nginx location with `proxy_buffering off` and a
|
The hotel routes get their own Caddy route with `flush_interval -1` and their
|
||||||
300s read timeout, because otherwise nginx would hold the whole NDJSON stream
|
own rate limit, so each NDJSON line reaches the browser as it is written. The
|
||||||
until it finished. The app also sends `X-Accel-Buffering: no` as a belt-and-
|
app also sends `X-Accel-Buffering: no`, which Caddy ignores but an nginx-style
|
||||||
braces version of the same thing. The internal deadlines in `travelodge.py`
|
proxy would need. The internal deadlines in `travelodge.py` (200s for a search,
|
||||||
(200s for a search, 240s for a scan) exist to finish *before* that 300s cut, and
|
240s for a scan) were set to finish before nginx's old 300s cut; Caddy sets no
|
||||||
return partial results with `summary.truncated = true` instead of dying.
|
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
|
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
|
`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
@@ -1,6 +1,6 @@
|
|||||||
"""Small Python API service.
|
"""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
|
/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
|
(set via --root-path on the uvicorn command line) keeps the generated docs
|
||||||
at /py/docs working behind the proxy.
|
at /py/docs working behind the proxy.
|
||||||
@@ -14,7 +14,7 @@ Endpoints
|
|||||||
POST /hotels/search/stream same search, streamed as NDJSON
|
POST /hotels/search/stream same search, streamed as NDJSON
|
||||||
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
|
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
|
||||||
POST /internal/rowing/read read a rowing display photo with Claude
|
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
|
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
|
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")
|
@app.get("/", response_model=Greeting, summary="Service index")
|
||||||
def index() -> Greeting:
|
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.")
|
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
|
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.
|
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
|
X-Accel-Buffering: no tells an nginx-style proxy not to buffer the
|
||||||
response and the user sees nothing until the search finishes, defeating the
|
response; without it the user would see nothing until the search finished,
|
||||||
point of streaming. Cache-Control: no-cache stops any intermediary storing
|
defeating the point of streaming. Caddy, the edge now, ignores the header
|
||||||
a partial stream.
|
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(
|
return StreamingResponse(
|
||||||
(ev.model_dump_json(exclude_none=True) + "\n" for ev in events),
|
(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
|
# Internal: the routes the Go backend calls
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
def _internal_only(request: Request) -> None:
|
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
|
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
|
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,
|
directly over app-network. Two layers keep the outside world off it,
|
||||||
because either alone is one config edit away from being lost:
|
because either alone is one config edit away from being lost:
|
||||||
|
|
||||||
1. nginx answers /py/internal/ with a 404 (both templates).
|
1. Caddy answers /py/internal/ with a 404 (caddy/routes.caddy, dev and
|
||||||
2. nginx stamps X-Real-IP and X-Forwarded-For on everything it proxies
|
production alike).
|
||||||
here, and a client cannot make it omit them; the Go backend sends
|
2. Caddy stamps X-Real-IP and X-Forwarded-For on everything it proxies
|
||||||
neither. So their presence means the request came from outside.
|
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
|
404 rather than 403, so the route is indistinguishable from one that does
|
||||||
not exist.
|
not exist.
|
||||||
@@ -732,7 +737,7 @@ class RowingReadRequest(BaseModel):
|
|||||||
response_model=rowing.RowingReading,
|
response_model=rowing.RowingReading,
|
||||||
summary="Read time and distance off a rowing machine display",
|
summary="Read time and distance off a rowing machine display",
|
||||||
description=(
|
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 "
|
"Sends the image to Claude and returns the three numbers it read. No plausibility checking "
|
||||||
"happens here - the caller owns the sanity bounds."
|
"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
|
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.
|
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
|
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
|
502 detail is one of rowing.read_display's fixed messages, which the Go
|
||||||
handler passes on to the admin verbatim.
|
handler passes on to the admin verbatim.
|
||||||
|
|||||||
@@ -55,7 +55,9 @@ Time budgets
|
|||||||
Every network path takes an optional `deadline` (a time.monotonic() value).
|
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
|
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
|
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
|
import logging
|
||||||
@@ -102,8 +104,9 @@ ORIGINS = {
|
|||||||
# Rough Greater London bounding box for custom "lat,lon" 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
|
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
|
# Wall-clock budget for one run_search call. Set when nginx cut the connection
|
||||||
# 300s, so stop pricing transport well before that and return what we have.
|
# 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
|
SEARCH_DEADLINE_S = 200
|
||||||
|
|
||||||
# A date-range scan fetches one Travelodge search per candidate night, then
|
# A date-range scan fetches one Travelodge search per candidate night, then
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
The Vue frontend splits the response on newlines and JSON-parses each line, so
|
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
|
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
|
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
|
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
|
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():
|
def test_ndjson_headers_defeat_proxy_buffering():
|
||||||
response = main._ndjson(iter([]))
|
response = main._ndjson(iter([]))
|
||||||
assert response.media_type == "application/x-ndjson"
|
assert response.media_type == "application/x-ndjson"
|
||||||
# Without X-Accel-Buffering nginx holds the whole response and the stream
|
# Without X-Accel-Buffering an nginx-style proxy holds the whole response
|
||||||
# is pointless.
|
# and the stream is pointless. (Caddy streams it regardless.)
|
||||||
assert response.headers["x-accel-buffering"] == "no"
|
assert response.headers["x-accel-buffering"] == "no"
|
||||||
assert response.headers["cache-control"] == "no-cache"
|
assert response.headers["cache-control"] == "no-cache"
|
||||||
|
|
||||||
|
|||||||
@@ -125,8 +125,8 @@ def test_route_returns_reading(fake_claude, http):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"])
|
@pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"])
|
||||||
def test_route_refuses_requests_proxied_by_nginx(fake_claude, http, header):
|
def test_route_refuses_requests_proxied_by_the_edge(fake_claude, http, header):
|
||||||
"""nginx sets these on everything it forwards; the Go backend sets neither."""
|
"""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"})
|
res = http.post("/internal/rowing/read", json=BODY, headers={header: "203.0.113.9"})
|
||||||
assert res.status_code == 404
|
assert res.status_code == 404
|
||||||
assert fake_claude.calls == []
|
assert fake_claude.calls == []
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
# SilverBullet writes plain markdown straight into the space folder and has no
|
# 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
|
# 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:
|
# 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.
|
# backend would hand anyone past that gate command execution inside the container.
|
||||||
#
|
#
|
||||||
# ON-DEMAND SYNC
|
# ON-DEMAND SYNC
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
# Vue frontend image — builds the SPA.
|
# Vue frontend image — builds the SPA.
|
||||||
#
|
#
|
||||||
# THIS IS A BUILD CONTAINER, NOT A SERVER. In production the container runs
|
# 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
|
# 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
|
# success case, not a failure. The dev override replaces the CMD with the Vite
|
||||||
# dev server, and then it does stay running.
|
# dev server, and then it does stay running.
|
||||||
|
|||||||
+13
-13
@@ -14,7 +14,7 @@ npm install
|
|||||||
npm run dev
|
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
|
is an environment variable, read in `vite.config.js` from the shell or from
|
||||||
`vue/.env.local`:
|
`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 |
|
| `/api` | `VITE_PROXY_API` | `http://localhost:8080` | Go backend |
|
||||||
| `/gitea` | `VITE_PROXY_GITEA` | `http://localhost:3000` | Gitea |
|
| `/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 |
|
| `/radio` | `VITE_PROXY_RADIO` | `http://localhost:8000` | Icecast2 |
|
||||||
|
|
||||||
**The defaults are not "where the compose stack is".** The stack publishes only
|
**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
|
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
|
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
|
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
|
can be right at a time — normally `/py`, with the radio simply reading as
|
||||||
offline.
|
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`
|
`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
|
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.
|
has to be a bare uvicorn.
|
||||||
|
|
||||||
## Structure
|
## 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` |
|
| `/` | 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 |
|
| `/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 |
|
| `/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 | |
|
| `/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 |
|
| `/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 |
|
| `/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) |
|
| `: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
|
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
|
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 Vite proxy in dev).
|
||||||
|
|
||||||
The backend's REST routes go through `src/api.js`, the same idea for plain JSON:
|
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
|
(`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
|
start-up (`ensureStpPage` in `backend/services/database.go`), so it can be
|
||||||
renamed, hidden or deleted like any other.
|
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
|
(`validateSlug` in `backend/graph/page_helpers.go`) — add to that list when
|
||||||
adding a route.
|
adding a route.
|
||||||
- **Backgrounds.** Each page key can have its own background (`Background` in
|
- **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`,
|
- **Dev** (`npm run dev`): Vite serves the SPA and proxies `/api`, `/gitea`,
|
||||||
`/radio` and `/py` to the `VITE_PROXY_*` targets (see Development above and
|
`/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.
|
does in production.
|
||||||
- **Production** (`npm run build`): `dist/` is built into the nginx container
|
- **Production** (`npm run build`): `dist/` is written into the `vue_dist`
|
||||||
and served as static files, with nginx doing the same reverse-proxying.
|
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
|
`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.
|
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
|
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
|
## Recommended IDE Setup
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
*
|
*
|
||||||
* Auth rides along in HTTP-only cookies set by the backend, so no token handling
|
* 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
|
* 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";
|
import axios from "axios";
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ const router = createRouter({
|
|||||||
},
|
},
|
||||||
// A signed-in user's own page: the gated services they have
|
// A signed-in user's own page: the gated services they have
|
||||||
// been granted. /no-access is the same page with a notice,
|
// 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",
|
path: "account",
|
||||||
name: "account",
|
name: "account",
|
||||||
@@ -105,7 +105,7 @@ const router = createRouter({
|
|||||||
component: () => import("@/views/CV/CV.vue"),
|
component: () => import("@/views/CV/CV.vue"),
|
||||||
},
|
},
|
||||||
// /cv/jobs and /cv/leads moved to the job tracker app at
|
// /cv/jobs and /cv/leads moved to the job tracker app at
|
||||||
// /jobs/; nginx redirects the old paths.
|
// /jobs/; Caddy redirects the old paths.
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import { useAuthStore } from "@/stores/auth";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
|
* 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
|
* proxy (dev) both serve /api/ws from the same origin as the page, and the
|
||||||
* auth cookies only travel if the origin matches.
|
* auth cookies only travel if the origin matches.
|
||||||
*/
|
*/
|
||||||
@@ -171,7 +171,7 @@ export const useMessagesStore = defineStore("messages", () => {
|
|||||||
* surface via `lastError`.
|
* surface via `lastError`.
|
||||||
*
|
*
|
||||||
* `private` goes to both: the upload is stored under /uploads/private/,
|
* `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.
|
* private. The two must agree.
|
||||||
*/
|
*/
|
||||||
async function uploadAndSendFile(file, isPrivate = false) {
|
async function uploadAndSendFile(file, isPrivate = false) {
|
||||||
|
|||||||
@@ -4,13 +4,13 @@
|
|||||||
* page for a signed-in account that is not an admin, listing the gated
|
* 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.
|
* 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
|
* 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
|
* `?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".
|
* open instead" is the useful answer to "you can't open that".
|
||||||
*
|
*
|
||||||
* The links are plain <a href>, not RouterLinks: every service lives in
|
* 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 { ref, computed, onMounted } from "vue";
|
||||||
import { useRoute, useRouter } from "vue-router";
|
import { useRoute, useRouter } from "vue-router";
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ async function handleLogout() {
|
|||||||
{{ section.label }}
|
{{ section.label }}
|
||||||
</button>
|
</button>
|
||||||
<!-- Logs and incoming request bodies live in Dozzle, outside the
|
<!-- 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
|
<a
|
||||||
class="admin-nav-link no-underline"
|
class="admin-nav-link no-underline"
|
||||||
href="/dozzle/"
|
href="/dozzle/"
|
||||||
@@ -108,7 +108,7 @@ async function handleLogout() {
|
|||||||
Logs ↗
|
Logs ↗
|
||||||
</a>
|
</a>
|
||||||
<!-- The receipt printer's page is served from stppi, which reaches
|
<!-- 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. -->
|
Tailscale behind the `receipt` permission gate. -->
|
||||||
<a
|
<a
|
||||||
class="admin-nav-link no-underline"
|
class="admin-nav-link no-underline"
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
* (a non-admin would only bounce off /admin's guard back to here).
|
* (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
|
* 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
|
* proxied containers (/notes/, /sb/, /receipt/). The latter means the
|
||||||
* destination is frequently NOT a Vue route, so see goTo() below.
|
* 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.
|
// 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
|
// 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
|
// 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
|
// 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
|
// 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
|
// `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.
|
// site-relative path — a leading "//" or a scheme would be an open redirect.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
* site's 404 — with, for an admin, a form to create a page right here.
|
* 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
|
* 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
|
* An adminOnly page answers null to anyone else, so to them it is simply a
|
||||||
* 404.
|
* 404.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
* in as literal values, read from the live page so a re-themed layout
|
* in as literal values, read from the live page so a re-themed layout
|
||||||
* (CVLayout re-points the tokens) would carry through.
|
* (CVLayout re-points the tokens) would carry through.
|
||||||
* - Load our fonts. Without allow-same-origin its origin is opaque ("null"),
|
* - 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
|
* 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
|
* fetches the two files (28 KB) once, same-origin, and inlines them as
|
||||||
* data: URLs.
|
* data: URLs.
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ export async function runStream(url, body, { signal, onEvent }) {
|
|||||||
try {
|
try {
|
||||||
payload = await res.json();
|
payload = await res.json();
|
||||||
} catch {
|
} 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));
|
throw new Error(describeError(res.status, payload));
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-8
@@ -7,11 +7,11 @@ import vueDevTools from "vite-plugin-vue-devtools";
|
|||||||
|
|
||||||
// Dev-server proxy targets (frontend-only `npm run dev`).
|
// 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
|
// 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:
|
// 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
|
// the liquidsoap harbor port
|
||||||
// NOT published: backend (8080), python (8000),
|
// NOT published: backend (8080), python (8000),
|
||||||
// icecast (8000), db, silverbullet
|
// icecast (8000), db, silverbullet
|
||||||
@@ -37,9 +37,9 @@ import vueDevTools from "vite-plugin-vue-devtools";
|
|||||||
// VITE_PROXY_RADIO Icecast default http://localhost:8000
|
// VITE_PROXY_RADIO Icecast default http://localhost:8000
|
||||||
//
|
//
|
||||||
// To borrow a running compose stack instead of running services on the host,
|
// 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):
|
// 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 nginx
|
// those three are forwarded with their path intact, which is what Caddy
|
||||||
// expects. VITE_PROXY_PY cannot be pointed at nginx — see the rewrite below.
|
// expects. VITE_PROXY_PY cannot be pointed at Caddy — see the rewrite below.
|
||||||
const DEFAULT_PROXY = {
|
const DEFAULT_PROXY = {
|
||||||
VITE_PROXY_API: "http://localhost:8080",
|
VITE_PROXY_API: "http://localhost:8080",
|
||||||
VITE_PROXY_GITEA: "http://localhost:3000",
|
VITE_PROXY_GITEA: "http://localhost:3000",
|
||||||
@@ -76,9 +76,9 @@ export default defineConfig(({ mode }) => {
|
|||||||
"/api": env.VITE_PROXY_API,
|
"/api": env.VITE_PROXY_API,
|
||||||
"/gitea": env.VITE_PROXY_GITEA,
|
"/gitea": env.VITE_PROXY_GITEA,
|
||||||
"/radio": env.VITE_PROXY_RADIO,
|
"/radio": env.VITE_PROXY_RADIO,
|
||||||
// Python API: nginx strips the /py prefix in production, so do the
|
// Python API: Caddy strips the /py prefix in production, so do the
|
||||||
// same here. That makes the target a bare uvicorn — pointed at nginx
|
// same here. That makes the target a bare uvicorn — pointed at Caddy
|
||||||
// the request would arrive without the prefix nginx routes on.
|
// the request would arrive without the prefix Caddy routes on.
|
||||||
"/py": {
|
"/py": {
|
||||||
target: env.VITE_PROXY_PY,
|
target: env.VITE_PROXY_PY,
|
||||||
rewrite: (path) => path.replace(/^\/py/, ""),
|
rewrite: (path) => path.replace(/^\/py/, ""),
|
||||||
|
|||||||
Reference in New Issue
Block a user