Trim comments to the non-obvious why
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s

Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 20:49:03 +00:00
co-authored by Claude Opus 5.5
parent effddd2794
commit 4530cb8dc4
222 changed files with 1173 additions and 5423 deletions
+36 -216
View File
@@ -1,107 +1,32 @@
# =============================================================================
# Caddyfile — the public edge: TLS, the SPA, and the reverse proxy in front of
# every other service. Replaced nginx and certbot (now .deprecated/) on
# 2026-11-17.
#
# FILES (all baked into the image by caddy/Dockerfile)
# Caddyfile this file: global options, the snippets every site
# uses, the healthcheck site, and the import that picks
# the dev or production sites.
# routes.caddy the proxy route table, shared by dev and production.
# ADD A NEW PROXIED ROUTE THERE.
# sites/prod.caddy production: http -> https://www, the apex (registry
# and redirect), the www site.
# sites/dev.caddy dev: localhost on http and https, `/` -> Vite.
#
# WHICH SITES ARE LOADED
# CADDY_SITE picks the file (`prod` unless set; docker-compose.dev.yml sets
# `dev`). It is a parse-time {$VAR}, substituted before the Caddyfile is
# read, so it can name the import itself.
#
# TWO KINDS OF VARIABLE
# {$NAME} / {$NAME:default} read from the environment ONCE, when the config
# is parsed. Used for upstream names and the
# domain. They end up in the JSON config Caddy
# autosaves to /config, so never a secret.
# {env.NAME} read per use at runtime, never written into the
# config. Used for the two secrets: the
# Cloudflare DNS token and the receipt token.
# Every variable must be in the caddy service's explicit `environment:`
# list in docker-compose.yml, or it reaches Caddy empty. Note an EMPTY
# variable is not "unset": {$X:default} keeps the empty value. So defaults
# live in that compose list (${X:-default}), which treats both alike, as
# nginx's entrypoint's ${X:-default} did.
#
# WHAT NO LONGER NEEDS DOING (vs nginx)
# - Upstreams are resolved when Caddy dials them, not at startup, so it
# boots with any container missing and 502s until it appears. No
# `resolver` / `set $upstream_*` trick.
# - Certificates are obtained and renewed in-process (sites/prod.caddy), and
# Caddy serves while it does, so there is no bootstrap config, no certbot,
# no reload sentinel.
# - `header` is additive: a route that sets its own headers keeps the site's
# too. No security_headers.conf re-included everywhere.
# - Websocket upgrades, streaming responses and request-body streaming are
# the reverse proxy's defaults.
# =============================================================================
# Global options and shared snippets. Routes are in routes.caddy; per-mode
# sites in sites/<CADDY_SITE>.caddy. {$X} is substituted at parse time and
# saved into /config, so secrets are read as {env.X} instead.
{
# No `email`: the ACME account works without one, Let's Encrypt stopped
# sending expiry notices in 2025, and an `email {$EMAIL}` line with EMAIL
# unset is a parse error that keeps the whole edge from starting.
# No `email`: with EMAIL unset that line is a parse error.
# rate_limit is a plugin, so it has no place in Caddy's built-in directive
# order. Before basic_auth means before forward_auth too: a gated route
# counts the request before asking the backend about the session, as
# nginx's limit_req (preaccess phase) ran before auth_request (access).
# Count requests before forward_auth asks the backend.
order rate_limit before basic_auth
# Dev's `tls internal` would otherwise try to add Caddy's local CA to the
# container's trust store, which is pointless and logs an error.
# Stops `tls internal` trying to edit the container's trust store.
skip_install_trust
servers {
# Real client IP behind the Cloudflare tunnel. For connections from
# the cloudflared container, and only those, the client IP is taken
# from Cloudflare's CF-Connecting-IP header. {client_ip} is then the
# visitor everywhere it is used: the rate-limit keys, the access log,
# and the X-Real-IP / X-Forwarded-For sent upstream (see `proxy`).
#
# Pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the subnet. Direct
# visitors on the published 80/443 can arrive from the bridge gateway,
# 172.28.0.1, so trusting the subnet would let anyone choose their own
# IP, and so their own rate-limit bucket, by sending the header.
# Trust CF-Connecting-IP only from cloudflared's fixed IP. Trusting the
# subnet would let direct visitors (via the bridge gateway) pick their IP.
trusted_proxies static 172.28.255.250
client_ip_headers CF-Connecting-IP
# No HTTP/3: 443/udp is not published and cloudflared does not use it,
# so advertising it (Alt-Svc) would only send browsers on a detour.
# 443/udp is not published.
protocols h1 h2
}
# ---- Access logs ---------------------------------------------------------
# Every site imports `logging`, which names its access logger `payloads`.
# The two loggers below take that stream; the default logger is told to
# leave it alone, or each request would also be printed unfiltered,
# request body included.
# Keep access logs out of the default logger, or bodies print unfiltered.
log default {
exclude http.log.access.payloads
}
# The payload log: one JSON line per request, body included (log_append
# in `logging`), for seeing what actually arrives at the edge.
# logs/caddy/ on the host; the `traffic` container tails it so Dozzle
# shows it as its own stream. Caddy rotates it itself, and
# `tail -F` follows the rotation. 0644 so `jq` on the host can read it
# unprivileged (Caddy's default is 0600).
#
# Redaction: any body mentioning a password, token or secret is replaced
# whole, not field by field, because there is no JSON parser here. That
# catches /auth/login, the GraphQL login and change-password mutations and
# the refresh-token call in one rule. Over-matching (a query that merely
# selects a field named *token*) costs a hidden body, never a leak.
# Cookie and Authorization headers are logged as REDACTED by Caddy itself
# (the `log_credentials` server option is off).
# One JSON line per request, body included. A body mentioning a password,
# token or secret is redacted whole: there is no JSON parser here.
log payloads_file {
include http.log.access.payloads
output file /var/log/caddy/payloads.log {
@@ -117,9 +42,7 @@
}
}
# The container's stdout, which `docker compose logs caddy` and Dozzle
# show: the same requests cut down to one short line each, without the
# body or headers, like nginx's `compact` format.
# One short line per request for `docker logs` and Dozzle.
log payloads_stdout {
include http.log.access.payloads
output stdout
@@ -136,36 +59,16 @@
}
# ---- Snippets ----------------------------------------------------------------
# Defined here, before the site files are imported, so every file can use
# them. `import <snippet> <args...>` fills {args[N]}.
# Inside every reverse_proxy. Caddy already passes Host through and sets
# X-Forwarded-Proto/Host. X-Forwarded-For is overwritten rather than left to
# Caddy's default, which APPENDS the trusted peer: behind the tunnel that is
# "<visitor>, 172.28.255.250", and Gitea (REVERSE_PROXY_LIMIT = 1, so the
# rightmost entry) would log cloudflared for every visitor. With exactly one
# entry, the visitor, every upstream sees what nginx gave it: gin's ClientIP()
# (backend/main.go, trusts 172.28/16), Gitea, and python/app/main.py's
# _internal_only guard, which refuses any request carrying either header.
# Overwrite X-Forwarded-For rather than append, so upstreams see only the
# visitor, not cloudflared.
(proxy) {
header_up X-Real-IP {client_ip}
header_up X-Forwarded-For {client_ip}
}
# import limit <zone> <events> <window>
#
# A sliding window: at most <events> per <window> per client IP, then 429
# (turned into 503 by `errors`). Unlike nginx's leaky bucket there is no
# separate burst, so each zone's <events> is nginx's rate and <window> its
# unit, which keeps the sustained rates exact; the instant allowance comes out
# close to nginx's burst + 1. DEPLOYMENT.md §6 has the table and the reasoning
# behind each zone.
#
# State is shared per ZONE NAME across every route that names it (the plugin
# keeps one pool keyed by name), which is how /api, /py, /jobs, /usaco and
# /tracker share one `api` bucket, as in nginx. So a zone name must always be
# given the same <events> and <window>; a route that wants different numbers
# needs its own zone name (see `receipt`).
# import limit <zone> <events> <window>: sliding window per client IP.
# A zone name is one shared bucket, so it must always get the same numbers.
(limit) {
rate_limit {
zone {args[0]} {
@@ -176,20 +79,8 @@
}
}
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/,
# /uploads/private/) ----
# forward_auth sends a GET carrying the original request's headers, cookie
# included, to the backend's /auth/validate-admin before the request goes
# anywhere. 2xx lets it through; 401/403 become a redirect to the SPA login.
# This puts the Go backend's session in front of services that have no idea
# it exists. The body is never sent (the method is rewritten to GET), so a
# 2 GB garage-webui upload does not go to the backend twice.
#
# {http.request.orig_uri}, not {uri}: a route's `uri strip_prefix` runs
# BEFORE forward_auth in Caddy's directive order, so {uri} would have lost its
# prefix by the time this redirect is built. The `*` matters too: given only a
# target and a status, `redir` takes a target starting with / as a path
# MATCHER, and the redirect would never fire.
# forward_auth sends no body. orig_uri because strip_prefix runs first; the
# `*` stops redir reading the target as a path matcher.
(admin_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate-admin
@@ -200,19 +91,8 @@
}
}
# ---- Permission gate (/receipt/) ----
# import permission_gate <key>
#
# The same mechanism, but asking GET /auth/validate/<key> whether the session
# holds one named permission (backend/services/permissions.go; admins hold
# them all), so a non-admin account granted it in the admin panel gets in.
# 401 (not signed in) goes to the login page; 403 (signed in, not granted)
# goes to a page that says so, since sending a signed-in user to log in again
# only shows them "Already signed in".
#
# On success the backend returns the username in X-Auth-User, copied onto the
# proxied request as X-Remote-User. copy_headers deletes any X-Remote-User the
# client sent before it sets the real one, so the upstream can trust it.
# import permission_gate <key>. 403 goes to /no-access, not the login page.
# copy_headers drops any client-sent X-Remote-User, so upstreams can trust it.
(permission_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate/{args[0]}
@@ -228,14 +108,7 @@
}
}
# Production only (sites/prod.caddy); HSTS on localhost would poison the
# browser for every other localhost project on the machine.
#
# No site-wide CSP here. It was left out because Gitea, proxied at /gitea/
# until 2026-11-24, relies on inline <script> blocks its own templates
# generate, so a shared script-src would need 'unsafe-inline', which voids
# almost all of CSP's value. Gitea now lives on git.DOMAIN and /gitea/ only
# redirects, so that reason is gone; a real CSP for the SPA is now possible.
# Production only: HSTS on localhost would affect every local project.
(security_headers) {
header {
X-Frame-Options "SAMEORIGIN"
@@ -245,13 +118,8 @@
}
}
# User-uploaded files are attacker-supplied bytes on our own origin. nosniff
# stops content-type guessing (so backend/services/uploads.go's stored type is
# what the browser goes by), Content-Disposition inline keeps them from being
# treated as downloads, and the locked-down CSP means even an uploaded .html
# can run no script and load no resource. `>` defers each one until the
# response is written, so it also wins over anything Garage sends. (-Server
# and -Via repeat `common`'s, for the error route, which does not run it.)
# Uploads are attacker-supplied bytes on our origin. `>` makes these win over
# Garage's headers.
(upload_headers) {
header {
>X-Content-Type-Options "nosniff"
@@ -262,45 +130,22 @@
}
}
# The disk half of /uploads/ (see routes.caddy): hand the request to the
# uploads disk site at the bottom of this file. Used both when Garage answers
# 404/5xx (handle_response) and when it cannot be reached at all (`errors`),
# so it works from the ORIGINAL path, whatever the route had stripped by then.
#
# Why proxy to a second site rather than call file_server here: in an error
# route file_server answers with the ERROR's status, so a file served while
# Garage is down would arrive as a 502 (with the file as its body), and
# forcing 200 instead would also turn its 206 and 304 answers into 200s. A
# proxied response keeps whatever status the disk site gave it.
#
# The headers are imported again because error routes do not inherit the
# deferred ones of the route that failed.
# Serves /uploads/ from disk via the :2080 site. A proxy, not file_server,
# because in an error route file_server replies with the error's status.
# Error routes don't inherit deferred headers, hence the import.
(uploads_disk) {
import upload_headers
rewrite * {http.request.orig_uri.path}
reverse_proxy 127.0.0.1:2080
}
# Error routes, for errors Caddy raises itself (never for an upstream's own
# error response, which is passed through untouched). Any error none of these
# handles is answered with its own status and an empty body.
(errors) {
# rate_limit's 429. Answered as 503, the status nginx's limit_req used,
# because vue/src/views/hotels/hotelsStream.js tells the two apart: 503 is
# "too many searches from your address", while a 429 is the Python
# service's own "someone else is searching right now".
# 503, not 429: hotelsStream.js reads 429 as the Python service's own limit.
handle_errors 429 {
respond "Too many requests from your address. Wait a moment and retry." 503
}
# An upstream that could not be reached or timed out. Three routes turn that
# into something better than a bare 502, each keyed on a variable its
# route sets (error routes keep the request's vars, and a variable cannot
# be spoofed the way a path can be dressed up):
# uploads_fallback Garage is down: serve the file from disk instead.
# receipt_upstream set only once the permission gate has passed, so a
# backend outage is not reported as the printer's.
# radar_upstream the Partner Radar stack (radar.DOMAIN) is down.
# Keyed on vars set by the route, which cannot be spoofed like a path.
handle_errors 502 504 {
@uploads_fallback vars uploads_fallback yes
handle @uploads_fallback {
@@ -317,29 +162,19 @@
}
}
# The access log, and the request body on it. {http.request.body} buffers the
# body in memory to log it, so it is only taken when the client declared a
# length under 100 KB and the route is not an upload path: big and chunked
# bodies are logged without one. nginx did the equivalent: bodies over its
# 64k buffer went to a temp file and logged empty.
# Bodies are buffered in memory to log them, so only small non-upload ones.
(logging) {
log payloads
@small_body {
# Up to five digits, spelt out because a {1,5} would read as a
# placeholder.
# Spelt out: {1,5} would parse as a placeholder.
header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
}
# `<` (early: taken before the request is proxied) must be explicit.
# Without it 2.11 takes the body early as documented, but then takes it a
# second time after the proxy has read it, logging an empty string.
# `<` must be explicit, or the body is logged a second time, empty.
log_append @small_body <req_body {http.request.body}
}
# Compression, for the types nginx's gzip_types listed. An explicit list so
# that streamed responses (application/x-ndjson from /py/hotels/*, Dozzle's
# text/event-stream, icecast's audio) are never held back to fill a
# compression buffer.
# Explicit types so streamed responses (ndjson, SSE, audio) are never buffered.
(encode) {
encode zstd gzip {
minimum_length 256
@@ -360,35 +195,20 @@
import logging
import errors
import encode
# Caddy's own `Server: Caddy` and an upstream's (icecast sends one), and
# the `Via: 1.1 Caddy` its reverse proxy adds: nginx sent neither.
header {
-Server
-Via
}
}
# ---- Container healthcheck ---------------------------------------------------
# The target of the healthcheck in docker-compose.yml, which the `autoheal`
# container acts on. Answered by Caddy itself, so it measures whether the
# server is serving and nothing upstream. Plain HTTP on :80, addressed by IP
# so it matches no real site; not logged, or it would put a line in the
# payload log every 30 s.
# ---- Container healthcheck (unlogged) ----------------------------------------
http://127.0.0.1 {
respond /caddy-health 204
respond 404
}
# ---- Uploads disk site -------------------------------------------------------
# The shared `uploads` volume (mounted at /srv/uploads), served to this
# container only (bound to the loopback; nothing publishes 2080). Reached by
# `uploads_disk` when Garage has no copy of a file; see that snippet for why
# it is a site of its own. Unlogged: the request was logged as it arrived.
#
# private/ is refused here as well as gated upstream. A request is routed by
# its cleaned, lower-cased path, so anything that could reach private/ goes to
# the gated /uploads/private/ route long before this; the refusal is the
# second lock, should that route ever be reordered.
# ---- Uploads disk site (loopback only, unlogged) -----------------------------
# private/ is refused here too, in case the gated route is ever reordered.
http://:2080 {
bind 127.0.0.1
@private path /uploads/private /uploads/private/*
+6 -40
View File
@@ -1,37 +1,8 @@
# =============================================================================
# caddy image — the public edge. Caddy with two plugins, plus this
# directory's config, checked while the image is built.
#
# WHY A CUSTOM BUILD
# Stock Caddy has neither of these, and the config needs both:
# caddy-dns/cloudflare DNS-01 certificates through the Cloudflare API
# (sites/prod.caddy), since the router forwards
# nothing to obtain them over HTTP.
# mholt/caddy-ratelimit the `rate_limit` directive (the `limit` snippet
# in the Caddyfile).
# xcaddy compiles them in. The cloudflare plugin is pinned to a release;
# caddy-ratelimit has had one tagged release (v0.1.0, 2024) and is pinned
# to a commit, so Renovate leaves it alone and it is bumped by hand.
#
# BASE: caddy:2.11.9, the builder and the runtime from the same release
# (the builder's xcaddy builds the CADDY_VERSION its image sets). Both
# tags are bumped together. Official images are multi-arch.
#
# THE CONFIG IS VALIDATED AT BUILD TIME
# The last RUN parses and provisions the config with `caddy validate`, for
# the production sites and the dev ones, against placeholder values for
# every variable the config reads. A config that would not load therefore
# fails the image build, and a failed build aborts `docker compose up
# --build` BEFORE any container is replaced, so the running edge keeps
# serving. `make check-caddy` is the same build. The placeholders exist
# only for that RUN; the real values come from the container's
# environment (docker-compose.yml).
#
# NO ENTRYPOINT. The base image's CMD runs
# `caddy run --config /etc/caddy/Caddyfile --adapter caddyfile`, which is all
# that is needed: Caddy reads the environment itself, and obtains and renews
# its own certificates.
# =============================================================================
# Caddy plus the Cloudflare DNS and rate-limit plugins. caddy-ratelimit is
# pinned to a commit (no usable release), so Renovate leaves it; bump by hand.
# Builder and runtime tags move together.
# The last RUN validates the config for both modes, so a bad config fails the
# build before any running container is replaced.
FROM caddy:2.11.9-builder AS builder
RUN xcaddy build \
--with github.com/caddy-dns/[email protected] \
@@ -41,13 +12,8 @@ FROM caddy:2.11.9
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile routes.caddy /etc/caddy/
COPY sites/ /etc/caddy/sites/
# Mount points (docker-compose.yml). Created so Caddy still starts without
# them: the log directory especially, since a log file that cannot be opened
# stops the config loading.
# A log directory that can't be opened stops the config loading.
RUN mkdir -p /var/log/caddy /srv/www /srv/uploads
# Validation writes Caddy's data and the payload log, so it is pointed at a
# throwaway directory and the log is removed afterwards, leaving the image as
# it was.
RUN set -e; \
for site in prod dev; do \
echo "caddy validate (CADDY_SITE=$site)"; \
+9 -50
View File
@@ -1,49 +1,12 @@
#!/usr/bin/env bash
# =============================================================================
# edge_test.sh — what the public edge does with a fixed set of requests.
#
# WHAT IT DOES
# Sends each request below to the edge and prints one line per request
# (status and Location, or one response header). Two kinds of line:
# ok / FAIL the privacy boundary and the gates, which have a fixed right
# answer: the /notes/ denials, /py/internal/, every gated
# prefix. Any FAIL makes the exit status 1.
# show / hdr everything else (redirects, headers, carve-outs, uploads),
# whose answer depends on the upstream's data. Compare two runs
# instead (below).
#
# USAGE
# caddy/edge_test.sh <base-url> [curl options...]
# base-url the www origin, e.g. https://www.example.com
# curl options added to every request: --resolve to reach a given
# container, -k for dev's internal CA.
# Environment, all optional:
# EDGE_APEX the apex origin (production only): adds the apex cases.
# EDGE_HTTP the plain-http apex origin (production only), e.g.
# http://example.com: adds the http -> https case.
# EDGE_COOKIE an admin session's Cookie header value: adds the
# signed-in cases (each gated prefix must then NOT redirect
# to the login).
# EDGE_UPLOAD the name of a file under /uploads/ that exists.
#
# On stpvm, pin the hostname to this machine, or curl goes out over the
# internet and back (and hangs):
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
# Dev stack:
# caddy/edge_test.sh https://localhost -k
#
# COMPARING TWO EDGES
# Run it against each and diff the output. This is how Caddy was checked
# against nginx before the 2026-11-17 cutover (Caddy on 8443 beside nginx),
# and how a big change to caddy/ can be checked against the running edge:
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >before.txt
# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >after.txt
# diff before.txt after.txt
# Every remaining difference should be one that was intended.
#
# NOTHING HERE WRITES. Every request is a GET, apart from one POST to
# /py/internal/, which never gets past the edge.
# =============================================================================
# Probes the edge. ok/FAIL lines (privacy denials and gates) set the exit
# status; show/hdr lines depend on data, so diff two runs instead.
# caddy/edge_test.sh <www-origin> [curl options...]
# e.g. https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 (on stpvm)
# https://localhost -k (dev)
# Optional env: EDGE_APEX, EDGE_HTTP, EDGE_COOKIE (admin session),
# EDGE_UPLOAD (an existing upload's name). Read-only: GETs plus one POST that
# the edge refuses.
set -u
if [ $# -lt 1 ]; then
@@ -57,11 +20,7 @@ FAILED=0
# The www host, without scheme or port.
BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')
# "<status> <location>" for one request. Arguments after the URL are extra
# curl options (method, headers, --path-as-is). A redirect to the www host is
# shown as its path alone: nginx sends an absolute Location built from its
# own port, Caddy a relative one, and either way the browser lands on the
# same page.
# "<status> <location>"; a redirect to www is shown as its path alone.
probe() {
local url=$1 out
shift
+41 -185
View File
@@ -1,55 +1,10 @@
# =============================================================================
# routes.caddy — the PROXY ROUTE TABLE shared by production and dev. Add a new
# proxied route HERE, once.
#
# WHO IMPORTS IT
# sites/prod.caddy (the www site) and sites/dev.caddy, each inside a
# `route { ... }` block, followed by that site's own `/` handler (the built
# SPA in production, the Vite dev server in dev). Everything else that
# differs between the two (TLS, security headers, static-asset caching, the
# apex) is in the site files.
#
# ORDER IS LITERAL: THE FIRST MATCHING handle WINS
# Inside `route`, Caddy keeps directives in the order written, and `handle`
# blocks are mutually exclusive. So this file is read top to bottom like a
# firewall list: denials first, then the specific routes, each carve-out
# ahead of the gated prefix it is carved out of, then the catch-alls.
# (nginx's longest-prefix / regex-in-file-order / ^~ rules are gone.)
#
# HOW PATHS ARE MATCHED
# `path` matchers are case-insensitive and see the decoded, cleaned path
# (`..` resolved, `//` merged), so /SB/, /notes/a/../private/x or
# /uploads/%70rivate/x cannot slip past a rule. `path_regexp` sees the
# decoded, cleaned path too but is case-sensitive, hence `(?i)` where case
# matters. caddy/edge_test.sh checks these against the live edge.
#
# PATTERNS THAT REPEAT BELOW
# - `uri strip_prefix /x`: the public URL carries a prefix (/api, /radio,
# /gitea, /py, /tracker, /receipt) but the upstream serves from /. Apps
# told their own base path (SilverBullet, the job tracker, usaco, Dozzle,
# garage-webui) keep it.
# - `import proxy` in every reverse_proxy: the forwarding headers (see the
# snippet in Caddyfile).
# - `import limit <zone> ...`: see the snippet; DEPLOYMENT.md §6 for the
# numbers.
# - `import admin_gate` / `import permission_gate <key>`: the session check
# against the backend. Some of these services have no auth of their own,
# so a gated route that loses its import is open to the internet.
# - Upstream read timeouts are not set anywhere: Caddy has none by default,
# so a long hotel search, an email sync or a log tail is never cut off by
# the proxy. (Cloudflare still gives up on an origin that sends nothing
# for 100 s; see DEPLOYMENT.md.)
#
# Upstream names come from the environment ({$BACKEND_HOST} etc.; see the
# caddy service in docker-compose.yml). The job tracker, activity tracker,
# usaco, Dozzle and Garage containers have fixed names there, so they are
# written literally.
# =============================================================================
# The route table for both modes, imported inside a `route` block: the first
# matching handle wins, so denials go first and each carve-out precedes the
# prefix it is carved from. `path` is case-insensitive on the cleaned path;
# path_regexp is case-sensitive, hence (?i). caddy/edge_test.sh checks these.
# A gated route that loses its gate import is open to the internet.
# Request bodies: 50 MB everywhere except garage-webui, which takes video
# uploads and sets its own 2 GB below. (An outer limit cannot be raised by an
# inner one, so the exception has to be carved out here.) The backend caps
# uploads at 10 MB itself; this is the ceiling for everything else.
# An inner limit cannot raise an outer one, so garage-webui's 2 GB is carved out here.
@body_default not path /garage/*
request_body @body_default {
max_size 50MB
@@ -57,38 +12,16 @@ request_body @body_default {
# ---- Denials -----------------------------------------------------------------
# /py/internal/: routes the Go backend calls directly over app-network (the
# rowing photo reader, which spends a paid Claude call and has no auth of its
# own). Never proxied. The Python side also refuses anything carrying the
# X-Real-IP / X-Forwarded-For headers `proxy` sets, as a second layer.
# Called by the backend over app-network only; spends paid Claude calls.
handle /py/internal/* {
respond 404
}
# PUBLIC notes viewer privacy boundary. /notes/ is a second, read-only
# SilverBullet over the vault /sb/ edits, and SB_SPACE_IGNORE only hides
# paths from its file LIST. Everything else serves them (all verified against
# 2.11.0 with curl):
# /notes/.fs/private/x.md raw file, straight off disk
# /notes/private/x the page URL: the server pre-renders the
# note's content into the HTML shell
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
# version of every private note ever
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a private/
# folder at ANY depth, so the block must too.
#
# 1. private/ or templates/ as any path segment, page URL or /.fs/. (?i) so
# Private/ is caught; (/|$) so the folder itself matches.
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The first
# segment is exempt because that is where SilverBullet's own endpoints
# live (/.fs, /.config, /.client, /.events ...). Nothing the client
# legitimately loads has a dot-segment deeper than that.
# 3. Revisions are read from the vault's own .git, i.e. the full history of
# every file INCLUDING private/ and anything ever deleted.
# SB_REVISIONS=disabled already turns this off upstream; this is the
# second lock in case that env var is ever dropped.
# Keep the folder list in step with SB_SPACE_IGNORE on silverbullet-public.
# 404 rather than 403 so the response does not confirm a private path exists.
# SB_SPACE_IGNORE only hides paths from listings, so these block direct
# fetches: private/ or templates/ at any depth, any dot-segment below the
# first (SilverBullet's own endpoints live at the first), and revisions.
# Keep the folder list in step with silverbullet-public's SB_SPACE_IGNORE.
# 404, not 403, so a private path's existence isn't confirmed.
@notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$)
handle @notes_private {
respond 404
@@ -104,9 +37,7 @@ handle /notes/.revisions* {
}
# ---- Bare prefixes and moved URLs ----------------------------------------------
# So a user typing /gitea without the slash lands correctly. Exact paths: unlike
# nginx's prefix locations, /gitea-something is not caught and is left to the
# SPA (where an admin-created canvas page with that slug now works).
# Exact paths, so /gitea-something is left to the SPA.
redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301
redir /radio /radio/ 301
redir /dozzle /dozzle/ 301
@@ -120,19 +51,14 @@ redir /usaco /usaco/ 301
redir /tracker /tracker/ 301
redir /receipt /receipt/ 301
# Where the job tracker used to be. The SPA routes were client-side, so these
# only catch bookmarks and typed URLs. The userscript's old @updateURL lands
# on the third, which is how installed copies find version 2.0.0 and its new
# API base.
# Old job tracker URLs; the userscript's old @updateURL finds its update here.
redir /cv/jobs /jobs/ 301
redir /cv/leads /jobs/leads 301
redir /job-capture.user.js /jobs/job-capture.user.js 301
# ---- Backend API ---------------------------------------------------------------
# Live chat / activity feed websocket. Deliberately NOT rate limited: a
# websocket is one long-lived request, and a limit here would drop reconnect
# storms, not abuse.
# Not rate limited: a limit would only drop reconnect storms.
handle {$BACKEND_ENDPOINT}/ws* {
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
@@ -140,7 +66,7 @@ handle {$BACKEND_ENDPOINT}/ws* {
}
}
# Brute-force defence on password auth, on top of the backend's own 5/min.
# On top of the backend's own 5/min.
handle {$BACKEND_ENDPOINT}/auth/login* {
import limit login 5 1m
uri strip_prefix {$BACKEND_ENDPOINT}
@@ -157,8 +83,7 @@ handle {$BACKEND_ENDPOINT}/uploads* {
}
}
# Tighter than the REST catch-all, because one GraphQL query can be
# arbitrarily expensive to resolve.
# One GraphQL query can be arbitrarily expensive.
handle {$BACKEND_ENDPOINT}/graphql* {
import limit graphql 10 1s
uri strip_prefix {$BACKEND_ENDPOINT}
@@ -177,11 +102,7 @@ handle {$BACKEND_ENDPOINT}/* {
# ---- Admin-gated services ------------------------------------------------------
# Dozzle: live view of every container's logs, including the `traffic`
# container's request-body log. It reads the Docker socket, so it is
# effectively root on the host: admin only. DOZZLE_BASE=/dozzle makes it serve
# under the prefix itself. Its log tails are server-sent events, which Caddy
# streams without buffering.
# Docker socket access is root on the host.
handle /dozzle/* {
import admin_gate
reverse_proxy dozzle:8080 {
@@ -189,11 +110,7 @@ handle /dozzle/* {
}
}
# garage-webui: buckets, keys and a file browser for the Garage object store.
# It holds Garage's admin token, so admin only, and its own login is left
# unset (one login, not two). BASE_PATH=/garage makes it serve under the
# prefix. 2 GB so videos can be uploaded through it; the body streams through
# rather than landing on disk first.
# Holds Garage's admin token. 2 GB for video uploads.
handle /garage/* {
import admin_gate
request_body {
@@ -204,9 +121,7 @@ handle /garage/* {
}
}
# The icecast ADMIN UI is a full station-control surface (kick sources, change
# metadata) protected only by the icecast admin password. Ahead of /radio/*,
# so listener traffic (the mount, status.xsl) is untouched.
# Station-control UI guarded only by the icecast password.
handle /radio/admin/* {
import admin_gate
uri strip_prefix /radio
@@ -215,10 +130,8 @@ handle /radio/admin/* {
}
}
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes. NO
# prefix strip: it is a PWA told its own base path via SB_URL_PREFIX=/sb, and
# builds its service-worker scope and asset URLs from it. Strip the prefix and
# the app loads a blank page with no error in the log.
# No prefix strip: with SB_URL_PREFIX the app builds its URLs from /sb, and a
# stripped prefix loads a blank page.
handle /sb/* {
import admin_gate
reverse_proxy {$SILVERBULLET_HOST}:{$SILVERBULLET_PORT} {
@@ -235,32 +148,20 @@ handle /radio/* {
}
}
# Gitea moved to its own address on 2026-11-24: git.DOMAIN, served by the
# Gitea LXC's own Cloudflare tunnel (the adamf/stpgit repo), and its ROOT_URL.
# Every old link (the CV's, HTTPS clone URLs, bookmarks) is sent there with the
# prefix dropped and the query kept; git follows the redirect on a clone. This
# edge no longer proxies Gitea's pages, so the admin gate that used to sit on
# its commit-history views and archives (a crawler swarm walked them in
# 2026-10) went with it: on git.DOMAIN they are public by choice. The registry
# at the apex's /v2/ (sites/prod.caddy) is still proxied from here.
# Gitea is at git.DOMAIN; the registry at /v2/ is still proxied (prod.caddy).
handle_path /gitea/* {
redir https://git.{$DOMAIN}{uri} 301
}
# The public notes viewer, behind the denials at the top of this file. No
# prefix strip, for the same reason as /sb/ (SB_URL_PREFIX=/notes).
# No prefix strip (SB_URL_PREFIX=/notes).
handle /notes/* {
reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} {
import proxy
}
}
# /py/hotels/search[/stream] and /py/hotels/scan/stream: public, minutes-long
# upstream calls to Travelodge/TfL with a single search slot on the Python
# side, so this zone is really concurrency protection. flush_interval -1
# passes each NDJSON progress line on as it arrives (chunked responses are
# flushed anyway; this makes it explicit). `encode` never touches
# application/x-ndjson.
# Minutes-long searches with one slot on the Python side, so the limit is
# really concurrency protection. flush_interval passes NDJSON lines straight on.
@hotels path_regexp ^/py/hotels/(search|scan)
handle @hotels {
import limit hotel_search 3 1m
@@ -280,16 +181,8 @@ handle /py/* {
}
# ---- Job tracker (/jobs/) ----
# Its own container (the adamf/job-tracker repo), which serves its SPA and its
# API from the same prefix, NOT stripped: the app is built to live at /jobs/.
# Gated like /sb/ (the app checks the session itself too), with two
# exceptions ahead of it that a session cookie can never reach:
# - the capture API, called by the userscript from job sites' origins with
# the capture bearer token rather than cookies; the app's
# CaptureTokenMiddleware guards it;
# - the userscript itself: userscript managers fetch its @updateURL without
# the session, and it holds no secrets (the token is entered after
# install).
# Not stripped: the app lives at /jobs/. The capture API (bearer token) and
# the userscript (fetched without cookies, holds no secrets) bypass the gate.
handle /jobs/api/capture* {
import limit api 30 1s
reverse_proxy jobs:8080 {
@@ -311,12 +204,9 @@ handle /jobs/* {
}
}
# ---- USACO practice log (/usaco/) ----
# Its own container (the usaco repo's site/), shaped like /jobs/: SPA and API
# under one prefix that is NOT stripped, and no gate, because most of it is
# public and the app checks the session itself for the admin's edits. Gitea's
# push webhook (/usaco/api/hooks/gitea) comes through here too, from the
# Gitea LXC over the LAN; it is signed with USACO_WEBHOOK_SECRET.
# ---- USACO (/usaco/) ----
# Not stripped, not gated: the app checks the session for admin edits. The
# Gitea webhook arrives here, signed with USACO_WEBHOOK_SECRET.
handle /usaco/* {
import limit api 30 1s
reverse_proxy usaco:8080 {
@@ -325,15 +215,8 @@ handle /usaco/* {
}
# ---- Activity tracker (/tracker/) ----
# Its own container (the adamf/ccp repo): an ingest API for device collectors,
# which send batches of events with a per-device bearer key, plus a dashboard
# and setup page. Gated like /sb/ (the app also checks the session itself),
# with two exceptions ahead of it: the API, which collectors call with bearer
# keys and no cookies (the app guards each route, by device key, admin
# session or either), and the public userscript. Unlike /jobs/ the prefix IS
# stripped: the server serves /api/v1/... and /readyz from /. Collectors must
# use the www host: the apex 301 would turn their POSTs into GETs. Health Auto
# Export bodies can be several MB; the 50 MB default above covers them.
# The collector API (bearer keys) and the userscript bypass the gate.
# Collectors must use www: the apex 301 turns POSTs into GETs.
handle /tracker/api/v1/* {
import limit api 30 1s
uri strip_prefix /tracker
@@ -359,21 +242,10 @@ handle /tracker/* {
}
# ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi (not in
# this stack: that machine reaches the printer on the home LAN), reached over
# Tailscale by IP. A page for printing a note or an uploaded image, plus its
# API. Behind the permission gate on `receipt`, so an account granted it in
# the admin panel can print without being an admin; the prefix IS stripped.
# The server trusts nothing without X-Receipt-Token, which only this proxy
# adds (header_up replaces any copy the client sent), and is told who is
# printing in X-Remote-User, which the gate sets.
#
# A `route`, so the steps run in the order written: receipt_upstream is set
# only after the gate has passed, so `errors` reports "printer offline" for a
# failed dial to stppi and not for a backend outage during the auth check.
# Its own zone, not `api`: a zone name must always carry the same numbers.
# 17 MB: the server caps uploads at 16 MB, plus room for the multipart
# framing around one.
# Runs on stppi (it is on the printer's LAN), reached over Tailscale.
# header_up replaces any client-sent X-Receipt-Token. A `route` so the
# receipt_upstream var is set only after the gate passes, so a backend outage
# is not reported as "printer offline". 17 MB: 16 MB uploads plus framing.
handle /receipt/* {
route {
import limit receipt 10 1s
@@ -386,8 +258,7 @@ handle /receipt/* {
reverse_proxy {$RECEIPT_WEB_UPSTREAM} {
import proxy
header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN}
# Caddy's default, spelt out: when stppi is off, fail fast and
# let `errors` answer.
# Fail fast when stppi is off.
transport http {
dial_timeout 3s
}
@@ -397,10 +268,7 @@ handle /receipt/* {
# ---- Uploads (/uploads/) ----
# PRIVATE attachments (admin-only): files on *private* chat messages, which
# the backend always writes to disk, at uploads/private/. Ahead of the public
# route below, and matched on the cleaned, lower-cased path, so no spelling of
# a path into private/ reaches the ungated one.
# Private chat attachments, always on disk. Must precede /uploads/*.
handle /uploads/private/* {
import admin_gate
import upload_headers
@@ -408,20 +276,8 @@ handle /uploads/private/* {
file_server
}
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the Garage
# bucket's website endpoint, which serves the bucket anonymously and picks it
# by the Host header (garage/garage.toml: s3_web). The bucket is reachable
# only over app-network, so this is the only public way in. If Garage has no
# such file (404), errors (5xx), or cannot be reached at all (a dial error,
# caught by `errors` through the uploads_fallback variable), the file is
# served from the shared `uploads` volume instead (`uploads_disk`). That
# volume holds uploads from before Garage and anything the backend wrote
# there because Garage refused it (backend/services/uploads.go). So the bucket
# is the source of truth (deleting a file in garage-webui unpublishes it
# unless a disk copy exists), while a Garage outage only costs files that are
# nowhere else. dial_timeout 2s: Garage is on the same bridge, so a slow
# connect means it is down; fall back quickly. Range requests pass through
# either way, so video seeks.
# Garage first, disk second: a 404, 5xx or dial error falls back to the
# volume, so the bucket is the source of truth.
handle /uploads/* {
import upload_headers
vars uploads_fallback yes
+3 -19
View File
@@ -1,22 +1,6 @@
# =============================================================================
# sites/dev.caddy — LOCAL DEVELOPMENT sites. Imported by the Caddyfile when
# CADDY_SITE=dev, which only docker-compose.dev.yml sets.
#
# HOW IT DIFFERS FROM sites/prod.caddy
# - `/` is proxied to the Vite dev server at vue:5173 instead of serving the
# built SPA. Its HMR websocket needs nothing extra.
# - http AND https both serve the full site, with no redirects, so
# http://localhost just works. Listing the http:// addresses is what
# stops Caddy adding its automatic http -> https redirect.
# - TLS is `tls internal`: a certificate from Caddy's own local CA, kept in
# ./caddy/data. Browsers warn until that CA is trusted, which is expected.
# - No security headers: HSTS on localhost would poison the browser for
# every other localhost project on the machine.
# - No static-asset caching: Vite serves those, and long cache lifetimes
# would defeat hot reload.
# Everything else, every proxied route, gate, denial and rate limit, is the
# same routes.caddy as production.
# =============================================================================
# Dev (CADDY_SITE=dev): `/` goes to Vite, http and https both serve without
# redirects (listing the http:// addresses disables Caddy's), `tls internal`,
# and no security headers or asset caching.
http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} {
tls internal
+17 -67
View File
@@ -1,30 +1,8 @@
# =============================================================================
# sites/prod.caddy — PRODUCTION sites. Imported by the Caddyfile unless
# CADDY_SITE says otherwise.
#
# FOUR SITES
# 1. http:// apex + www -> 301 to https://www.DOMAIN.
# 2. https:// apex -> Gitea's registry at /v2/, else 301 to www, so
# there is exactly one canonical origin (cookies,
# CORS and the SPA all assume www).
# 3. https:// www -> the real site.
# (4. the healthcheck site, http://127.0.0.1, is in the Caddyfile.)
#
# CERTIFICATES
# Caddy obtains one for each name over DNS-01 through the Cloudflare API
# (`prod_tls`), keeps them in /data (./caddy/data on the host), and renews
# each when a third of its lifetime is left, in-process, with no reload.
# DNS-01 because the router forwards nothing: behind the tunnel no ACME
# server can reach :80 or :443. The token needs Zone -> Zone -> Read and
# Zone -> DNS -> Edit on this zone; see .env.example. Until the first
# certificate arrives (about a minute on a fresh ./caddy/data) the TLS
# handshake fails, so the tunnel, which verifies it, serves 502s.
#
# resolvers: on app-network, DOMAIN is a network alias for this very
# container, so Docker's DNS would answer the plugin's zone lookup itself
# and the order fails with "expected 1 zone, got 0". Asking Cloudflare's
# public resolvers sees the real zone.
# =============================================================================
# Production. The apex serves only the registry and otherwise redirects, so
# www is the one origin cookies and CORS assume.
# DNS-01 because no ACME server can reach us behind the tunnel. Public
# resolvers because DOMAIN is a Docker alias for this container, which would
# fail the zone lookup ("expected 1 zone, got 0").
(prod_tls) {
tls {
@@ -33,8 +11,7 @@
}
}
# Spelt out rather than left to Caddy's automatic redirect, which goes to the
# same host: http://apex would then take two hops (https://apex, then www).
# Explicit so http://apex is one hop to www, not two.
http://{$DOMAIN}, http://www.{$DOMAIN} {
import logging
header -Server
@@ -47,15 +24,9 @@ http://{$DOMAIN}, http://www.{$DOMAIN} {
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
# Gitea's container registry, which publishes images such as
# DOMAIN/adamf/job-tracker. Docker always talks to /v2/ at the root of
# the host, whatever Gitea's ROOT_URL says, and Gitea advertises its
# token endpoint at https://DOMAIN/v2/token: on the apex, not under
# /gitea/ and not on www. So the apex serves /v2/ itself rather than
# redirecting it; a redirect on a blob upload is not something every
# Docker client follows. No request_body limit (routes.caddy's 50 MB
# is not imported here): image layers are far larger, and Caddy
# streams them to Gitea as they arrive.
# Docker clients expect /v2/ (and Gitea's token endpoint) at the apex root
# and don't all follow redirects on blob uploads. No body limit: layers
# are large and stream through.
handle /v2/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
@@ -72,13 +43,8 @@ www.{$DOMAIN} {
import security_headers
# ---- Static asset caching ----
# Each matcher also requires the file to exist (`file`), so only a real
# file is marked cacheable: a 404 for a hash the browser asks for before
# the new build lands must never be cached for a year as `immutable`.
# (nginx's add_header without `always` skipped error responses the same
# way.)
# `file` so a 404 for a not-yet-deployed hash is never cached as immutable.
# Vite hashed assets: a new build has new names, so these never change.
@hashed {
path /assets/*
file {
@@ -103,27 +69,20 @@ www.{$DOMAIN} {
}
header @week Cache-Control "public, max-age=604800"
# This GIF is a "web stamp" other people's sites hot-link, so it needs a
# CORS header. It is a public, deliberately hot-linkable image and nothing
# here is credentialed, so `*` is safe.
# A hot-linked web stamp; public and uncredentialed, so `*` is safe.
header /img/stamps/mine.gif Access-Control-Allow-Origin "*"
route {
import ../routes.caddy
# Static directories: a missing file is a 404, never the SPA's
# index.html. A stale page asking for an old asset hash then gets an
# honest error rather than HTML served as JavaScript.
# 404 rather than index.html, so a stale asset hash isn't served HTML.
@static path /assets/* /fonts/* /img/* /sound/*
handle @static {
root * /srv/www
file_server
}
# The built SPA (the vue_dist volume). Serve the file if it exists,
# otherwise hand index.html to the browser so Vue Router can resolve
# the path client-side: that is what makes deep links like /admin or
# a canvas page's /<slug> work on refresh.
# SPA fallback so deep links work on refresh.
handle {
root * /srv/www
try_files {path} {path}/ /index.html
@@ -133,22 +92,13 @@ www.{$DOMAIN} {
}
# ---- Partner Radar (radar.DOMAIN) ----
# The adamf/cto "Partner Radar" demo: its own docker compose project on this
# host (`make stpvm` there), whose `web` container (its own Caddy, serving the
# React app and proxying its API) joins app-network as `radar-web`. A
# subdomain, not a /radar/ path, because the app assumes it owns `/` and its
# session cookie then stays apart from www's.
#
# No admin gate: the app has its own login and accounts. No security_headers
# either: the app's Caddy sends its own, and www's CSP would block the React
# app. Two zones of its own (see DEPLOYMENT.md §6): `radar` on every request,
# and `radar_login` on top of it for the login endpoint. radar_upstream lets
# `errors` answer "offline" when the stack is down instead of a bare 502.
# The adamf/cto stack's own Caddy. A subdomain because the app assumes it owns
# `/`. No gate (it has its own login) and no security_headers (it sends its
# own, and www's would block the app).
(radar_proxy) {
reverse_proxy {$RADAR_UPSTREAM} {
import proxy
# Caddy's default, spelt out: when the stack is down, fail fast and
# let `errors` answer.
# Fail fast when the stack is down.
transport http {
dial_timeout 3s
}