22 Commits
Author SHA1 Message Date
adamfandClaude Opus 5.5 ffc68bc151 Move the CI runners to adamf/stprunner
Test and deploy / test (push) Successful in 23s
Test and deploy / deploy (push) Successful in 3s
stpvm's and stpbuild's runners are now gitea-runner v6.0.1 systemd
services installed by stprunner's install.sh (hosts/<host>.env per VM),
replacing gitea-runner/run.sh from @reboot cron and the untracked copy on
stpbuild. act_runner 0.2.11 could not run node24 actions. stpvm's runner
is renamed from stppi to stpvm. The GITEA_RUNNER_* env vars had no reader
left. Renovate now also watches stprunner, for gitea-runner releases.

The ignore rules stay: the old directory is still on stpvm with its
.runner credentials.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 13:47:03 +00:00
adamfandClaude Opus 5.5 66173d96e3 CI: scratch directories per run, not per commit
Test and deploy / test (push) Successful in 26s
Test and deploy / deploy (push) Successful in 26s
The build runner takes two jobs at once, so the same commit pushed to
two branches (main and a feature branch) ran its test job twice in
parallel against one src-<sha> directory, and each run's clean-up
deleted the other's source mid-test. Suffix the scratch directories
(and activity-tracker's throwaway Postgres and network) with the run id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:14:45 +00:00
adamfandClaude Opus 5.5 d383774e97 Harden auth: same-origin check, live admin flag, 90-day refresh
Test and deploy / test (push) Failing after 28s
Test and deploy / deploy (push) Has been skipped
- Refuse non-GET requests whose Origin (or Sec-Fetch-Site) is not the
  apex or www. SameSite=Lax lets sibling subdomains such as radar. and
  git. send the auth cookies. The WebSocket check shares the helper and
  no longer accepts localhost in production.
- Take the admin flag from the user row the token check already loads,
  so a demotion applies on the next request, not on token expiry.
- Cut the refresh token lifetime from 365 to 90 days; refreshes renew it.
- Docs: fix the stale revocation notes in backend/README.md and the
  Cloudflare Access comment in routes.caddy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:12:01 +00:00
adamfandClaude Opus 5.5 3139e8e239 CI: run tests and Renovate on the build VM
Test and deploy / test (push) Successful in 1m40s
Test and deploy / deploy (push) Successful in 4s
The test job and Renovate move to stpbuild's runner (label `build`), a
new Proxmox VM; deploy and maintenance stay on stpvm (`self-hosted`).
test fetches over HTTP with the job's own GITEA_TOKEN. DEPLOYMENT.md
gains a "Build VM" section, and CLAUDE.md says where each job runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:00:13 +00:00
adamfandClaude Opus 5.5 18265871e1 Harden the chat hub, evict idle rate-limit keys, isolate Dozzle
Test and deploy / test (push) Successful in 16s
Test and deploy / deploy (push) Successful in 30s
- Chat: cap frame, message and file URL sizes, put a write deadline on
  every send so a stalled client can't hold the hub lock, and check the
  save, prune and history errors instead of broadcasting an unsaved
  message. ChatPanel's maxlength stays under the server cap.
- RateLimiter: sweep keys idle past the window, at most once a window.
- Dozzle: move to an internal dozzle-net shared only with Caddy, so the
  admin gate is the only way to reach the Docker socket.
- Drop the GraphQL WebSocket transport: the route is POST-only and the
  schema has no subscriptions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 15:15:31 +00:00
adamfandClaude Opus 5.5 223c8ae35a Move Garage and garage-webui to stpcore
Test and deploy / test (push) Successful in 18s
Test and deploy / deploy (push) Successful in 30s
Garage now runs on the stpcore LXC (adamf/stpcore), the shared core
other stacks depend on. caddy, backend and usaco pin the name `garage`
to it with GARAGE_UPSTREAM; /garage/ goes to stpcore's Caddy with
X-Core-Token. The disk fallback for /uploads/ is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:32:33 +00:00
adamfandClaude Opus 5.5 d0ff2e125b Format claude.py
Test and deploy / deploy (push) Has been cancelled
Test and deploy / test (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:17:38 +00:00
adamfandClaude Opus 5.5 705804c503 Renovate: also update stppriv
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:17:38 +00:00
adamfandClaude Opus 5.5 eadbc4fac3 Let canvas boxes go left of the canvas edge
Test and deploy / test (push) Successful in 29s
Test and deploy / deploy (push) Successful in 13s
The canvas is centred, so on wide screens there is margin to its left
that boxes could not be dragged into: x was clamped to 0 in the drag
geometry, the arrow-key nudge and validateBox. Only y stays clamped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:14:46 +00:00
adamfandClaude Opus 5.5 41d8e70050 Docs: stppriv uses this site's admin session; jobs DB is gone
Test and deploy / test (push) Successful in 22s
Test and deploy / deploy (push) Successful in 19s
The job tracker's database and role were dropped from this Postgres
after moving to stppriv. stppriv gates its tools with this site's admin
session rather than Cloudflare Access.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:09:55 +00:00
adamfandClaude Opus 5.5 94a6abba97 Move the notes editor and job tracker to stppriv
Test and deploy / test (push) Successful in 31s
Test and deploy / deploy (push) Successful in 27s
The SilverBullet editor and the job tracker now run on their own LXC
(adamf/stppriv) at priv.<DOMAIN>, behind Cloudflare Access. Here:

- silverbullet and jobs services removed; /sb/, /jobs/ and the old
  /cv/jobs, /cv/leads and userscript URLs 301 to priv.<DOMAIN>
- silverbullet-git runs with SYNC_MODE=pull: stppriv is the vault's only
  writer. The backend's vault mount is read-only.
- jobs env vars, dev overrides and docs removed; edge_test.sh checks
  the new redirects

Merge only after stppriv serves /sb/ and /jobs/ and the jobs data has
been moved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:53:48 +00:00
adamfandClaude Opus 5.5 65f2408ad4 Caddy: let stppriv's admin gate skip the api rate limit
stppriv's Caddy asks /api/auth/validate-admin for every request it
gates, all from its one LAN IP, which would exhaust the 30/s per-IP api
bucket on a SilverBullet page load. Requests from STPPRIV_LAN_IP to that
one path go straight to the backend. Public traffic always arrives from
cloudflared's address, so it cannot match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:53:41 +00:00
adamf 46f06a033b Login: follow a redirect back to priv.<domain>
stppriv's admin gate sends a signed-out visitor here with an absolute
https://priv.<domain>/... redirect. Only that exact host is allowed, so
it is not an open redirect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit c8c34d15483722cae145c9501823dbff74cf0c02)
2026-11-26 13:53:16 +00:00
adamfandClaude Opus 5.5 bfe2fe2782 Rename the repo to adamf/stpweb
Test and deploy / test (push) Successful in 1m29s
Test and deploy / deploy (push) Successful in 2s
Point CI, Renovate, the CV links, tests and docs at adamf/stpweb and
the deploy folder at ~/deploy/stpweb. Pin the Compose project name to
web_server so the existing volumes and network keep their names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:54:30 +00:00
adamfandClaude Opus 5.5 4530cb8dc4 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]>
2026-11-24 20:49:03 +00:00
adamf effddd2794 Update README.md
Test and deploy / test (push) Successful in 22s
Test and deploy / deploy (push) Successful in 24s
2026-11-24 17:31:54 +00:00
adamfandClaude Opus 5.5 ed87d04e04 Reach Gitea as git.DOMAIN on the LAN and drop the forwarder
Test and deploy / test (push) Has been cancelled
Test and deploy / deploy (push) Has been cancelled
Everything on stpvm now reaches the Gitea LXC by its own name, GITEA_HOST
(git.DOMAIN), pinned to its LAN IP: by extra_hosts in caddy, backend, usaco
and silverbullet-git, and by /etc/hosts on the host for the runner, CI and
Renovate. Public DNS for that name is Cloudflare, which only carries HTTPS,
so the pin is what makes :3000 and :2222 work. The haproxy forwarder that
kept localhost:3000/2222 working is gone, so stpvm no longer publishes
those ports. The deploy and Renovate workflows and the runner script use
the new name; the docs and the rollback notes follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:28:58 +00:00
adamfandClaude Opus 5.5 180f6ac8b8 Redirect /gitea/ to git.DOMAIN instead of proxying Gitea
Test and deploy / test (push) Successful in 21s
Test and deploy / deploy (push) Successful in 8s
Gitea's ROOT_URL is now https://git.DOMAIN/, served by the Gitea LXC's own
tunnel, so Caddy stops proxying /gitea/ and 301s every /gitea/* URL there
with the prefix dropped and the query kept (CV links, HTTPS clones,
bookmarks). The admin gate on Gitea's commit-history views goes with the
proxy; on git.DOMAIN they are public by choice. The registry at the apex's
/v2/ is still proxied. edge_test.sh checks the redirects instead of the
gate, and the docs and architecture diagrams follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:21:13 +00:00
adamfandClaude Opus 5.5 bb83c6bb03 Move gitea/ to its own repo, adamf/stpgit
Test and deploy / test (push) Successful in 21s
Test and deploy / deploy (push) Successful in 13s
The Gitea LXC's compose file, entrypoint, app.ini template and env example
now live in adamf/stpgit, which the LXC checks out instead of this repo.
What stays here is stpvm's side: the haproxy forwarder, renamed to
gitea-forwarder/haproxy.cfg, and a copy of the entrypoint in
.deprecated/gitea/ so the stpvm rollback does not depend on the new repo.
Renovate now also covers adamf/stpgit, and the docs point there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 16:52:55 +00:00
adamfandClaude Opus 5.5 fc777ba8b2 Add a cloudflared connector for git.DOMAIN on the Gitea LXC
Test and deploy / test (push) Successful in 21s
Test and deploy / deploy (push) Successful in 2s
Gitea gets its own remotely managed Cloudflare tunnel, run beside it on the
LXC, so public HTTPS for git.DOMAIN no longer has to pass through stpvm. It is
a separate tunnel from the site's, since a tunnel's connectors share all its
hostnames. It sits behind the `tunnel` profile until git.DOMAIN is the
canonical address, so a routine `docker compose up -d` does not publish it
early.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 16:33:42 +00:00
adamfandClaude Opus 5.5 31b84b06d4 Keep the pre-move Gitea in .deprecated/gitea as the rollback
Test and deploy / test (push) Successful in 21s
Test and deploy / deploy (push) Successful in 2s
The old stpvm service is kept as a compose override with its state
mounts pointed at .deprecated/gitea/, where the pre-move data now lives
(gitignored), so rolling back is one layered 'up' rather than a revert.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 16:01:23 +00:00
adamfandClaude Opus 5.5 10606f4c77 Move Gitea to its own LXC; keep a forwarder on stpvm
Test and deploy / test (push) Successful in 17s
Test and deploy / deploy (push) Successful in 2s
Gitea (git, Actions, the registry) now runs from gitea/docker-compose.yml
on a separate Proxmox LXC with its own Postgres, deployed by hand. The
stack's gitea service becomes an haproxy TCP forwarder from stpvm's 3000
and 2222 to the LXC (GITEA_UPSTREAM), under the same container name, so
Caddy, the backend feed, usaco, the runner, Renovate and every repo's CI
keep their addresses. Webhooks from the LXC reach Caddy over the LAN.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 15:42:44 +00:00
241 changed files with 1968 additions and 6348 deletions
+35
View File
@@ -49,3 +49,38 @@ host, valid until 2027-01-20.
To bring them back: revert the commit that moved them here and then `daa2a46`; To bring them back: revert the commit that moved them here and then `daa2a46`;
DEPLOYMENT.md §7 ("Roll back to nginx") has the commands. DEPLOYMENT.md §7 ("Roll back to nginx") has the commands.
## gitea/
Gitea as it ran inside this stack on stpvm until 2026-11-24, when it moved to
its own Proxmox LXC (`stpgit`, run from the `adamf/stpgit` repo) and stpvm's
`gitea` service became a forwarder to it.
- `docker-compose.gitea.yml` — the old service, with its state mounts
repointed at this directory.
- `entrypoint.sh` — its app.ini-seeding wrapper, copied here when `gitea/`
moved to its own repo, so the rollback does not depend on that repo.
- `data/` and `config/app.ini` (gitignored, on stpvm only) — the pre-move
copy of the repositories and the live config, moved here from `gitea/`.
Gitea's pre-move database is still the `gitea` database in stpvm's `db`.
To bring it back on stpvm: stop Gitea on stpgit, copy anything pushed since
the move back (its `data/`, and a `pg_dump` of `gitea-db` restored into
`db`'s `gitea` database), then
`docker compose -f docker-compose.yml -f .deprecated/gitea/docker-compose.gitea.yml up -d gitea`.
The service still reads `POSTGRES_GITEA_DB` and the three `GITEA_*`
secrets from `.env`; stpvm's `.env` still has them, so keep them there until
this copy is deleted. Delete `data/`, `config/app.ini` and the old database once the LXC has run
cleanly for a few weeks (from about 2026-12-08).
Since later on 2026-11-24 the stack has no `gitea` service at all (the
forwarder is gone) and Gitea's address is `git.<DOMAIN>`, so a rollback
also needs: `GITEA_HOST=gitea` in stpvm's `.env` (the containers'
`extra_hosts` pin then becomes harmless), the `/gitea/` proxy route back in
`caddy/routes.caddy` (revert `180f6ac`), `ROOT_URL` back to
`https://<DOMAIN>/gitea/` in `config/app.ini` here, and the CI remotes,
`.runner`'s address and Renovate's endpoint back to `localhost`.
The laptop's own leftovers (an old dev `gitea/data` and `app.ini`, and a
stale `gitea-runner/.runner`) are under `dev-leftovers/` here, also
gitignored, and can simply be deleted.
@@ -0,0 +1,84 @@
# =============================================================================
# .deprecated/gitea/docker-compose.gitea.yml — Gitea as it ran on stpvm until
# 2026-11-24, kept as the rollback from the move to its own LXC.
#
# STATUS: not live. Gitea runs on stpgit (the adamf/stpgit repo); stpvm's
# `gitea` service is an haproxy forwarder to it.
#
# This is the old service verbatim except for the two state mounts, which now
# point at the pre-move copy moved in beside this file (gitignored). Layered
# over docker-compose.yml it replaces the forwarder under the same name;
# compose merges the forwarder's GITEA_UPSTREAM and haproxy.cfg mount in
# too, and both are harmless to Gitea. Relative paths resolve against the
# project directory (the repo root), not this file. See README.md here and
# DEPLOYMENT.md §7, "Gitea LXC", for the full rollback.
# =============================================================================
services:
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
# main, executed by the act_runner that lives outside docker (gitea-runner/).
#
# ROOTLESS image: runs as an unprivileged user, so config lives in /etc/gitea
# and data in /var/lib/gitea (not /data as in the root image) — that is why
# the bind mounts look unlike most Gitea compose examples.
#
# The GITEA__section__KEY environment convention is Gitea's own: each maps to
# an app.ini key and overrides the file at runtime, which is how the secrets
# stay in .env instead of in the committed app.ini.template.
#
# entrypoint is overridden to run our wrapper (which materialises app.ini
# from the template on first boot) before handing off to Gitea's real
# docker-entrypoint.sh. dumb-init is kept as PID 1 for correct signal/zombie
# handling, exactly as the stock image does it.
gitea:
image: docker.gitea.com/gitea:1.25.4-rootless
container_name: "${GITEA_HOST}"
entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"]
networks:
- app-network
environment:
- GITEA__database__DB_TYPE=postgres
- GITEA__database__HOST=${POSTGRES_HOST}
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
- GITEA__database__USER=${POSTGRES_USER}
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
# The host's own name, which Gitea prints in SSH clone URLs. It lives in
# .env, not app.ini, so moving to another host is a one-line change;
# environment-to-ini writes it into the live app.ini on every start.
# localhost suits dev.
- GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
- GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
# Webhooks are refused to private addresses by default ("external").
# The usaco site's push hook targets http://usaco:8080 on the Docker
# network, so that one host is allowed by name.
- GITEA__webhook__ALLOWED_HOST_LIST=external,usaco
- USER_UID=1000
- USER_GID=1000
restart: always
volumes:
# PERSISTENT: repositories, LFS objects, avatars, sessions. The git data
# itself. (Gitea's *relational* data is in Postgres, not here.)
- ./.deprecated/gitea/data:/var/lib/gitea
# PERSISTENT: app.ini is generated into this host directory on first boot
# and then edited by Gitea itself, so it is gitignored — only the
# template is committed.
- ./.deprecated/gitea/config:/etc/gitea
# Mounted over the config dir so the wrapper script is available at the
# path the overridden entrypoint points at.
- ./.deprecated/gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
# Match the Pi's clock/zone so commit and CI timestamps are local time.
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
ports:
# 2222 = Gitea's *built-in* SSH server (the rootless image cannot use 22).
# Clones use ssh://git@host:2222/... — including the deploy workflow,
# which fetches from ssh://git@localhost:2222.
- "2222:2222"
# 3000 = HTTP, published directly as well as proxied at /gitea/, because
# the act_runner registers against http://localhost:3000 from the host.
- "3000:3000"
depends_on:
- db
@@ -17,15 +17,15 @@
# it to re-seed, which loses any UI-made settings). # it to re-seed, which loses any UI-made settings).
# #
# WHEN IT RUNS # WHEN IT RUNS
# Container start. docker-compose.yml overrides gitea's entrypoint to # Container start. gitea/docker-compose.yml overrides gitea's entrypoint to
# ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"], keeping dumb-init # ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"], keeping dumb-init
# as PID 1 for signal handling exactly as the stock image does, and inserting # as PID 1 for signal handling exactly as the stock image does, and inserting
# this script ahead of Gitea's own docker-entrypoint.sh. # this script ahead of Gitea's own docker-entrypoint.sh.
# #
# WHERE THE SECRETS ACTUALLY COME FROM # WHERE THE SECRETS ACTUALLY COME FROM
# Not from the template. docker-compose.yml passes GITEA__section__KEY # Not from the template. gitea/docker-compose.yml passes GITEA__section__KEY
# environment variables (database credentials, LFS_JWT_SECRET, # environment variables (database credentials, LFS_JWT_SECRET,
# INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from ./.env; Gitea applies those # INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from gitea/.env; Gitea applies those
# over whatever app.ini says. That is why the template can safely ship with # over whatever app.ini says. That is why the template can safely ship with
# those fields empty. # those fields empty.
# #
+16 -55
View File
@@ -16,13 +16,12 @@
# #
# Keep it in step with .env.example: a new variable goes in both. Settings that # Keep it in step with .env.example: a new variable goes in both. Settings that
# are not secrets (hosts, ports, timezone) keep .env.example's defaults; values # are not secrets (hosts, ports, timezone) keep .env.example's defaults; values
# a service parses (Garage's hex secrets, Gitea's base64 JWT keys, the S3 key # a service parses (the S3 key id and secret) are dummies in the exact shape it requires, or that service won't start.
# id) are dummies in the exact shape it requires, or that service won't start.
# #
# The dummy Postgres credentials only work on a database volume created with # The dummy Postgres credentials only work on a database volume created with
# them: an existing dbdata volume keeps whatever password it was initialised # them: an existing dbdata volume keeps whatever password it was initialised
# with. Only POSTGRES_DB is created on a fresh volume; the gitea, jobs and # with. Only POSTGRES_DB is created on a fresh volume; the tracker database
# tracker databases and roles still have to be created by hand (.env.example). # and role still have to be created by hand (.env.example).
# ============================================================================= # =============================================================================
# --- Postgres ---------------------------------------------------------------- # --- Postgres ----------------------------------------------------------------
@@ -31,55 +30,19 @@ POSTGRES_PASSWORD=dev-postgres-password
POSTGRES_DB=site POSTGRES_DB=site
POSTGRES_PORT=5432 POSTGRES_PORT=5432
POSTGRES_HOST=db POSTGRES_HOST=db
POSTGRES_JOBS_DB=jobs
POSTGRES_JOBS_USER=jobs
POSTGRES_JOBS_PASSWORD=dev-jobs-password
POSTGRES_TRACKER_DB=tracker POSTGRES_TRACKER_DB=tracker
POSTGRES_TRACKER_USER=tracker POSTGRES_TRACKER_USER=tracker
POSTGRES_TRACKER_PASSWORD=dev-tracker-password POSTGRES_TRACKER_PASSWORD=dev-tracker-password
# --- Gitea ------------------------------------------------------------------- # --- Gitea -------------------------------------------------------------------
# The two JWT secrets must decode as base64url of 32 bytes; these decode to # Dev has no Gitea: GITEA_HOST is pinned to a TEST-NET address that never
# the text "dev-only-not-a-secret-0123456789". # answers, so the home page's git feed is empty (and /gitea/ redirects to
GITEA_HOST=gitea # git.localhost, which goes nowhere).
GITEA_HOST=git.localhost
GITEA_PORT=3000 GITEA_PORT=3000
GITEA_INTERNAL_TOKEN=dev-gitea-internal-token GITEA_UPSTREAM=192.0.2.1
GITEA_LFS_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk
GITEA_OAUTH2_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk
POSTGRES_GITEA_DB=gitea
# Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is not part of the compose stack; nothing in dev reads these.
GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=dev-runner
GITEA_RUNNER_REGISTRATION_TOKEN=dev-dummy-runner-token
# --- Email ingest (job tracker) -----------------------------------------------
# Sync is off; the credentials are fake, so a manual sign-in fails at Microsoft.
EMAIL_BACKEND=graph
MSGRAPH_CLIENT_ID=00000000-0000-0000-0000-000000000000
MSGRAPH_CLIENT_SECRET=dev-dummy-msgraph-secret
MSGRAPH_TENANT_ID=consumers
MSGRAPH_REDIRECT_URI=http://localhost/jobs/api/email/callback
IMAP_HOST=imap.invalid
IMAP_PORT=993
IMAP_EMAIL=[email protected]
IMAP_PASSWORD=dev-dummy-imap-password
EMAIL_SYNC_INTERVAL=
EMAIL_SYNC_ENABLED=false
# --- Job leads (job tracker) --------------------------------------------------
# The timer is off; "Check now" still works for the keyless board sources.
JOB_LEADS_ENABLED=false
JOB_LEADS_INTERVAL=
ADZUNA_APP_ID=dev-dummy-adzuna-id
ADZUNA_APP_KEY=dev-dummy-adzuna-key
REED_API_KEY=dev-dummy-reed-key
# --- SilverBullet (notes) --------------------------------------------------- # --- SilverBullet (notes) ---------------------------------------------------
SILVERBULLET_HOST=silverbullet
SILVERBULLET_PORT=3000 SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_HOST=silverbullet-public
SILVERBULLET_PUBLIC_PORT=3000 SILVERBULLET_PUBLIC_PORT=3000
@@ -144,9 +107,6 @@ SEED_DB=true
PYTHON_HOST=python PYTHON_HOST=python
PYTHON_PORT=8000 PYTHON_PORT=8000
# --- Job tracker (/jobs/) -----------------------------------------------------
JOBS_IMAGE_TAG=
# --- USACO site (/usaco/) ------------------------------------------------------ # --- USACO site (/usaco/) ------------------------------------------------------
USACO_IMAGE_TAG= USACO_IMAGE_TAG=
USACO_GIT_TOKEN=dev-dummy-gitea-token USACO_GIT_TOKEN=dev-dummy-gitea-token
@@ -158,15 +118,16 @@ TRACKER_TZ=Europe/London
TFL_APP_KEY=dev-dummy-tfl-key TFL_APP_KEY=dev-dummy-tfl-key
# --- Garage object store (public /uploads/) ----------------------------------- # --- Garage object store (public /uploads/, on stpcore) -----------------------
# Shapes Garage enforces: 64 hex for the RPC secret, "GK" + 24 hex for the key # Uploads fall back to the `uploads` volume unless a dev stpcore is running
# id, 64 hex for the secret. Uploads fall back to the `uploads` volume until # with LAN_BIND=172.17.0.1 and these same dummy values (see stpcore's README).
# garage/bootstrap.sh has imported this key and created the bucket. # Shapes Garage enforces: "GK" + 24 hex for the key id, 64 hex for the secret.
GARAGE_RPC_SECRET=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef GARAGE_UPSTREAM=host-gateway
GARAGE_ADMIN_TOKEN=dev-garage-admin-token GARAGE_WEBUI_TOKEN=dev-garage-webui-token
S3_ACCESS_KEY_ID=GK0123456789abcdef01234567 S3_ACCESS_KEY_ID=GK0123456789abcdef01234567
S3_SECRET_ACCESS_KEY=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 S3_SECRET_ACCESS_KEY=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210
S3_ENDPOINT=http://garage:3900 S3_ENDPOINT=http://garage:3900
S3_REGION=garage S3_REGION=garage
S3_BUCKET=uploads S3_BUCKET=uploads
GARAGE_CAPACITY=1G
STPPRIV_LAN_IP=192.0.2.1
+55 -124
View File
@@ -8,8 +8,8 @@
# 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. backend, db and icecast2 do this. # variables inside that container. backend, db and icecast2 do this.
# The `python` and `jobs` services deliberately do neither wholesale — each # The `python` service deliberately does neither wholesale — each
# uses an explicit `environment:` allow-list, so neither sees the site's # uses an explicit `environment:` allow-list, so it never 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.
# #
# HOW TO USE # HOW TO USE
@@ -20,7 +20,7 @@
# #
# ADDING A VARIABLE # ADDING A VARIABLE
# Add it to .env.dev as well, with a dummy value, so the dev stack keeps # Add it to .env.dev as well, with a dummy value, so the dev stack keeps
# starting. If the python or jobs service reads it, add it to that service's # starting. If the python service reads it, add it to that service's
# `environment:` list in docker-compose.yml too, or the container never # `environment:` list in docker-compose.yml too, or the container never
# receives it. # receives it.
# #
@@ -33,107 +33,40 @@
# ============================================================================= # =============================================================================
# --- Postgres ---------------------------------------------------------------- # --- Postgres ----------------------------------------------------------------
# One instance, four databases: POSTGRES_DB for the Go backend, # One instance, two databases: POSTGRES_DB for the Go backend and
# POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker and # POSTGRES_TRACKER_DB for the activity tracker (with its own role). The job
# POSTGRES_TRACKER_DB for the activity tracker (each of the last two with its # tracker and Gitea have their own Postgres on stppriv and stpgit. Only
# own role). Only POSTGRES_DB is auto-created on first init; the others must # POSTGRES_DB is auto-created on first init; the tracker database must be
# be created by hand on a fresh volume (the job-tracker and ccp READMEs have # created by hand on a fresh volume (the ccp README has the commands).
# the commands).
# POSTGRES_HOST doubles as the db container's name. # POSTGRES_HOST doubles as the db container's name.
POSTGRES_USER= POSTGRES_USER=
POSTGRES_PASSWORD= POSTGRES_PASSWORD=
POSTGRES_DB= POSTGRES_DB=
POSTGRES_PORT=5432 POSTGRES_PORT=5432
POSTGRES_HOST=db POSTGRES_HOST=db
POSTGRES_JOBS_DB=jobs
POSTGRES_JOBS_USER=jobs
POSTGRES_JOBS_PASSWORD=
POSTGRES_TRACKER_DB=tracker POSTGRES_TRACKER_DB=tracker
POSTGRES_TRACKER_USER=tracker POSTGRES_TRACKER_USER=tracker
POSTGRES_TRACKER_PASSWORD= POSTGRES_TRACKER_PASSWORD=
# --- Gitea ------------------------------------------------------------------- # --- Gitea -------------------------------------------------------------------
# GITEA_HOST is the container name AND the Caddy upstream host. # Gitea runs in its own LXC (the adamf/stpgit repo, whose variables are in its
# The three secrets below are passed as GITEA__section__KEY overrides so the # .env.example); this stack has no Gitea container. GITEA_HOST is its public
# committed app.ini.template can keep those fields blank. Generate each as a # name, used on its plain-HTTP port GITEA_PORT by Caddy's /v2/, the backend's
# long random hex string. # feed and usaco, and as the SSH host for silverbullet-git. GITEA_UPSTREAM is
GITEA_HOST=gitea # the LXC's LAN IP, which those containers pin GITEA_HOST to (extra_hosts), so
# the hop stays on the LAN instead of going to Cloudflare. On the host itself
# (the runner, CI, Renovate) the same pin is a line in /etc/hosts.
GITEA_HOST=git.adam-french.co.uk
GITEA_PORT=3000 GITEA_PORT=3000
GITEA_INTERNAL_TOKEN= GITEA_UPSTREAM=
GITEA_LFS_JWT_SECRET=
GITEA_OAUTH2_JWT_SECRET=
POSTGRES_GITEA_DB=gitea
# The host's Tailscale MagicDNS name (e.g. stpvm.tailf20278.ts.net), shown in
# Gitea's SSH clone URLs. Not the public domain: 2222 is reachable only over
# the tailnet. Becomes Gitea's SSH_DOMAIN and DOMAIN. Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
# The registration token is SINGLE-USE: it is exchanged for a permanent
# identity in gitea-runner/.runner on first registration, after which this
# value is ignored. Mint it in Site Administration -> Actions -> Runners.
GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=pi-runner
GITEA_RUNNER_REGISTRATION_TOKEN=
# --- Email ingest (job tracker) -----------------------------------------------
# EMAIL_BACKEND selects the mail source: "graph" (Microsoft Graph API, OAuth)
# or "imap" (fallback; Microsoft has retired IMAP basic auth for outlook.com,
# so imap+app-password only works with non-Microsoft providers like Gmail).
# For "graph": register an Entra "app registration" for a personal Microsoft
# account at azure.microsoft.com > Microsoft Entra ID > App registrations
# (default tenant = "consumers"); add a delegated Mail.Read permission with
# admin/user consent, and create a client secret. Redirect URI type "Web",
# value must live behind the site's real HTTPS origin, e.g.
# https://<YOUR_DOMAIN>/jobs/api/email/callback (served by the job tracker,
# which exchanges the code there). TenantID must be "consumers" for a personal
# outlook.com account.
# The tracker's Settings page (/jobs/settings) shows the authorisation link
# until you sign in; the refresh token is persisted to
# jobs-data/msgraph_token.json.
# OAuth flow reference: https://learn.microsoft.com/en-us/graph/auth-v2-user
EMAIL_BACKEND=
MSGRAPH_CLIENT_ID=
MSGRAPH_CLIENT_SECRET=
MSGRAPH_TENANT_ID=consumers
MSGRAPH_REDIRECT_URI=
# IMAP_PASSWORD should be an app-specific password, not the account password.
# Only read when EMAIL_BACKEND=imap.
IMAP_HOST=
IMAP_PORT=993
IMAP_EMAIL=
IMAP_PASSWORD=
EMAIL_SYNC_INTERVAL=
EMAIL_SYNC_ENABLED=
# --- Job leads (job tracker) --------------------------------------------------
# The lead fetcher polls the sources listed on /jobs/leads and files new
# postings in the leads inbox. JOB_LEADS_ENABLED=true runs it on a timer;
# "Check now" on that page works whether or not it is set. JOB_LEADS_INTERVAL
# is a Go duration (default 6h). Scoring uses CLAUDE_API_KEY, above.
# The board sources (Greenhouse, Lever, Ashby) need no key. The two search
# sources do, both free:
# Adzuna: https://developer.adzuna.com/ (an application id and a key)
# Reed: https://www.reed.co.uk/developers/jobseeker
# A search source whose key is blank reports that on the page; nothing else
# is affected.
JOB_LEADS_ENABLED=
JOB_LEADS_INTERVAL=
ADZUNA_APP_ID=
ADZUNA_APP_KEY=
REED_API_KEY=
# --- SilverBullet (notes) --------------------------------------------------- # --- SilverBullet (notes) ---------------------------------------------------
# Two instances over the same vault: the admin-only editor at /sb/, and the # The public read-only notes site at /notes/. The editor, and the vault's only
# public read-only notes site at /notes/ (which replaced Quartz). All four # writer, is stppriv (priv.DOMAIN/sb/); silverbullet-git here only pulls.
# default in docker-compose.yml (the caddy service's list), so they can be left # Both default in docker-compose.yml.
# blank.
SILVERBULLET_HOST=silverbullet
SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_HOST=silverbullet-public
SILVERBULLET_PUBLIC_PORT=3000 SILVERBULLET_PUBLIC_PORT=3000
# Seconds between notes commit/push cycles (default 300). # Seconds between notes pulls (default 300).
SILVERBULLET_GIT_INTERVAL= SILVERBULLET_GIT_INTERVAL=
# --- Go backend -------------------------------------------------------------- # --- Go backend --------------------------------------------------------------
@@ -148,8 +81,8 @@ BACKEND_SECRET=
BACKEND_ENDPOINT=/api BACKEND_ENDPOINT=/api
# --- Obsidian vault ---------------------------------------------------------- # --- Obsidian vault ----------------------------------------------------------
# HOST path, interpolated straight into the bind mounts: read-write into the # HOST path, interpolated straight into the bind mounts: read-write into
# backend, silverbullet and silverbullet-git, read-only into # silverbullet-git (which pulls it), read-only into the backend and
# silverbullet-public. Must be an absolute path that exists on the host or the # silverbullet-public. Must be an absolute path that exists on the host or the
# stack will not start. # stack will not start.
OBSIDIAN_DIR= OBSIDIAN_DIR=
@@ -206,8 +139,8 @@ CLOUDFLARE_DNS_API_TOKEN=
# --- Third-party API keys (backend) ------------------------------------------ # --- Third-party API keys (backend) ------------------------------------------
# CLAUDE_API_KEY is used by the python service, which makes the main site's # CLAUDE_API_KEY is used by the python service, which makes the main site's
# Claude calls: the rowing photo reader, the job posting reader and the email # Claude calls: the rowing photo reader, the job posting reader and the email
# pipeline's classifier. The backend no longer calls Claude itself. The jobs # pipeline's classifier. The backend no longer calls Claude itself. The usaco
# and usaco containers get the same key for their own calls. # container gets the same key for its own calls.
CLAUDE_API_KEY= CLAUDE_API_KEY=
# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5 # Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5
# (the default when blank) or claude-opus-5-5. Recreate the python service # (the default when blank) or claude-opus-5-5. Recreate the python service
@@ -225,12 +158,6 @@ SEED_DB=
PYTHON_HOST=python PYTHON_HOST=python
PYTHON_PORT=8000 PYTHON_PORT=8000
# --- Job tracker (/jobs/) -----------------------------------------------------
# An image built and published by the job-tracker repo's CI. Blank runs
# :latest; set a commit sha to pin. Changing it needs
# `docker compose pull jobs && docker compose up -d jobs`.
JOBS_IMAGE_TAG=
# --- USACO site (/usaco/) ------------------------------------------------------ # --- USACO site (/usaco/) ------------------------------------------------------
# An image built and published by the usaco repo's CI. Blank runs :latest; set # An image built and published by the usaco repo's CI. Blank runs :latest; set
# a commit sha to pin. Changing it needs # a commit sha to pin. Changing it needs
@@ -261,13 +188,12 @@ USACO_CLAUDE_MONTHLY_BUDGET=
# Claude cannot take audio, so this OpenAI key transcribes it (whisper-1, # Claude cannot take audio, so this OpenAI key transcribes it (whisper-1,
# about $0.006 a minute). Blank turns reviews off. # about $0.006 a minute). Blank turns reviews off.
USACO_OPENAI_API_KEY= USACO_OPENAI_API_KEY=
# Optional: keep the recordings for playback in a PRIVATE Garage bucket, # Optional: keep the recordings for playback in a PRIVATE Garage bucket
# never `uploads` (that one is served publicly at /uploads/). Its own key, # (`usaco-audio` on stpcore), never `uploads` (that one is served publicly at
# same shapes as S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY above. With the # /uploads/). Its own key, same shapes as S3_ACCESS_KEY_ID /
# key blank the recordings are thrown away once transcribed. One-off setup: # S3_SECRET_ACCESS_KEY below. With the key blank the recordings are thrown
# docker compose exec -T garage /garage bucket create usaco-audio # away once transcribed. Put the same pair in stpcore's .env and run its
# docker compose exec -T garage /garage key import -n usaco-site --yes "$USACO_S3_ACCESS_KEY_ID" "$USACO_S3_SECRET_ACCESS_KEY" # garage/bootstrap.sh, which creates the bucket and imports the key.
# docker compose exec -T garage /garage bucket allow --read --write usaco-audio --key "$USACO_S3_ACCESS_KEY_ID"
USACO_S3_ACCESS_KEY_ID= USACO_S3_ACCESS_KEY_ID=
USACO_S3_SECRET_ACCESS_KEY= USACO_S3_SECRET_ACCESS_KEY=
@@ -291,6 +217,12 @@ RECEIPT_WEB_UPSTREAM=100.107.152.119:8765
# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`. # `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`.
RECEIPT_WEB_TOKEN= RECEIPT_WEB_TOKEN=
# --- stppriv (priv.DOMAIN) ---------------------------------------------------
# The private-tools LXC's LAN IP. Its Caddy asks /api/auth/validate-admin
# directly, not via the tunnel, and requests from this IP skip the api rate
# limit. Blank matches nothing.
STPPRIV_LAN_IP=
# --- Partner Radar (radar.DOMAIN) ---------------------------------------------- # --- Partner Radar (radar.DOMAIN) ----------------------------------------------
# A separate compose project on this host (adamf/cto, `make stpvm`), whose web # A separate compose project on this host (adamf/cto, `make stpvm`), whose web
# container joins app-network as `radar-web`. Only set this to point # container joins app-network as `radar-web`. Only set this to point
@@ -300,30 +232,29 @@ 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
TFL_APP_KEY= TFL_APP_KEY=
# --- Garage object store (public /uploads/) ----------------------------------- # --- Garage object store (public /uploads/, on stpcore) -----------------------
# See garage/garage.toml and DEPLOYMENT.md ("Garage"). Everything here is # Garage runs on the stpcore LXC (adamf/stpcore); its README is the runbook
# optional for the site to run: with S3_ENDPOINT blank the backend keeps # and its .env holds Garage's own secrets. Everything here is optional for
# writing uploads to the `uploads` volume exactly as before. # the site to run: with S3_ENDPOINT blank, or stpcore down, the backend
# writes uploads to the `uploads` volume and Caddy serves them from there.
# #
# Garage's own secrets, passed to the garage and garage-webui containers. # stpcore's LAN IP: the name `garage` is pinned to it in caddy, backend and
# Generate each with `openssl rand -hex 32`. The RPC secret must never change # usaco. `host-gateway` in dev. Blank means 127.0.0.1, which fails fast.
# once the node has data; the admin token unlocks garage-webui's whole API. GARAGE_UPSTREAM=
GARAGE_RPC_SECRET= # Shared secret Caddy adds as X-Core-Token on /garage/, after the admin
GARAGE_ADMIN_TOKEN= # gate; the same value as GARAGE_WEBUI_TOKEN in stpcore's .env.
# The backend's S3 access, imported into Garage by garage/bootstrap.sh. # `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`.
# Garage only accepts this shape: GARAGE_WEBUI_TOKEN=
# The backend's S3 key, the same values as in stpcore's .env (whose
# bootstrap.sh imports it). Garage only accepts this shape:
# S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12)) # S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12))
# S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32) # S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32)
S3_ACCESS_KEY_ID= S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY= S3_SECRET_ACCESS_KEY=
# Blank keeps uploads on disk. Set to http://garage:3900 (after running # Blank keeps uploads on disk. http://garage:3900 stores new public uploads
# garage/bootstrap.sh) to store new public uploads in the bucket; recreate the # in the bucket; recreate the backend after changing it. If a write to Garage
# backend after changing it. If a write to Garage fails the backend logs it and # fails the backend logs it and writes to disk instead.
# 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 stpcore's garage.toml and bootstrap.sh.
S3_REGION=garage S3_REGION=garage
S3_BUCKET=uploads S3_BUCKET=uploads
# Optional, bootstrap.sh only: the node's capacity in the layout. With one node
# it only has to be non-zero; it is not a quota. Default 20G.
GARAGE_CAPACITY=
+41 -101
View File
@@ -1,46 +1,11 @@
# ============================================================================= # `test` runs on every push, on the build VM (stpbuild, label `build`);
# deploy.yaml — test every push; deploy pushes to main that pass. # `deploy` runs for main only after it passes, on stpvm (`self-hosted`),
# # since it recreates the stack there.
# TWO JOBS # The runner is in host mode with only git and docker on the host, so Go and
# test runs on every push, to any branch: `go vet` + `go test` for the # Python run in containers pinned to the same images as their Dockerfiles
# backend and pytest for the Python service. These are the same # (bump together), and checkout is plain git rather than actions/checkout.
# checks as `make check-backend` and `make check-python`. # The Vue build isn't tested here: a failed image build in `up --build`
# deploy runs only for refs/heads/main, and only if `test` passed # aborts before any container is replaced.
# (`needs: test`). Before this gate existed every push to main went
# straight to the live site.
#
# WHERE THIS RUNS, AND WHAT THAT RULES OUT
# A self-hosted act_runner on the Pi itself, in HOST mode (see
# gitea-runner/run.sh): steps are shell commands on the Pi, not in a job
# container. So:
# - No host toolchains are assumed. The Pi is known to have git and docker
# and nothing else; Go and Python run inside `docker run` containers
# pinned to the same base images as backend/Dockerfile (golang:1.26) and
# python/Dockerfile (python:3.12-slim). Bump them together.
# - No `actions/checkout`. It is a JavaScript action and would need Node on
# the host. The source is fetched with plain git instead, from the same
# local Gitea SSH remote the deploy step has always used.
#
# THE LIVE DIRECTORY IS NOT TOUCHED UNTIL TESTS PASS
# The site runs out of /home/adamf/deploy/web_server. The test job never
# goes near it: it fetches into a separate bare cache repo and exports the
# pushed commit to a scratch directory. Only the deploy job, after `test`
# is green, does the `git reset --hard` there.
#
# NOT TESTED HERE: THE VUE BUILD
# Deliberately skipped. `docker compose up --build` in the deploy job
# already runs the full frontend build (npm ci + vite) while building the
# vue image, and a failed image build aborts `up` BEFORE any container is
# replaced, so the old site keeps serving. Building it a second time here
# would cost the Pi several minutes per push to learn nothing new. The same
# reasoning does not hold for Go and Python: their images build fine with
# failing tests, which is exactly why those are gated here.
#
# NO pull_request TRIGGER
# `push` with no branch filter already covers every branch, including the
# head branch of any PR in this repo, so adding pull_request would run the
# suite twice per push on a machine with little CPU to spare.
# =============================================================================
name: Test and deploy name: Test and deploy
on: on:
@@ -48,22 +13,20 @@ on:
jobs: jobs:
test: test:
runs-on: self-hosted runs-on: build
env: env:
# The commit and ref this push delivered. Passed through env rather # Via env so a branch name is never parsed as shell.
# than interpolated into the scripts so a branch name can never be
# parsed as shell.
SHA: ${{ github.sha }} SHA: ${{ github.sha }}
REF: ${{ github.ref }} REF: ${{ github.ref }}
REMOTE: ssh://git@localhost:2222/adamf/web_server.git # Over HTTP with the job's own token (read access to this repo while
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no" # the job runs), so the runner needs no SSH key or Gitea user.
# Bare repo kept between runs so each fetch is incremental (the REMOTE: http://git.adam-french.co.uk:3000/adamf/stpweb.git
# history is ~140MB; a fresh clone per push would be slow on the GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
# Pi's SD card). Lives outside the deploy directory on purpose. # Kept between runs so fetches are incremental.
CACHE: /home/adamf/.cache/web_server-ci/repo.git CACHE: /home/adamf/.cache/stpweb-ci/repo.git
# This run's source tree, exported from the cache and removed in # Per run, not just per commit: the build runner takes two jobs at
# the last step. Keyed by commit so two runs cannot share a tree. # once, and the same commit pushed to two branches runs twice.
SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }} SRC: /home/adamf/.cache/stpweb-ci/src-${{ github.sha }}-${{ github.run_id }}
steps: steps:
- name: Export the pushed commit to a scratch directory - name: Export the pushed commit to a scratch directory
shell: bash shell: bash
@@ -71,33 +34,24 @@ jobs:
set -eu set -eu
mkdir -p "$(dirname "$CACHE")" mkdir -p "$(dirname "$CACHE")"
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE" [ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
# Fetch the pushed ref, then export the exact pushed commit. # $SHA, not FETCH_HEAD: test this run's commit even if the
# Using $SHA rather than FETCH_HEAD means that if the branch # branch has moved on.
# has moved on since this run was queued we still test the # The job's token as a Basic auth header, passed via env rather
# commit this run is about, not a newer one. # than -c so it never shows in the process list.
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF" auth=$(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)
GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: Basic $auth" \
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
rm -rf "$SRC" rm -rf "$SRC"
mkdir -p "$SRC" mkdir -p "$SRC"
# `git archive` gives a clean tree of tracked files only: no
# .git, and nothing left over from an earlier run.
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC" git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
# Do not rely on the shell having pipefail: if the archive # In case the shell lacks pipefail.
# half failed, make sure that is noticed here.
test -f "$SRC/backend/go.mod" test -f "$SRC/backend/go.mod"
test -f "$SRC/python/requirements-dev.txt" test -f "$SRC/python/requirements-dev.txt"
echo "Exported $SHA ($REF) to $SRC" echo "Exported $SHA ($REF) to $SRC"
# The whole repo is mounted read-only. Tests write only to # Read-only so root in the container can't leave files the
# t.TempDir(), and a read-only mount means the container (root) # clean-up step can't delete. The named volumes are Go caches.
# cannot leave root-owned files in $SRC that the clean-up step,
# running as the runner user, could not delete.
#
# The two named volumes are the Go module cache and build cache.
# Without them every run would re-download every dependency and
# recompile gorm, gin and gqlgen from scratch — minutes on a Pi.
# They survive `docker image prune` and the weekly maintenance
# job; `docker volume rm web_server_ci_gomod web_server_ci_gobuild`
# resets them if they ever go bad.
- name: Backend - go vet and go test - name: Backend - go vet and go test
shell: bash shell: bash
run: | run: |
@@ -105,17 +59,12 @@ jobs:
docker run --rm \ docker run --rm \
-v "$SRC":/src:ro \ -v "$SRC":/src:ro \
-w /src/backend \ -w /src/backend \
-v web_server_ci_gomod:/go/pkg/mod \ -v stpweb_ci_gomod:/go/pkg/mod \
-v web_server_ci_gobuild:/root/.cache/go-build \ -v stpweb_ci_gobuild:/root/.cache/go-build \
golang:1.26 \ golang:1.26 \
sh -c 'go vet ./... && go test ./...' sh -c 'go vet ./... && go test ./...'
# requirements-dev.txt pulls in requirements.txt plus pytest. The # Read-only source, so bytecode and the pytest cache are off.
# install is repeated every run (the container is thrown away) but
# the pip cache volume means it is unpacking cached wheels, not
# downloading. Read-only source for the same reason as above, so
# bytecode and the pytest cache are switched off rather than left
# to fail noisily.
- name: Python - pytest - name: Python - pytest
shell: bash shell: bash
run: | run: |
@@ -123,41 +72,33 @@ jobs:
docker run --rm \ docker run --rm \
-v "$SRC":/src:ro \ -v "$SRC":/src:ro \
-w /src/python \ -w /src/python \
-v web_server_ci_pip:/root/.cache/pip \ -v stpweb_ci_pip:/root/.cache/pip \
-e PYTHONDONTWRITEBYTECODE=1 \ -e PYTHONDONTWRITEBYTECODE=1 \
python:3.12-slim \ python:3.12-slim \
sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider' sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider'
# always(): a failed test must not leave a source tree behind per
# push. The cache repo is kept; only this run's export goes.
- name: Remove the scratch directory - name: Remove the scratch directory
if: always() if: always()
shell: bash shell: bash
run: rm -rf "$SRC" run: rm -rf "$SRC"
deploy: deploy:
# Both conditions matter: `needs` makes a red test job skip this one,
# and the `if` keeps pushes to other branches from deploying at all.
needs: test needs: test
if: github.ref == 'refs/heads/main' if: github.ref == 'refs/heads/main'
runs-on: self-hosted runs-on: self-hosted
steps: steps:
- name: Pull changes - name: Pull changes
working-directory: /home/adamf/deploy/web_server working-directory: /home/adamf/deploy/stpweb
env: env:
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no" GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
SHA: ${{ github.sha }} SHA: ${{ github.sha }}
shell: bash shell: bash
run: | run: |
set -eu set -eu
git config --global --add safe.directory /home/adamf/deploy/web_server git config --global --add safe.directory /home/adamf/deploy/stpweb
git fetch ssh://git@localhost:2222/adamf/web_server.git main git fetch ssh://git@git.adam-french.co.uk:2222/adamf/stpweb.git main
# Deploy only the commit the test job just passed. If main # Deploy only the tested commit; a newer main gets its own
# has moved on since this run started, FETCH_HEAD is a newer # run. This also stops a re-run rolling the site back.
# commit that THIS run never tested — stop, and let that
# commit's own run test and deploy it. Failing (rather than
# resetting to $SHA anyway) also means re-running an old run
# can never roll the site back to an old commit.
if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then
echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA." echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA."
echo "Not deploying: the run for the newer commit will." echo "Not deploying: the run for the newer commit will."
@@ -166,11 +107,10 @@ jobs:
git reset --hard FETCH_HEAD git reset --hard FETCH_HEAD
- name: Run docker compose up - name: Run docker compose up
working-directory: /home/adamf/deploy/web_server working-directory: /home/adamf/deploy/stpweb
env: env:
COMPOSE_BAKE: "false" COMPOSE_BAKE: "false"
# The lock is shared with maintenance.yaml, so a deploy and the # Shared with maintenance.yaml so the two never run compose at once.
# weekly rebuild cannot run compose at the same time.
run: flock .compose.lock docker compose up -d --build --remove-orphans run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker resources - name: Prune unused Docker resources
+6 -15
View File
@@ -2,9 +2,7 @@ name: Weekly Maintenance
on: on:
schedule: schedule:
# 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and # Restarts dockerd, so it runs when nobody is likely mid-edit.
# every container, so it runs when nobody is likely to be mid-edit;
# 01:00 kept catching late-night SilverBullet saves.
- cron: "0 5 * * 0" - cron: "0 5 * * 0"
workflow_dispatch: workflow_dispatch:
@@ -24,21 +22,14 @@ jobs:
- name: Autoremove obsolete packages - name: Autoremove obsolete packages
run: sudo apt-get -y autoremove --purge run: sudo apt-get -y autoremove --purge
# Both compose steps below take .compose.lock, the same flock # .compose.lock is shared with deploy.yaml, so two compose runs
# deploy.yaml holds while it runs compose. Without it this weekly # never race. Taken per step to keep deploys from waiting long.
# job could recreate containers while a deploy is mid-build, and
# two `compose up`s racing over the same project can each recreate
# a container the other just started. flock blocks until the other
# holder finishes, so the job waits rather than fails. The lock is
# taken per step, not across both: nothing needs pull and up to be
# atomic, and holding it for less time keeps a deploy from waiting
# behind a long pull.
- name: Pull latest base images - name: Pull latest base images
working-directory: /home/adamf/deploy/web_server working-directory: /home/adamf/deploy/stpweb
run: flock .compose.lock docker compose pull run: flock .compose.lock docker compose pull
- name: Rebuild and restart containers - name: Rebuild and restart containers
working-directory: /home/adamf/deploy/web_server working-directory: /home/adamf/deploy/stpweb
run: flock .compose.lock docker compose up -d --build --remove-orphans run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker images - name: Prune unused Docker images
@@ -49,7 +40,7 @@ jobs:
- name: Show running containers - name: Show running containers
run: docker compose ps run: docker compose ps
working-directory: /home/adamf/deploy/web_server working-directory: /home/adamf/deploy/stpweb
- name: Show disk usage after - name: Show disk usage after
run: df -h / run: df -h /
+10 -43
View File
@@ -1,53 +1,20 @@
# ============================================================================= # Weekly Renovate run (config in /renovate.json5), on the build VM (stpbuild,
# renovate.yaml — weekly dependency-update PRs, opened against this repo. # label `build`). --network host uses the
# # host's /etc/hosts pin to reach Gitea on the LAN, and RENOVATE_GIT_URL=endpoint
# Renovate stands in for Dependabot, which does not exist outside GitHub. What # stops it cloning via the public ROOT_URL. Secrets are passed as bare `-e NAME`
# it updates is configured in /renovate.json5; this file is only how it runs. # so they never appear in the process list. Gitea refuses secret names starting
# # GITHUB_, hence RENOVATE_GITHUB_COM_TOKEN.
# HOW IT RUNS
# The same host-mode act_runner as deploy.yaml, so (as there) nothing but
# git and docker is assumed on the host: Renovate runs from its own image.
# --network host lets the container reach Gitea on localhost:3000, the port
# the runner itself registers against, so this keeps working while Caddy or
# the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same reason:
# without it Renovate clones from the URL Gitea advertises, which is
# ROOT_URL — the public https://…/gitea/ path.
#
# WHAT HAPPENS AFTER
# Each update is pushed as a renovate/* branch, which triggers deploy.yaml's
# `test` job like any other push (and never its `deploy` job, which is
# main-only). Nothing is merged automatically: merging is deploying.
# Renovate also keeps a "Dependency Dashboard" issue open listing everything
# pending; ticking a box there is picked up on the next run, so run this
# workflow by hand (workflow_dispatch) to act on it sooner.
#
# THE TOKEN
# RENOVATE_TOKEN is a repo Actions secret: a Gitea access token for the
# account the PRs come from (a dedicated `renovate` user with write access
# to this repo, ideally), scopes read:user, read:organization,
# write:repository, write:issue.
# RENOVATE_GITHUB_COM_TOKEN is optional: any github.com token with no
# scopes. Without it Renovate is rate-limited by GitHub and leaves release
# notes out of the PRs. (Gitea refuses secret names starting GITHUB_, hence
# the prefix.) Both reach the container as `-e NAME` with no value, so they
# are copied from this step's env and never appear in the process list.
#
# The renovate/renovate:44 tag floats within the major (--pull always picks
# up the newest 44.x each week); Renovate itself proposes the next major via
# the regex manager in renovate.json5.
# =============================================================================
name: Renovate name: Renovate
on: on:
schedule: schedule:
# 04:00 UTC Monday: clear of the Sunday 05:00 maintenance rebuild, and # Clear of the Sunday maintenance rebuild.
# done before the working week so the PRs are waiting.
- cron: "0 4 * * 1" - cron: "0 4 * * 1"
workflow_dispatch: workflow_dispatch:
jobs: jobs:
renovate: renovate:
runs-on: self-hosted runs-on: build
steps: steps:
- name: Run Renovate - name: Run Renovate
shell: bash shell: bash
@@ -62,9 +29,9 @@ jobs:
fi fi
docker run --rm --pull always --network host \ docker run --rm --pull always --network host \
-e RENOVATE_PLATFORM=gitea \ -e RENOVATE_PLATFORM=gitea \
-e RENOVATE_ENDPOINT=http://localhost:3000/api/v1 \ -e RENOVATE_ENDPOINT=http://git.adam-french.co.uk:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \ -e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/web_server \ -e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv,adamf/stpcore,adamf/stprunner \
-e RENOVATE_TOKEN \ -e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \ -e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \ -e LOG_LEVEL=info \
+10 -4
View File
@@ -8,7 +8,6 @@ certbot/www
# Caddy's certificates, keys and ACME account (docker-compose.yml) # Caddy's certificates, keys and ACME account (docker-compose.yml)
caddy/data/ caddy/data/
backend/token/ backend/token/
jobs-data/
usaco-data/ usaco-data/
.env .env
.env.bak .env.bak
@@ -16,12 +15,19 @@ usaco-data/
# flock taken by the deploy and maintenance workflows around docker compose # flock taken by the deploy and maintenance workflows around docker compose
.compose.lock .compose.lock
gitea/data/* # Gitea's pre-move state, kept as the rollback (.deprecated/gitea/README)
gitea/config/app.ini .deprecated/gitea/data/
.deprecated/gitea/config/
.deprecated/gitea/dev-leftovers/
# Gitea runner # The old runner directory: gone from git, but still on stpvm holding the
# previous .runner credentials (runners are installed from adamf/stprunner)
gitea-runner/.runner gitea-runner/.runner
gitea-runner/act_runner gitea-runner/act_runner
gitea-runner/gitea-runner
gitea-runner/.runner.lock
# Old registrations: credentials, like .runner
gitea-runner/.runner.bak*
gitea-runner/nohup.out gitea-runner/nohup.out
# Python bytecode # Python bytecode
+10 -8
View File
@@ -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 serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. 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`. Uploads stay on disk unless a dev stpcore is also running (from that repo, with `LAN_BIND=172.17.0.1` and the same dummy keys as `.env.dev`), which `GARAGE_UPSTREAM=host-gateway` reaches.
### Full stack (production, HTTPS) ### Full stack (production, HTTPS)
@@ -59,13 +59,15 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
**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). **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. 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"). **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, `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/`; 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`. **Job tracker and notes editor** (on stppriv): the job tracker (`adamf/job-tracker`) and the SilverBullet editor run on their own LXC, from the `adamf/stppriv` repo, at `priv.<DOMAIN>`. stppriv's Caddy gates them with this site's admin session (the cookie is set for the parent domain), asking `/api/auth/validate-admin` over the LAN; requests from `STPPRIV_LAN_IP` to that path skip the api rate limit. Caddy here 301s `/sb/`, `/jobs/` and the old `/cv/jobs`, `/cv/leads` and userscript URLs there. stppriv is the notes vault's only writer; `silverbullet-git` here runs with `SYNC_MODE=pull` and feeds `/notes/`.
**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. **Gitea** (own repo, `adamf/stpgit`): git, Actions and the image registry (`<DOMAIN>/adamf/...`) run in their own Proxmox LXC since 2026-11-24, from the `adamf/stpgit` repo (this repo's `gitea/` directory until then) with their own Postgres (`gitea-db`) and `.env`, deployed by hand there and never by CI. Everything on stpvm reaches it as `GITEA_HOST` (`git.<DOMAIN>`, :3000 HTTP and :2222 SSH), pinned to the LXC's LAN IP (`GITEA_UPSTREAM`) by `extra_hosts` in containers and `/etc/hosts` on the host; public DNS for that name is Cloudflare, which carries only HTTPS. There is no Gitea container or forwarder in this stack since 2026-11-24. stpvm keeps a gitea-runner (registered as `stpvm`, label `self-hosted`) for the jobs that touch the stack (deploys, maintenance); tests, image builds and Renovate run on the build VM `stpbuild` (Proxmox VM 123, 192.168.178.240, runner `stpbuild-runner`, label `build`) since 2026-11-26, which fetches over HTTP with each job's own `GITEA_TOKEN`. Both runners are installed from the `adamf/stprunner` repo (systemd, `hosts/<host>.env` per VM). See "Build VM" in `DEPLOYMENT.md` §7. Runbook: that repo's README, summarised in "Gitea LXC" in `DEPLOYMENT.md` §7.
**Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit <zone> <events> <window>`) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated at the edge because a crawler swarm hammers them; the branch views stay public. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7. **Uploads / Garage** (Garage itself on stpcore): 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 Garage (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). Garage and `garage-webui` are not in this stack: they run on the `stpcore` LXC, from the `adamf/stpcore` repo (the shared core other stacks depend on; its README is the runbook, including `garage/bootstrap.sh`), and the name `garage` is pinned to its LAN IP (`GARAGE_UPSTREAM`) by `extra_hosts` in `caddy`, `backend` and `usaco`. Caddy serves `/uploads/` from Garage's anonymous website endpoint (`garage:3902`) first and the volume second, so the bucket is the source of truth and a Garage or stpcore outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `/garage/` (admin-gated) proxies to stpcore's Caddy on `garage:3909`, adding `X-Core-Token` (`GARAGE_WEBUI_TOKEN`), which that Caddy requires before it forwards to garage-webui. A new consumer of the store gets its own key and bucket on stpcore and the same `extra_hosts` pin. "Garage" in `DEPLOYMENT.md` §7 covers this side.
**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 is not proxied any more: it lives at `git.<DOMAIN>` (its own tunnel, from the stpgit repo) and `/gitea/*` 301s there; only the registry at the apex's `/v2/` still goes through Caddy. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7.
## Backend Structure ## Backend Structure
@@ -93,12 +95,12 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
## Key Patterns ## Key Patterns
- **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types. - **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types.
- **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` (90 days, renewed on every refresh) as HTTP-only cookies (`backend/main.go`). `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. The admin flag is read from the user row on every request (`AuthenticateTokenWithClaims` overwrites the claim), so a demotion applies at once. `services.RequireSameOrigin` refuses any non-GET request whose `Origin` is not the apex or www, since SameSite=Lax lets sibling subdomains (radar., git.) send the cookies. 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. 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. - **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 reads must also be added to the `python` 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.
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows. - **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
@@ -114,7 +116,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, the edge's route order). Preserve these when editing; if you change the behaviour they describe, update them. - **Keep comments rare and short.** Code should explain itself through names and structure. Comment only a non-obvious *why* (a security boundary, an upstream quirk, an ordering constraint), in a line or two. No history, dates, migration notes or narration of what the code does: those belong in commit messages and the READMEs. If you change behaviour a comment describes, update or delete it.
- **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.
+189 -103
View File
@@ -13,8 +13,8 @@ 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: Caddy on 80/443, Gitea on Only two things are reachable from outside the host: Caddy on 80/443 and the
3000/2222, and the liquidsoap harbor port. Everything else is internal. Web liquidsoap harbor port. (Gitea, below, is on its own LXC.) 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.
@@ -25,29 +25,83 @@ dials out and publishes no port; see "Cloudflare Tunnel" in §3.
v v v v v v
+--------------+ +--------+ +-------------+ +--------------+ +--------+ +-------------+
| caddy | | gitea | | liquidsoap | | caddy | | gitea | | liquidsoap |
| (TLS, SPA, | | (git + | | harbor | | (TLS, SPA, | | (fwd | | harbor |
| reverse | | CI) | | (live DJ) | | reverse | | to | | (live DJ) |
| proxy) | +--------+ +------+------+ | proxy) | | LXC) | +------+------+
+------+-------+ | | | | +--------+ |
| | | +------+-------+ |
--------------------------------------------- | (same container | |
| | | | | | | as icecast2) --------------------------------------------- (same container
v v v v v v | | | | | | | | as icecast2)
/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | | v v v v v v |
backend icecast2 gitea sb sb-pub python | | /api/ /radio/ /v2/ /notes/ /py/ |
| ^ | | backend icecast2 gitea sb-pub python |
| | | | | ^ |
| +---------------------------------------|---------------+ | | |
| | | +-------------------------------------------------------+
+----------+--------------------------------------+ |
+----------+
v v
+------+ +------+
| db | postgres:16 | db | postgres:16
+------+ (app database + gitea database) +------+ (app database + the trackers' databases)
vue one-shot build container -> writes vue_dist volume -> caddy serves it vue one-shot build container -> writes vue_dist volume -> caddy serves it
``` ```
### Gitea runs in its own LXC
Gitea (git, Actions, the image registry) is not in this stack. It runs on a
separate Proxmox LXC, from its own repo (`adamf/stpgit`), with its own Postgres
(`gitea-db`); the runbook is that repo's README, summarised in "Gitea LXC" in §7.
Everything here reaches it by one name, `GITEA_HOST`
(`git.<DOMAIN>`), pinned to the LXC's LAN IP (`GITEA_UPSTREAM`): in
containers by `extra_hosts`, and on the host by a line in `/etc/hosts`. Public
DNS for that name points at Cloudflare, which carries only HTTPS, so without
the pin SSH and port 3000 would go nowhere. (Until 2026-11-24 an haproxy
forwarder here published 3000/2222 and everything used `localhost`.)
```
stpvm (pin: git.DOMAIN -> LAN IP) Gitea LXC (LAN IP)
caddy /v2/ (apex) ----+ +------------------+
backend feed ----------+--> git.DOMAIN:3000 --------> | gitea :3000 |
usaco pulls -----------+ | |
runner, Renovate git.DOMAIN:3000 (/etc/hosts) ----> | |
CI, silverbullet-git, obsidian git.DOMAIN:2222 ----> | :2222 |
| gitea-db |
usaco <-- caddy <-- https://www.DOMAIN/usaco/api/hooks/gitea --+ (webhook,
over the LAN)
```
A new machine or container that talks to Gitea needs the same pin, or a
`~/.ssh/config` entry pointing the name at the tailnet name `stpgit` for SSH.
### Garage runs on stpcore
Garage (the S3 object store behind `/uploads/`) and garage-webui are not in
this stack either. They run on the `stpcore` LXC, from `adamf/stpcore`, the
shared core every other stack depends on; its README is the runbook. The name
`garage` is pinned to that LXC's LAN IP (`GARAGE_UPSTREAM`) by `extra_hosts`
in `caddy`, `backend` and `usaco`, so the configs still say `garage:3900`
(S3), `garage:3902` (website) and `garage:3909` (stpcore's Caddy in front of
garage-webui, which wants the `X-Core-Token` this Caddy adds after the admin
gate). Nothing here depends on it being up: see "Garage" in §7.
```
stpvm (pin: garage -> stpcore LAN IP) stpcore LXC (LAN IP)
backend S3 PUT (uploads) ------+ +----------------------+
usaco S3 (usaco-audio) ------+--> garage:3900 ---> | garage :3900 S3 |
caddy /uploads/ -----------------> garage:3902 --> | :3902 web |
caddy /garage/ (+X-Core-Token) --> garage:3909 --> | caddy -> garage-webui|
+----------------------+
```
Gitea's public address is `https://git.<DOMAIN>/` (its `ROOT_URL`), served by
the LXC's own Cloudflare tunnel, not by this edge; Caddy only 301s the old
`/gitea/*` URLs there and still proxies the registry at the apex's `/v2/`.
The LXC is also on the tailnet, so a laptop can use its own name directly.
Deploys of this stack never touch Gitea.
### 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 |
@@ -55,23 +109,20 @@ backend icecast2 gitea sb sb-pub python | |
| caddy (the edge) | `caddy` | 80, 443 (fixed IP `172.28.255.251`) | everything below | **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-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 Caddy `forward_auth`; capture API and userscript public, bearer-token) | no |
| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by Caddy `forward_auth`; `/api/v1/` bearer/app-checked) | no | | 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** |
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no | | vue | `vue` | 5173 (dev only) | `/` (dev only) | 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 Caddy, 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 Caddy `forward_auth`; reads the Docker socket; on `dozzle-net`, shared only with Caddy) | 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 Caddy `forward_auth`; Caddy adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no |
| Partner Radar (adamf/cto, its own compose project) | `radar-web` (alias of that project's `web`, on app-network) | 80 | `radar.<DOMAIN>`, the whole host (its own login, no gate; zones `radar` and `radar_login`). Started from the cto checkout with `make stpvm`; 503 "offline" when that stack is down | no | | Partner Radar (adamf/cto, its own compose project) | `radar-web` (alias of that project's `web`, on app-network) | 80 | `radar.<DOMAIN>`, the whole host (its own login, no gate; zones `radar` and `radar_login`). Started from the cto checkout with `make stpvm`; 503 "offline" when that stack is down | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no | | traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy caddy) | `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, adamf/stpcore) | — (runs on the **stpcore** LXC; `garage` pinned to `GARAGE_UPSTREAM`) | 3900 S3, 3902 web | `/uploads/` from its website endpoint first, then the `uploads` volume; backend and usaco use S3 | no |
| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by Caddy `forward_auth`) | no | | garage-webui (Garage admin UI, adamf/stpcore) | — (on **stpcore**, behind its Caddy) | 3909 on stpcore | `/garage/` (admin-gated by Caddy `forward_auth`; Caddy adds `X-Core-Token`). 503 "offline" when stpcore is down | no |
Container names come from `.env`, and Caddy builds its upstreams from the same Container names come from `.env`, and Caddy builds its upstreams from the same
variables (passed through the caddy service's `environment:` list). **Renaming variables (passed through the caddy service's `environment:` list). **Renaming
@@ -98,15 +149,15 @@ The config is `caddy/Caddyfile` (global options and snippets), `caddy/routes.cad
it, so stripping the prefix serves a blank page with nothing in the log). it, so stripping the prefix serves a blank page with nothing in the log).
- **Upstreams resolve when dialled.** Caddy starts with any upstream container - **Upstreams resolve when dialled.** Caddy starts with any upstream container
missing and answers 502 until it appears; it never refuses to start over one. 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.** `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/` and `/uploads/private/` are
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
branch views stay public) are
protected by `forward_auth` to the backend's `/auth/validate-admin` (the protected by `forward_auth` to the backend's `/auth/validate-admin` (the
`admin_gate` snippet); a 401/403 redirects to the SPA login. Most of these services have no auth of their own at that path; the `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 activity tracker also checks the session itself. Its carve-outs, which a session
cookie never reaches, stay public at the edge 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 app:
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`. `/tracker/api/v1/` and `/tracker/tracker.user.js`. `/sb/` and `/jobs/` 301 to stppriv
Paths are matched cleaned and case-insensitively, so `/SB/` or `/uploads/x/../private/y` (`priv.<DOMAIN>`). Its Caddy gates them with this same admin session, asking
`/api/auth/validate-admin` over the LAN; see the `adamf/stppriv` README.
Paths are matched cleaned and case-insensitively, so `/TRACKER/` or `/uploads/x/../private/y`
land on the gate too. With the backend down every gated path answers 502: it fails closed. 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.** `/receipt/` asks `/auth/validate/receipt` instead (the
`permission_gate` snippet), which also lets in a `permission_gate` snippet), which also lets in a
@@ -162,14 +213,15 @@ which has two jobs:
leaves the old containers running. 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@git.<DOMAIN>:2222` (Gitea
on its LXC, pinned in `/etc/hosts`),
hard-resets the deploy checkout, and runs hard-resets the deploy checkout, and runs
`docker compose up -d --build --remove-orphans` under the `docker compose up -d --build --remove-orphans` under the
`.compose.lock` flock, shared with the weekly maintenance workflow. `.compose.lock` flock, shared with the weekly maintenance workflow.
The test job keeps state on the host outside the deploy checkout: a bare The test job keeps state on the host outside the deploy checkout: a bare
repository cache at `/home/adamf/.cache/web_server-ci/` and three named repository cache at `/home/adamf/.cache/stpweb-ci/` and three named
volumes (`web_server_ci_gomod`, `web_server_ci_gobuild`, `web_server_ci_pip`). volumes (`stpweb_ci_gomod`, `stpweb_ci_gobuild`, `stpweb_ci_pip`).
The weekly maintenance workflow's `docker image prune -af` removes the two The weekly maintenance workflow's `docker image prune -af` removes the two
toolchain images, so the first run after it pulls them again; the volumes toolchain images, so the first run after it pulls them again; the volumes
survive. Maintenance takes the same flock around its compose steps. survive. Maintenance takes the same flock around its compose steps.
@@ -207,7 +259,6 @@ The override layer changes these services and disables `cloudflared`:
- **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.
- **jobs** — seeded, with the GraphQL playground on.
- **cloudflared** — put in the `disabled` profile, so it never starts: a dev - **cloudflared** — put in the `disabled` profile, so it never starts: a dev
stack must never join the production tunnel. stack must never join the production tunnel.
@@ -374,10 +425,8 @@ Setup, once:
| Volume | Holds | Losing it means | | Volume | Holds | Losing it means |
| ---------- | ----------------------------------------------------- | -------------------------------------------------- | | ---------- | ----------------------------------------------------- | -------------------------------------------------- |
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata | | `dbdata` | Postgres: the app database and the trackers' databases | All posts, users and messages, and the trackers' data |
| `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files | | `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files |
| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) |
| `garage_data` | The bucket's object bytes | Every upload stored in Garage |
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy | | `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
| `caddy_config` | Caddy's autosaved JSON config | Nothing — rewritten on every start | | `caddy_config` | Caddy's autosaved JSON config | Nothing — rewritten on every start |
@@ -389,12 +438,13 @@ of deleting the directory:
| `./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). | | `./caddy/data` | Caddy's TLS certificates, **private keys** and ACME account | Gitignored. Never commit. Losing it means a re-issue on the next start (§3). |
| `./certbot/conf` | The old certbot certificate and keys | Unused since 2026-11-17; kept as the rollback until it is cleaned up (§7). | | `./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. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs (`go.log`); 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. | | `./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) | A pull-only clone (`silverbullet-git`); **read-only** to backend and silverbullet-public |
Gitea's state (`data/`, `config/` and the `gitea_gitea_db` volume, in the
`adamf/stpgit` checkout) is on the Gitea LXC, not here; see "Gitea LXC" in §7. The pre-move copy is in
stpvm's `.deprecated/gitea/` (gitignored), kept as the rollback.
**Ephemeral:** anything else inside a container. Notably the Vue build, the **Ephemeral:** anything else inside a container. Notably the Vue build, the
rendered icecast config, and the Gitea runner's downloaded binary rendered icecast config, and the Gitea runner's downloaded binary
@@ -414,20 +464,20 @@ Two distinct mechanisms read it, and services use both:
- **`env_file: ./.env`** — injects the whole file into the container. Used by - **`env_file: ./.env`** — injects the whole file into the container. Used by
backend, db and icecast2. backend, db and icecast2.
`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own Gitea's own variables are in the `.env` of its checkout on the Gitea LXC (the
convention for overriding `app.ini` keys), and `python` receives an explicit `adamf/stpgit` repo's `.env.example`);
allow-list (as do `jobs`, `caddy` and the rest), so it never sees the database password or any API key other than there it receives explicit `GITEA__section__KEY` variables (Gitea's own
convention for overriding `app.ini` keys). Here, `python` receives an explicit
allow-list (as do `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 backend receives `CLAUDE_API_KEY`
(the job tracker, built from its own repo) makes its own, and gets a similar through `env_file` but does not use it. A new variable for it has
allow-list with its own database role. The backend receives `CLAUDE_API_KEY`
through `env_file` but does not use it. A new variable for either service has
to be added to its allow-list as well as to be added to its allow-list as well as
`.env.example`. `.env.example`.
**`.env` is edited by hand on the host**, in **`.env` is edited by hand on the host**, in
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's `~/deploy/stpweb`. 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: compose substitutes an empty string, An unset variable is not an error: compose substitutes an empty string,
@@ -488,7 +538,7 @@ together.
## 7. Runbook ## 7. Runbook
All commands run from the deploy checkout on the host All commands run from the deploy checkout on the host
(`~/deploy/web_server`) unless stated. (`~/deploy/stpweb`) unless stated.
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does **Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
it. By hand: it. By hand:
@@ -576,7 +626,8 @@ 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 `logs/nginx/*.log` stanza in `/etc/logrotate.d/web_server` is nginx's and
can go when `logs/nginx/` does. can go when `logs/nginx/` does.
**Reset the database** — destructive; wipes the app database **and Gitea's**: **Reset the database** — destructive; wipes the app database (Gitea's is on
the Gitea LXC and is not affected):
``` ```
docker compose down docker compose down
@@ -585,51 +636,38 @@ docker compose up -d
``` ```
The app schema is recreated by GORM auto-migration on backend start (there are no The app schema is recreated by GORM auto-migration on backend start (there are no
migration files). **Gitea's database is not auto-created** — the Postgres image migration files). The job and activity trackers' databases are not
only creates `POSTGRES_DB` on first init, so create `${POSTGRES_GITEA_DB}` auto-created; their READMEs have the commands.
manually before Gitea will start:
``` **Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket
docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB" on the stpcore LXC (`adamf/stpcore`, whose README is the runbook: setup,
``` keys, the move from this host, backups), with the `uploads` volume here as a
safety net. Nothing breaks while stpcore is down or not set up:
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket,
with the `uploads` volume as a safety net. Nothing breaks while Garage is down
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 or can't be reached;
- Caddy 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 starts without the Garage has no such file or is unreachable (2s connect timeout);
`garage` container. - `/garage/` answers 503 "offline".
Turning it on: Pointing this stack at it: set `GARAGE_UPSTREAM` (stpcore's LAN IP),
`GARAGE_WEBUI_TOKEN` (same as stpcore's), `S3_ACCESS_KEY_ID` /
1. Fill in `GARAGE_RPC_SECRET`, `GARAGE_ADMIN_TOKEN`, `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` (same as stpcore's, imported by its
`S3_SECRET_ACCESS_KEY` in `.env` **before** the deploy that adds the `garage/bootstrap.sh`) and `S3_ENDPOINT=http://garage:3900`, then
containers (otherwise `garage` crash-loops on a blank secret until they `docker compose up -d caddy backend usaco`. The backend logs
are set; nothing else is affected). `.env.example` says how to generate `[upload] storing uploads in bucket uploads ...` on start.
each.
2. Deploy, then `garage/bootstrap.sh` (idempotent; it creates the layout, the
`uploads` bucket and the backend's key, and opens the bucket to the
website endpoint).
3. Set `S3_ENDPOINT=http://garage:3900` and `docker compose up -d backend`.
The backend logs `[upload] storing uploads in bucket uploads ...` on start.
4. Check: upload something through a canvas page or chat, then
`docker compose exec garage /garage bucket info uploads` shows the object
count going up, and the returned `/uploads/...` URL loads.
Moving the old files in (so they show in garage-webui, and so the bucket Moving the old files in (so they show in garage-webui, and so the bucket
holds everything): holds everything):
``` ```
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env) export $(grep -E '^(S3_ACCESS_KEY_ID|S3_SECRET_ACCESS_KEY|GARAGE_UPSTREAM)=' .env)
docker run --rm --network web_server_app-network \ docker run --rm \
-v web_server_uploads:/data:ro \ -v web_server_uploads:/data:ro \
-e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \ -e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \
-e AWS_DEFAULT_REGION=garage \ -e AWS_DEFAULT_REGION=garage \
amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \ amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \
--endpoint-url http://garage:3900 --endpoint-url "http://$GARAGE_UPSTREAM:3900"
``` ```
The copies left on the volume are then only a fallback for when Garage is The copies left on the volume are then only a fallback for when Garage is
@@ -638,33 +676,81 @@ served from its disk copy, if it has one. Once the bucket has been trusted for
a while, remove everything but `private/` from the volume. a while, remove everything but `private/` from the volume.
**Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files **Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files
written to the bucket in the meantime stay reachable as long as `garage` runs; written to the bucket in the meantime stay reachable as long as stpcore runs;
to drop Garage entirely, first copy them back to drop Garage entirely, first copy them back
(`aws s3 sync s3://uploads /data` with the volume mounted read-write). (`aws s3 sync s3://uploads /data` with the volume mounted read-write).
**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 2 GB by Caddy. capped at 2 GB by Caddy, here and on stpcore.
**Backups:** Garage here is one node on the same disk — it is not a backup. **Gitea LXC.** Gitea runs in its own Proxmox LXC (§1), from a checkout of its
Back up `garage_meta` and `garage_data` together (meta without data, or the own repo, `adamf/stpgit` (until 2026-11-24 this repo's `gitea/` directory),
reverse, is useless); Garage also snapshots its metadata every 6h inside with its secrets in that checkout's `.env`. Its README is the full runbook.
`garage_meta`. It is deployed by hand, never by CI:
**Set up the CI runner on a fresh host:**
``` ```
cd gitea-runner cd ~/deploy/stpgit && git pull && docker compose up -d
bash download.sh # pulls the binary for this CPU
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises
``` ```
The runner lives **outside** Docker on purpose: it runs `docker compose up` That includes a Renovate PR to that repo that bumps an image: merging deploys
against this stack, so it cannot be a container in it. Registration is one-shot — nothing, so pull and `up -d` there afterwards.
`.runner` is the lasting credential; re-registering needs that file deleted _and_
a fresh token. - *The container.* Debian, unprivileged, with `nesting=1,keyctl=1` (Docker
needs both), a static LAN IP on stpvm's bridge, Docker and Tailscale.
`GITEA_UPSTREAM` in stpvm's `.env` is that LAN IP; `GITEA_SSH_DOMAIN` in
the stpgit `.env` is its tailnet name, which Gitea prints in SSH clone URLs.
- *Webhooks to the site* (usaco's push hook,
`https://www.<DOMAIN>/usaco/api/hooks/gitea`) go straight to stpvm's Caddy
over the LAN: `extra_hosts` pins `www.<DOMAIN>` to `EDGE_IP`, and
`ALLOWED_HOST_LIST` allows that name, since its address is private.
- *Backups.* A Proxmox `vzdump` of the whole LXC covers the git data and the
database together. `data/` alone is not a backup: the issues, PRs,
users and registry index are in `gitea_db`.
- *If it is down,* `git.<DOMAIN>` is a Cloudflare error, the registry is 502, CI does not run, and
image pulls fail; the site itself keeps serving.
- *Moving it again* (or the first move, from stpvm): stop Gitea, `pg_dump -Fc`
its database and restore it with `pg_restore --no-owner --role=gitea` into
a fresh `gitea-db`, copy `data/` and `config/` with
`tar --numeric-owner` (owned by uid 1000), start it, then point
`GITEA_UPSTREAM` at the new address and `docker compose up -d gitea` on
stpvm. The SSH host key is in `data/`, so clients' `known_hosts` still
match.
- *Rollback to running it on stpvm:* stop it on the LXC, copy its
`data/` and database back over the pre-move copy in
`.deprecated/gitea/` and stpvm's `db`, then
`docker compose -f docker-compose.yml -f .deprecated/gitea/docker-compose.gitea.yml up -d gitea`.
`.deprecated/README.md` has the details.
**Build VM (stpbuild).** Since 2026-11-26 CI is split over two runners.
stpvm's (`stpvm`, label `self-hosted`) keeps only the jobs that
touch this stack: `deploy` in this repo's deploy.yaml and in usaco's and
activity-tracker's ci.yaml, and maintenance.yaml. Everything that only needs
git and docker (tests, image builds and pushes, Renovate) runs on
`stpbuild-runner` (label `build`, instance-wide, capacity 2), on the Proxmox
VM `stpbuild` (VMID 123, `192.168.178.240`, Ubuntu 24.04, 4 cores, 2 GB + 4 GB
swapfile). Its `/etc/hosts` pins `git.<DOMAIN>` to stpgit's LAN IP and the apex to
stpvm's (registry pushes go to this Caddy over the LAN, not Cloudflare). It
has no SSH key: build jobs fetch from `http://git.<DOMAIN>:3000/` with the
job's own `secrets.GITEA_TOKEN`, so a new repo needs no Gitea setup, only
`runs-on: build`. A `publish` job reuses its `test` job's git cache, so both
must stay on `build`. stpweb's own images are still built here by
`up --build`; moving them is the next step.
**The runners** are installed by the `adamf/stprunner` repo, not from here:
on each VM, `~/deploy/stprunner` and `sudo ./install.sh <host>` run
gitea-runner (formerly act_runner) as the systemd service `gitea-runner`,
with that host's name, labels and capacity in `hosts/<host>.env` there. Its
README covers a fresh VM, upgrades (Renovate bumps the pinned version) and
renames. Both run in host mode as `adamf`, outside Docker on purpose: the
deploy job runs `docker compose up` against this stack, so it cannot be a
container in it. Since 2026-11-27: gitea-runner v6.0.1, which needs Gitea
1.26.2+ (act_runner 0.2.x could not run `node24` actions such as
`actions/checkout@v5`). Until then each VM ran its own copy of this repo's
old `gitea-runner/` scripts from an `@reboot` crontab line, and stpvm's runner
was registered as `stppi` (the Pi it moved from). Those directories are still
on the VMs, unused, with the old `.runner` files.
**Dependency updates (Renovate).** Dependabot is GitHub-only, so **Dependency updates (Renovate).** Dependabot is GitHub-only, so
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday `.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday
@@ -720,7 +806,7 @@ Documented, not fixed — each would change deploy behaviour.
and `./logs/nginx/`, plus the `logs/nginx` stanza in and `./logs/nginx/`, plus the `logs/nginx` stanza in
`/etc/logrotate.d/web_server`. The code is in `.deprecated/`. Once the `/etc/logrotate.d/web_server`. The code is in `.deprecated/`. Once the
rollback is no longer wanted, delete the two directories and the stanza. rollback is no longer wanted, delete the two directories and the stanza.
2. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be 2. **`config/entrypoint.sh` in the stpgit checkout is an empty, unused,
mounted to the same in-container path as the real wrapper. It is currently root-owned file** that would be mounted to the same in-container path as
shadowed by an explicit file mount — fragile. Deleting it would be safe but the real wrapper. It is currently shadowed by an explicit file mount —
is a file removal. fragile. Deleting it (`sudo rm`) would be safe but is a file removal.
+11 -67
View File
@@ -1,39 +1,14 @@
# ============================================================================= # `make check` before pushing; `make help` lists targets. A missing toolchain
# Makefile — one place for the commands that verify and run this repo. # fails only the targets that need it.
#
# WHY THIS FILE EXISTS
# The stack is four toolchains (Go, Python, Node, Docker) and the command
# that checks each one used to live only in a gitignored notes file. `make
# check` is the single thing to run before pushing; .gitea/workflows/
# deploy.yaml runs the same backend and Python checks (in containers, since
# the Pi runner has no host toolchains) before it deploys.
#
# WHAT IT NEEDS ON THE HOST
# check-backend / generate Go (the version in backend/go.mod)
# check-python python3 with the venv module
# check-vue Node + `npm install` done in vue/
# check-compose / dev Docker with the compose plugin
# check-caddy Docker
# Nothing here installs a toolchain; a missing one fails that target only.
#
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
# its own shell, so the directory change cannot leak into the next line.
# =============================================================================
# `make` with no arguments prints the target list rather than running checks.
.DEFAULT_GOAL := help .DEFAULT_GOAL := help
# Overridable: `make check-python PYTHON=python3.12` to match the image.
PYTHON ?= python3 PYTHON ?= python3
# The virtualenv for the Python checks. At the repo root rather than inside # At the root, not in python/, which is a docker build context.
# python/, because python/ is a docker build context and a venv there would be
# sent to the daemon on every build. Gitignored (/.venv/).
VENV := .venv VENV := .venv
# Written after a successful install. Being a file target that depends on both # Re-installs only when a requirements file changes.
# requirements files, it is what makes `check-python` re-install when either
# changes and skip the install otherwise.
VENV_STAMP := $(VENV)/.installed VENV_STAMP := $(VENV)/.installed
.PHONY: help check check-backend check-python check-vue check-compose check-caddy generate dev .PHONY: help check check-backend check-python check-vue check-compose check-caddy generate dev
@@ -49,17 +24,12 @@ help:
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit" @echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
@echo " make dev build and run the dev stack (http://localhost)" @echo " make dev build and run the dev stack (http://localhost)"
# Run with `make -k check` to keep going past the first failing area.
check: check-backend check-python check-vue check-compose check-caddy check: check-backend check-python check-vue check-compose check-caddy
check-backend: check-backend:
cd backend && go vet ./... && go test ./... cd backend && go vet ./... && go test ./...
# requirements-dev.txt `-r`-includes requirements.txt, so one install covers # Recreated from scratch so packages dropped from the files don't linger.
# the app's dependencies and pytest. The venv is recreated from scratch
# whenever a requirements file changes: upgrading in place would leave behind
# packages that were removed from the files, and the check would keep passing
# on a dependency the image no longer has.
$(VENV_STAMP): python/requirements.txt python/requirements-dev.txt $(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
rm -rf $(VENV) rm -rf $(VENV)
$(PYTHON) -m venv $(VENV) $(PYTHON) -m venv $(VENV)
@@ -70,11 +40,7 @@ $(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
check-python: $(VENV_STAMP) check-python: $(VENV_STAMP)
cd python && ../$(VENV)/bin/python -m pytest tests -q cd python && ../$(VENV)/bin/python -m pytest tests -q
# A Vite build is enough to catch a broken import or template; there is no # Builds into a temp directory, so vue/dist is never touched.
# test runner or linter for the frontend.
#
# The build goes to a temp directory that is removed afterwards (success or
# failure), so the check never leaves a vue/dist behind or overwrites one.
check-vue: check-vue:
@test -d vue/node_modules || { \ @test -d vue/node_modules || { \
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \ echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
@@ -82,22 +48,9 @@ check-vue:
@out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \ @out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \
cd vue && npx vite build --outDir "$$out" --emptyOutDir cd vue && npx vite build --outDir "$$out" --emptyOutDir
# Validates the compose files: YAML, schema, and that every ${VAR} they # Without a .env, validates against a temp project dir holding .env.example
# interpolate resolves to something usable. # (compose refuses a missing env_file, and a blank OBSIDIAN_DIR is an invalid
# # bind mount). A real .env is never created.
# With a real .env present this is simply `docker compose config -q`.
#
# Without one (a CI checkout, a fresh clone) two things break, and
# `--env-file .env.example` fixes neither:
# - several services declare `env_file: ./.env`, and compose refuses to load
# the project if that file does not exist;
# - .env.example has blank values, and OBSIDIAN_DIR is used as a bind-mount
# source, where an empty string is a hard "invalid spec" error.
# So in that case the files are validated against a temporary PROJECT
# DIRECTORY holding a copy of .env.example as its .env, with a placeholder for
# OBSIDIAN_DIR. `config` only resolves paths, it does not need them to exist,
# so the build contexts not being under the temp directory is fine. Nothing is
# written to the repo, and a real .env is never created by accident.
check-compose: check-compose:
@set -e; \ @set -e; \
if [ -f .env ]; then \ if [ -f .env ]; then \
@@ -113,21 +66,12 @@ check-compose:
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \ echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
# The edge config is validated by the image build itself (the last RUN in # The image build runs `caddy validate` for both modes.
# caddy/Dockerfile runs `caddy validate` for the production and dev sites), so
# this is that build and nothing more. The deploy's `docker compose up
# --build` runs the same build, and a failure there stops before any
# container is replaced. The first build compiles Caddy with its plugins and
# takes a few minutes; later ones reuse that layer unless the Dockerfile
# changes.
check-caddy: check-caddy:
docker build -q -t web_server-caddy:check caddy/ docker build -q -t stpweb-caddy:check caddy/
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
generate: generate:
cd backend && go run github.com/99designs/gqlgen generate cd backend && go run github.com/99designs/gqlgen generate
# 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
+13 -31
View File
@@ -1,4 +1,3 @@
Gay bal;;s
# My Web # My Web
![screenshot](vue/public/img/screenshot.png) ![screenshot](vue/public/img/screenshot.png)
@@ -24,9 +23,8 @@ 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)
gitea (3000) ── Self-Hosted Git gitea (3000) ── Self-Hosted Git
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 ── Pulls the notes repo (the editor and its pushes are on stppriv)
python (8000) ── Python API (FastAPI) python (8000) ── Python API (FastAPI)
``` ```
@@ -53,9 +51,9 @@ python (8000) ── Python API (FastAPI)
- Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben) - Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben)
- Self-hosted Git (Gitea) with CI/CD and commit feed on homepage - Self-hosted Git (Gitea) with CI/CD and commit feed on homepage
- 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: runs on stppriv (`priv.<DOMAIN>/jobs/`), from the `adamf/job-tracker` repo
- 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: `/sb`, `/jobs`, `/tracker`, `/dozzle`, `/garage` and more require the admin session, checked by Caddy's `forward_auth` against the backend - Admin-gated routes: `/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)
@@ -68,10 +66,10 @@ python (8000) ── Python API (FastAPI)
| `/stp` | Home dashboard with grid layout | | `/stp` | Home dashboard with grid layout |
| `/admin` | Admin login + panel (authenticated) | | `/admin` | Admin login + panel (authenticated) |
| `/cv` | Curriculum Vitae (printable) | | `/cv` | Curriculum Vitae (printable) |
| `/cv/jobs` | Job application tracker (admin-only, hidden print) | | `/cv/jobs` | 301 to the job tracker on stppriv |
| `/bookmarks` | Bookmarks (database-backed, grouped by category) | | `/bookmarks` | Bookmarks (database-backed, grouped by category) |
| `/notes/:path` | Obsidian notes (read-only SilverBullet, public; `private/` excluded) | | `/notes/:path` | Obsidian notes (read-only SilverBullet, public; `private/` excluded) |
| `/sb/` | Obsidian note editor (via SilverBullet, admin-only) | | `/sb/` | 301 to the note editor on stppriv (`priv.<DOMAIN>/sb/`) |
| `/shrines` | Fan shrine index + individual shrines | | `/shrines` | Fan shrine index + individual shrines |
## API ## API
@@ -181,11 +179,11 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
| `/radio` | icecast:8000 | Audio streaming | | `/radio` | icecast:8000 | Audio streaming |
| `/gitea` | gitea:3000 | Git service | | `/gitea` | gitea:3000 | Git service |
| `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) | | `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) |
| `/sb` | silverbullet:3000 | Obsidian notes editor (admin-only) | | `/sb`, `/jobs` | 301 to `priv.<DOMAIN>` | Editor and job tracker, on stppriv |
| `/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 `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. Admin-only routes such as `/tracker` are 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
@@ -214,14 +212,9 @@ Create a `.env` file in the project root. All services read from this file.
| `UPTIMEKUMA_PORT` | Uptime Kuma port (planned) | | `UPTIMEKUMA_PORT` | Uptime Kuma port (planned) |
| `WALLABAG_HOST` | Wallabag hostname (planned) | | `WALLABAG_HOST` | Wallabag hostname (planned) |
| `WALLABAG_PORT` | Wallabag port (planned) | | `WALLABAG_PORT` | Wallabag port (planned) |
| `SILVERBULLET_HOST` | SilverBullet hostname (defaults to `silverbullet`) |
| `SILVERBULLET_PORT` | SilverBullet port (defaults to `3000`) |
| `SILVERBULLET_PUBLIC_HOST` | Public notes SilverBullet hostname (defaults to `silverbullet-public`) | | `SILVERBULLET_PUBLIC_HOST` | Public notes SilverBullet hostname (defaults to `silverbullet-public`) |
| `SILVERBULLET_PUBLIC_PORT` | Public notes SilverBullet port (defaults to `3000`) | | `SILVERBULLET_PUBLIC_PORT` | Public notes SilverBullet port (defaults to `3000`) |
| `SILVERBULLET_GIT_INTERVAL` | Seconds between notes commit/push cycles (defaults to `300`) | | `SILVERBULLET_GIT_INTERVAL` | Seconds between notes pulls (defaults to `300`) |
| `GITEA_RUNNER_HOST` | Gitea runner hostname |
| `GITEA_RUNNER_NAME` | Gitea runner display name |
| `GITEA_RUNNER_REGISTRATION_TOKEN` | Token to register Gitea Actions runner |
| `BACKEND_PORT` | Backend port (typically `8080`) | | `BACKEND_PORT` | Backend port (typically `8080`) |
| `BACKEND_HOST` | Backend hostname (use `backend` for Docker) | | `BACKEND_HOST` | Backend hostname (use `backend` for Docker) |
| `BACKEND_SECRET` | JWT signing secret | | `BACKEND_SECRET` | JWT signing secret |
@@ -251,13 +244,7 @@ Create a `.env` file in the project root. All services read from this file.
### Gitea Config ### Gitea Config
Copy from the template and fill in secrets: Gitea is not part of this stack. It runs in its own LXC from the `adamf/stpgit` repo, whose README covers its config; this stack reaches it as `GITEA_HOST`, pinned to its LAN IP (`GITEA_UPSTREAM`).
```sh
cp gitea/config/app.ini.template gitea/config/app.ini
```
Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the database `PASSWD`. Alternatively, the Gitea entrypoint generates `app.ini` from the template using environment variables.
### Spotify Token Setup ### Spotify Token Setup
@@ -267,9 +254,9 @@ Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the
### Obsidian Notes Setup ### Obsidian Notes Setup
1. Set `OBSIDIAN_DIR` in `.env` to the absolute path of your Obsidian vault on the host machine 1. Set `OBSIDIAN_DIR` in `.env` to the absolute path of your Obsidian vault on the host machine
2. The vault is mounted read-write into `silverbullet` at `/data`, which serves it as an 2. The vault is a pull-only clone of the notes repo (`silverbullet-git`, `SYNC_MODE=pull`),
editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at mounted read-only into `silverbullet-public`, which serves it publicly at `/notes/` with
`/notes/` with `SB_READ_ONLY` `SB_READ_ONLY`. The editor, and the vault's only writer, is on stppriv (`priv.<DOMAIN>/sb/`)
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** Caddy deny rules — the Caddy rules 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")
@@ -291,9 +278,7 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
### Gitea Runner ### Gitea Runner
1. Download the `act_runner` binary from [Gitea releases](https://gitea.com/gitea/act_runner/releases) and place in `gitea-runner/` The CI runners (stpvm's and the build VM's) are installed from the `adamf/stprunner` repo, not from here. See its README and "Build VM" in `DEPLOYMENT.md` §7.
2. Set `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`
3. The runner registers automatically on first startup
## Dev Mode ## Dev Mode
@@ -339,12 +324,9 @@ These files are git-ignored and must be created manually:
| File | Notes | | File | Notes |
| ------------------------------- | --------------------------------------------------------------- | | ------------------------------- | --------------------------------------------------------------- |
| `.env` | See setup section above | | `.env` | See setup section above |
| `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
| `caddy/data/` | Created automatically by Caddy (certificates and their keys) | | `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/.runner` | Generated on first runner startup |
## Future Ideas ## Future Ideas
+3 -33
View File
@@ -1,32 +1,5 @@
# ============================================================================= # Static binary (CGO_ENABLED=0) on a slim base. ca-certificates for outbound
# Go backend image — multi-stage: build with the full toolchain, ship a slim # HTTPS; the cache mounts keep rebuilds fast.
# runtime containing one static binary.
#
# STAGE 1 (golang:1.26)
# go.mod/go.sum are copied and downloaded BEFORE the rest of the source, so
# the dependency layer is cached and only re-runs when the module files
# change — a meaningful saving when building on a Raspberry Pi.
#
# The `--mount=type=cache` lines are BuildKit cache mounts: the module cache
# and the Go build cache persist BETWEEN builds on the host without being
# baked into any image layer. This is the single biggest reason a rebuild on
# the Pi takes minutes rather than much longer. They require BuildKit, which
# is the default in modern `docker compose build`.
#
# CGO_ENABLED=0 produces a fully static binary with no libc dependency, which
# is what lets a golang-built binary run on a different, slimmer base image.
#
# STAGE 2 (debian:bookworm-slim)
# Carries only the binary plus ca-certificates — needed because the backend
# makes outbound HTTPS calls (Spotify, Claude, Steam, the Gitea feed) and
# would fail certificate verification without a trust store.
#
# EXPOSE 8080 is documentation only; the port is never published to the host.
# Caddy reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
#
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
# amd64 (a dev laptop) with no platform pin.
# =============================================================================
FROM golang:1.26 AS builder FROM golang:1.26 AS builder
WORKDIR /backend WORKDIR /backend
@@ -44,10 +17,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \
FROM debian:bookworm-slim FROM debian:bookworm-slim
# wget is not just for humans: the compose healthcheck probes the server with # For the compose healthcheck.
# `wget -qO- http://localhost:8080/`, and without it in the image every probe
# fails as "executable file not found" and Docker marks the container
# unhealthy.
RUN apt-get update \ RUN apt-get update \
&& apt-get install --yes --no-install-recommends ca-certificates wget \ && apt-get install --yes --no-install-recommends ca-certificates wget \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
+13 -10
View File
@@ -38,7 +38,7 @@ graph/ GraphQL layer
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
spoofed via `X-Forwarded-For`. spoofed via `X-Forwarded-For`.
3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a 3. **REST**: the route's middleware chain runs. `AuthMiddleware` requires a
valid access token and stashes the claims in the Gin context; valid access token and stashes the claims in the Gin context;
`AdminMiddleware` then requires `admin: true` in those claims. A handler `AdminMiddleware` then requires `admin: true` in those claims. A handler
reached through the `admin` group can assume both. reached through the `admin` group can assume both.
@@ -55,12 +55,12 @@ graph/ GraphQL layer
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets - `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`: two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary - `access_token` (7 days) carries `id`, `username`, `admin` and `tv`;
requests authorise without a database hit; - `refresh_token` (90 days) carries `id` and `tv`.
- `refresh_token` (365 days) carries only `id`. Every check loads the user row (one SELECT) to compare `tv`, and takes
`admin` from the row, not the token.
- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh - `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
token for a new pair, re-reading the user — and therefore the admin flag — token for a new pair, so the 90 days slide while the account is in use.
from the database.
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401) - `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
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.
@@ -74,10 +74,13 @@ graph/ GraphQL layer
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
Caddy 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 - Revocation is by `User.TokenVersion`: logout and a password change bump it,
is revoked server-side, and a token that has already been issued stays valid which invalidates every token already issued to that user. Demoting an admin
until it expires. The same is true of demoting an admin: it takes effect on applies on their next request.
their next refresh, not immediately. - Any request that is not GET/HEAD/OPTIONS must come from the site's own
origin (`services.RequireSameOrigin`). SameSite=Lax alone would let a page on
a sibling subdomain such as radar. or git. post with the cookies. Requests
without `Origin` or `Sec-Fetch-Site` (curl, server-to-server) pass.
The two implementations (REST in `handlers/handle_auth.go`, GraphQL in The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
`graph/auth.resolvers.go`) are parallel by design, since the front end uses `graph/auth.resolvers.go`) are parallel by design, since the front end uses
-3
View File
@@ -14,9 +14,6 @@ import (
// CreateActivity is the resolver for the createActivity field. // CreateActivity is the resolver for the createActivity field.
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) { func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
// Admin-only, but there is no check to see here: the field is marked
// @admin in the schema and the directive (directives.go) has already
// refused anyone else by the time this runs.
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link} activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&activity).Error; err != nil { if err := r.Store.DB.Create(&activity).Error; err != nil {
return nil, err return nil, err
+6 -25
View File
@@ -19,12 +19,7 @@ import (
// Login is the resolver for the login field. // Login is the resolver for the login field.
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) { func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
// The Gin context is needed for two things GraphQL cannot express: the // Gin context for the client IP and cookies. Shares the REST login's limiter.
// client IP for rate limiting, and setting response cookies. It is
// smuggled in by AuthContextMiddleware.
//
// This mutation mirrors handlers.Store.Login; the two share the limiter
// and services.Auth, so the same 5/min budget covers both entry points.
gc := GinContextFromCtx(ctx) gc := GinContextFromCtx(ctx)
if gc == nil { if gc == nil {
return nil, fmt.Errorf("could not get gin context") return nil, fmt.Errorf("could not get gin context")
@@ -34,8 +29,6 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
return nil, fmt.Errorf("too many login attempts, please try again later") return nil, fmt.Errorf("too many login attempts, please try again later")
} }
// Identical message for unknown user and wrong password, so the API
// cannot be used to enumerate usernames.
var user models.User var user models.User
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil { if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
return nil, fmt.Errorf("invalid credentials") return nil, fmt.Errorf("invalid credentials")
@@ -52,8 +45,7 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens) services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
// The payload carries no token: the tokens only ever travel as HttpOnly // Tokens travel only as HttpOnly cookies.
// cookies, so client JavaScript never sees them.
return &model.AuthPayload{User: &user}, nil return &model.AuthPayload{User: &user}, nil
} }
@@ -64,12 +56,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
return false, fmt.Errorf("could not get gin context") return false, fmt.Errorf("could not get gin context")
} }
// Bumping the token version is what actually revokes the tokens; clearing // Best effort, always succeeds, like the REST endpoint.
// the cookies only stops the browser presenting them. Both are best
// effort and logout always reports success, matching the REST endpoint.
if userID, ok := UserIDFromCtx(ctx); ok { if userID, ok := UserIDFromCtx(ctx); ok {
// The context only carries claims from a token that already // Claims in ctx are already verified, so this can't target others.
// verified, so this cannot be used to revoke someone else's sessions.
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil { if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err) log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
} }
@@ -92,11 +81,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
return nil, fmt.Errorf("unauthorized") return nil, fmt.Errorf("unauthorized")
} }
// Shared with the REST refresh endpoint, but the messages below are the // Re-reads admin and token version from the DB.
// ones this resolver already returned, so the GraphQL error strings are
// unchanged. Admin status and the token version are both re-read from the
// database here, which is what lets a revoked admin flag or a logout take
// effect on refresh.
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken) user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
if err != nil { if err != nil {
switch { switch {
@@ -121,16 +106,12 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
// Me is the resolver for the me field. // Me is the resolver for the me field.
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) { func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
// Checked here rather than with @signedIn because the message differs: // Not @signedIn: this query's error has always been "unauthorized".
// this query has always answered "unauthorized", and the directive's is
// "authentication required".
userID, ok := UserIDFromCtx(ctx) userID, ok := UserIDFromCtx(ctx)
if !ok { if !ok {
return nil, fmt.Errorf("unauthorized") return nil, fmt.Errorf("unauthorized")
} }
// Read fresh from the database rather than returned from the token
// claims, so `me` reflects the current username and admin flag.
var user models.User var user models.User
user.ID = userID user.ID = userID
if err := r.Store.DB.First(&user).Error; err != nil { if err := r.Store.DB.First(&user).Error; err != nil {
+2 -4
View File
@@ -12,10 +12,8 @@ import (
"adam-french.co.uk/backend/models" "adam-french.co.uk/backend/models"
) )
// The SPA puts these values straight into a style binding, as // These go into a style binding; a quote or bracket in the image could still
// `background-color` and `url("<image>")`. Vue sets them through the CSSOM, // end url() early, hence the narrow shapes.
// so nothing can escape into other properties, but a quote or bracket in the
// image could still end the url() early — hence the narrow shapes.
var ( var (
// A hex colour, a colour name, or one of the colour functions — named, // A hex colour, a colour name, or one of the colour functions — named,
// so that url() and friends don't pass as a "function". // so that url() and friends don't pass as a "function".
+1 -3
View File
@@ -23,9 +23,7 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
// DeleteBookmark is the resolver for the deleteBookmark field. // DeleteBookmark is the resolver for the deleteBookmark field.
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) { func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
// Loaded first so the deleted record can be returned to the client, and // Loaded first so the deleted record can be returned and a bad id is "not found".
// so a missing id is a clean "not found" rather than a silent no-op.
// Delete is a soft delete: deleted_at is set and the row stays.
var bookmark models.Bookmark var bookmark models.Bookmark
if err := r.Store.DB.First(&bookmark, id).Error; err != nil { if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
return nil, err return nil, err
+7 -17
View File
@@ -15,9 +15,7 @@ import (
// CreateBox is the resolver for the createBox field. // CreateBox is the resolver for the createBox field.
func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) { func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) {
// Framed defaults to true here rather than in the gorm tag — see the // Framed defaults here, not in the gorm tag; see models.Box.Framed.
// comment on models.Box.Framed. Sizes not supplied fall back to the
// same 300x200 the column defaults use.
box := models.Box{ box := models.Box{
Page: input.Page, Page: input.Page,
Kind: input.Kind, Kind: input.Kind,
@@ -45,8 +43,7 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
if input.AdminOnly != nil { if input.AdminOnly != nil {
box.AdminOnly = *input.AdminOnly box.AdminOnly = *input.AdminOnly
} }
// A linked box takes its html from the component, so its own is // A linked box's own html would only go stale.
// dropped rather than stored as a copy that would quietly go stale.
if input.ComponentID != nil { if input.ComponentID != nil {
id := uint(*input.ComponentID) id := uint(*input.ComponentID)
exists, err := componentExists(r.Store.DB, id) exists, err := componentExists(r.Store.DB, id)
@@ -75,10 +72,8 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
// UpdateBox is the resolver for the updateBox field. // UpdateBox is the resolver for the updateBox field.
func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) { func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) {
// Partial update: nil fields are left alone. The canvas sends only the // Partial: the canvas sends only geometry after a drag and only html after
// geometry after a drag and only the html after an edit, so this is // an edit, so neither overwrites the other.
// what keeps the two from overwriting each other. Kind is not
// updatable — switching a widget box to html is a delete and create.
var box models.Box var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil { if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err return nil, err
@@ -87,8 +82,7 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
box.Widget = input.Widget box.Widget = input.Widget
} }
if input.HTML != nil { if input.HTML != nil {
// A linked box's html is the component's; changing it here would // Edit linked html via updateComponent, or it forks a copy.
// only fork a copy. The editor sends it to updateComponent instead.
if box.ComponentID != nil { if box.ComponentID != nil {
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first") return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
} }
@@ -140,12 +134,8 @@ func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box,
// Boxes is the resolver for the boxes field. // Boxes is the resolver for the boxes field.
func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) { func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) {
// Public: this is the page layout every visitor loads. Ordered by z so // Ordered by z so DOM and tab order match stacking. Admin-only content is
// DOM order matches stacking order, which keeps tab order sensible. // filtered server-side so it never reaches anyone else.
//
// What is admin-only is filtered here rather than hidden in the browser,
// so a private note never reaches anyone else: an adminOnly page answers
// with no boxes at all, and adminOnly boxes are left out of the rest.
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page) hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
if err != nil { if err != nil {
return nil, err return nil, err
+3 -10
View File
@@ -1,8 +1,6 @@
package graph package graph
// Hand-written helpers for box.resolvers.go. Kept out of that file because // Helpers live outside *.resolvers.go because gqlgen moves unknown code there.
// gqlgen moves unknown code in a resolvers file to the end, under a warning
// comment, on every regenerate.
import ( import (
"errors" "errors"
@@ -26,9 +24,7 @@ func setInt(dst *int, src *int) {
} }
} }
// validateBox checks the fields a box needs to render and clamps geometry // validateBox clamps geometry, so an overshooting drag lands at the edge.
// rather than rejecting it, because a drag that overshoots the canvas edge
// should land at the edge, not fail.
func validateBox(box *models.Box) error { func validateBox(box *models.Box) error {
if !validPageKey(box.Page) { if !validPageKey(box.Page) {
return errors.New("a box needs a valid page") return errors.New("a box needs a valid page")
@@ -52,16 +48,13 @@ func validateBox(box *models.Box) error {
if err := validateShadow(&box.Shadow); err != nil { if err := validateShadow(&box.Shadow); err != nil {
return err return err
} }
box.X = max(box.X, 0)
box.Y = max(box.Y, 0) box.Y = max(box.Y, 0)
box.W = max(box.W, minBoxSize) box.W = max(box.W, minBoxSize)
box.H = max(box.H, minBoxSize) box.H = max(box.H, minBoxSize)
return nil return nil
} }
// validateShadow trims a box-shadow value and bounds its length. The value is // validateShadow doesn't parse: a style binding confines it to one property.
// not parsed: the front end sets it through a style binding, so it can only
// ever be the one property, and an invalid value just draws no shadow.
func validateShadow(shadow *string) error { func validateShadow(shadow *string) error {
*shadow = strings.TrimSpace(*shadow) *shadow = strings.TrimSpace(*shadow)
if len(*shadow) > maxShadowLen { if len(*shadow) > maxShadowLen {
+5 -4
View File
@@ -35,13 +35,14 @@ func TestValidateBox(t *testing.T) {
}) })
} }
// Geometry is clamped, not rejected: a drag past the canvas edge lands // Geometry is clamped, not rejected: x may go negative, into the margin
// at the edge, and a box can never shrink below a grabbable size. // left of a centred canvas, but nothing goes above the top or below a
// grabbable size.
box := models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), X: -30, Y: -1, W: 5, H: 0} box := models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), X: -30, Y: -1, W: 5, H: 0}
if err := validateBox(&box); err != nil { if err := validateBox(&box); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if box.X != 0 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize { if box.X != -30 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize {
t.Fatalf("clamped to %d,%d %dx%d; want 0,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize) t.Fatalf("clamped to %d,%d %dx%d; want -30,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize)
} }
} }
+4 -13
View File
@@ -16,8 +16,6 @@ import (
// Uses is the resolver for the uses field. // Uses is the resolver for the uses field.
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) { func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
// One count per component, which is fine for an admin-only list of a
// handful; soft-deleted boxes are excluded by GORM's default scope.
var count int64 var count int64
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil { if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
return 0, err return 0, err
@@ -27,7 +25,6 @@ func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (in
// CreateComponent is the resolver for the createComponent field. // CreateComponent is the resolver for the createComponent field.
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) { func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
// Framed defaults to true and the size to 300x200, as for a new box.
name, err := usableComponentName(r.Store.DB, input.Name, 0) name, err := usableComponentName(r.Store.DB, input.Name, 0)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -57,8 +54,7 @@ func (r *mutationResolver) CreateComponent(ctx context.Context, input model.Crea
// UpdateComponent is the resolver for the updateComponent field. // UpdateComponent is the resolver for the updateComponent field.
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) { func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
// Partial, like updateBox. Nothing to do for the linked boxes: they // Linked boxes read the html from here, so nothing else to update.
// read the html from here every time they are fetched.
var c models.Component var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil { if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err return nil, err
@@ -100,9 +96,7 @@ func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input mo
// DeleteComponent is the resolver for the deleteComponent field. // DeleteComponent is the resolver for the deleteComponent field.
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) { func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
// The linked boxes keep showing what they showed, as copies, so // Linked boxes become copies, so deleting never changes a page.
// deleting a component never changes a page. One transaction, so a
// failure can't leave boxes linked to a deleted component.
var c models.Component var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil { if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err return nil, err
@@ -121,9 +115,8 @@ func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field. // SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) { func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
// The box becomes the component's first linked instance, so carrying // The box becomes the first linked instance. A linked box must be
// on editing it edits the component. A box that is already linked // detached first.
// would make a component of a component's html; detach it first.
var box models.Box var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil { if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err return nil, err
@@ -161,8 +154,6 @@ func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name
// DetachBox is the resolver for the detachBox field. // DetachBox is the resolver for the detachBox field.
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) { func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
// The html is filled in from the component and then saved, which is
// exactly the copy fillLinked otherwise never lets reach the row.
var box models.Box var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil { if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err return nil, err
+2 -9
View File
@@ -27,9 +27,6 @@ func cleanComponentName(name string) (string, error) {
return name, nil return name, nil
} }
// componentNameTaken reports whether a live component other than exceptID
// has this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) { func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64 var count int64
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
@@ -53,12 +50,8 @@ func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error
return name, nil return name, nil
} }
// fillLinked sets each linked box's in-memory HTML to its component's, with // fillLinked sets linked boxes' HTML in memory only: saving a filled box would
// one query for all of them. Only for boxes about to be returned or // freeze a copy into it. A missing component leaves the HTML empty.
// snapshotted: a linked row's own HTML is nil, and saving a filled box would
// freeze a copy of the component into it. A box whose component has gone
// (deleted outside deleteComponent, which detaches first) is left with
// empty HTML rather than failing the whole page.
func fillLinked(db *gorm.DB, boxes []models.Box) error { func fillLinked(db *gorm.DB, boxes []models.Box) error {
var ids []uint var ids []uint
for _, b := range boxes { for _, b := range boxes {
+7 -30
View File
@@ -7,17 +7,10 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
// This file is the bridge between Gin's request handling and gqlgen's // Resolvers get only a context.Context; AuthContextMiddleware puts the
// resolvers. gqlgen resolvers receive only a context.Context, so // verified claims and the *gin.Context into it.
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
// the *gin.Context itself into that context, and these accessors read them
// back out.
// contextKey is a private named type so that these keys can never collide // Unrelated to the "userClaims" key handlers.AuthMiddleware sets on Gin's context.
// with a key set by another package — the reason the standard library warns
// against using bare strings as context keys. Note the string value
// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the
// *Gin* context, but the two are unrelated and do not see each other.
type contextKey string type contextKey string
const ( const (
@@ -25,10 +18,8 @@ const (
ginContextKey contextKey = "ginContext" ginContextKey contextKey = "ginContext"
) )
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request // UserClaimsFromCtx returns nil for anonymous requests; refusing is the
// is anonymous. nil means "not authenticated": a missing or invalid token is // directives' job.
// not an error here, because many queries are public. Turning "anonymous"
// into a refusal is the job of the schema directives, per field.
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims { func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims) claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
if !ok { if !ok {
@@ -37,12 +28,6 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
return claims return claims
} }
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
// float64 because claims are decoded by encoding/json, hence the conversion.
//
// ok is also the test behind the @signedIn directive. A resolver calls this
// itself when it needs the id for more than a gate: to record a post's
// author, or to compare the caller with a row's owner.
func UserIDFromCtx(ctx context.Context) (uint, bool) { func UserIDFromCtx(ctx context.Context) (uint, bool) {
claims := UserClaimsFromCtx(ctx) claims := UserClaimsFromCtx(ctx)
if claims == nil { if claims == nil {
@@ -55,12 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true return uint(idF), true
} }
// IsAdminFromCtx reports whether the request carries an admin token. It is // IsAdminFromCtx reads the claims, whose admin flag comes from the user row.
// what the @admin directive tests (directives.go), which is how nearly every
// mutation is authorised; resolvers call it directly only for the softer
// cases a directive cannot express, such as the messages query filtering
// rather than refusing. Admin comes from the token, not the database, so a
// revoked admin flag only bites once the access token expires.
func IsAdminFromCtx(ctx context.Context) bool { func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx) claims := UserClaimsFromCtx(ctx)
if claims == nil { if claims == nil {
@@ -70,10 +50,7 @@ func IsAdminFromCtx(ctx context.Context) bool {
return ok && admin return ok && admin
} }
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need // GinContextFromCtx is nil if the middleware wasn't installed.
// for things that live outside GraphQL's model: setting auth cookies and
// reading the client IP. Returns nil if the middleware was not installed,
// which the auth resolvers surface as an error rather than panicking.
func GinContextFromCtx(ctx context.Context) *gin.Context { func GinContextFromCtx(ctx context.Context) *gin.Context {
gc, ok := ctx.Value(ginContextKey).(*gin.Context) gc, ok := ctx.Value(ginContextKey).(*gin.Context)
if !ok { if !ok {
+3 -9
View File
@@ -36,18 +36,14 @@ func cleanCoverLetterName(name string) (string, error) {
return name, nil return name, nil
} }
// coverLetterNameTaken reports whether a live letter other than exceptID has
// this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) { func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64 var count int64
err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err return count > 0, err
} }
// checkCoverLetterBody reports why body can't be stored. The server never // checkCoverLetterBody: the server never reads inside it, so it need only be a
// reads inside it, so it only has to be a JSON object of a sane size — an // JSON object of sane size.
// array or a bare string would be a frontend bug worth refusing early.
func checkCoverLetterBody(body string) error { func checkCoverLetterBody(body string) error {
if len(body) > maxCoverLetterBodyLen { if len(body) > maxCoverLetterBodyLen {
return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024) return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024)
@@ -60,9 +56,7 @@ func checkCoverLetterBody(body string) error {
return nil return nil
} }
// cleanSnippetText trims text and reports why it can't be a bank paragraph. // cleanSnippetText counts characters, not bytes.
// Counted in characters, not bytes, since the limit is about how much prose
// fits rather than storage.
func cleanSnippetText(text string) (string, error) { func cleanSnippetText(text string) (string, error) {
text = strings.TrimSpace(text) text = strings.TrimSpace(text)
if text == "" { if text == "" {
+4 -28
View File
@@ -7,34 +7,16 @@ import (
"github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql"
) )
// The schema's two authorisation directives. A field marked @admin or // The @admin and @signedIn directives. The front end shows these error
// @signedIn in graph/schema/*.graphql has the matching function here run // strings verbatim (the tracker reads "admin access required" as a lapsed
// before its resolver; if it returns an error the resolver is never called // session), so don't reword them.
// and the error is what the client receives for that field.
//
// This replaces a check that used to be copied into the top of every guarded
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
// it is now declared next to the field, where a missing one can be seen and
// tested for (directives_test.go), instead of being a line someone has to
// remember to paste.
//
// The two error strings are part of the contract with the front end, which
// shows them as they are; the tracker page, for one, explains "admin access
// required" as a lapsed session. Do not reword them.
//
// This file is hand-written and never touched by gqlgen.
const ( const (
errAdminRequired = "admin access required" errAdminRequired = "admin access required"
errSignedInRequired = "authentication required" errSignedInRequired = "authentication required"
) )
// Directives is the set gqlgen needs in graph.Config. It is a function so // Directives is shared by main and the tests. A nil directive fails closed.
// that main and the tests wire exactly the same implementations.
//
// Leaving a directive nil in the Config does not open the fields that use it:
// the generated code answers "directive admin is not implemented" for each.
func Directives() DirectiveRoot { func Directives() DirectiveRoot {
return DirectiveRoot{ return DirectiveRoot{
Admin: requireAdmin, Admin: requireAdmin,
@@ -42,9 +24,6 @@ func Directives() DirectiveRoot {
} }
} }
// requireAdmin implements @admin: the request must carry an access token
// whose admin claim is true. Admin comes from the token, not the database, so
// demoting a user only bites once their access token is replaced.
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) { func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if !IsAdminFromCtx(ctx) { if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf(errAdminRequired) return nil, fmt.Errorf(errAdminRequired)
@@ -52,9 +31,6 @@ func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error
return next(ctx) return next(ctx)
} }
// requireSignedIn implements @signedIn: any verified access token will do,
// admin or not. An admin is signed in, so this never needs pairing with
// @admin.
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) { func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if _, ok := UserIDFromCtx(ctx); !ok { if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf(errSignedInRequired) return nil, fmt.Errorf(errSignedInRequired)
+11 -42
View File
@@ -20,15 +20,8 @@ import (
"adam-french.co.uk/backend/handlers" "adam-french.co.uk/backend/handlers"
) )
// Authorisation is declared in the schema (@admin / @signedIn) and enforced // Covers both the directive functions and which fields carry them. No
// by directives.go. These tests cover both halves: that the two functions // database: refused fields never reach their resolvers.
// decide correctly, and that the schema marks the fields it should — the
// second being the one that matters day to day, since the way this goes
// wrong is a new field added without a directive.
//
// Nothing here needs a database: a refused field never reaches its resolver,
// and the tests only ever drive fields that are refused or that return before
// touching the Store.
// withClaims builds the context AuthContextMiddleware would for a verified // withClaims builds the context AuthContextMiddleware would for a verified
// token. Claims are decoded from JSON in production, hence float64 for the id. // token. Claims are decoded from JSON in production, hence float64 for the id.
@@ -100,9 +93,7 @@ func TestDirectivesAreAllImplemented(t *testing.T) {
} }
} }
// guardOf reports which authorisation directive a field carries: "admin", // guardOf fails on both directives at once: @signedIn adds nothing to @admin.
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
// nothing to @admin) and fails the test rather than being quietly accepted.
func guardOf(t *testing.T, field *ast.FieldDefinition) string { func guardOf(t *testing.T, field *ast.FieldDefinition) string {
t.Helper() t.Helper()
admin := field.Directives.ForName("admin") != nil admin := field.Directives.ForName("admin") != nil
@@ -123,14 +114,8 @@ func schemaUnderTest() *ast.Schema {
return NewExecutableSchema(Config{}).Schema() return NewExecutableSchema(Config{}).Schema()
} }
// publicMutations is the complete list of mutations that anyone may call. // publicMutations is the allow-list; any other unguarded mutation fails
// A mutation is public only by being named here, so adding one to the schema // TestEveryMutationIsGuarded.
// without a directive fails TestEveryMutationIsGuarded until it is either
// guarded or deliberately listed.
//
// All three are how a session is obtained or given up, so they cannot require
// one: login checks a password, refreshToken checks the refresh cookie, and
// logout is a no-op for a visitor who is not signed in.
var publicMutations = []string{"login", "logout", "refreshToken"} var publicMutations = []string{"login", "logout", "refreshToken"}
func TestEveryMutationIsGuarded(t *testing.T) { func TestEveryMutationIsGuarded(t *testing.T) {
@@ -159,9 +144,7 @@ func TestEveryMutationIsGuarded(t *testing.T) {
} }
} }
// The mutations that need only a session rather than an admin. Pinned so that // Pinned so loosening @admin to @signedIn needs a change here.
// loosening a mutation from @admin to @signedIn — which the test above would
// accept — has to be done here too.
func TestSignedInMutationsArePinned(t *testing.T) { func TestSignedInMutationsArePinned(t *testing.T) {
want := []string{"createPlace", "deletePlace", "updatePlace"} want := []string{"createPlace", "deletePlace", "updatePlace"}
var got []string var got []string
@@ -176,15 +159,8 @@ func TestSignedInMutationsArePinned(t *testing.T) {
} }
} }
// Queries are public by default — the home page is built from them — so the // Queries are public by default, so the guarded set is pinned exactly.
// rule cannot be "every field is guarded". Instead the guarded set is pinned // me, messages and spotifyNeedsReauth vary by caller without a directive.
// exactly: removing a directive from one of these, or adding a query that
// exposes private data without one, has to be a visible change to this map.
//
// Three queries are sensitive to who is asking without being in it, because
// they answer rather than refuse: `me` returns "unauthorized" itself,
// `messages` filters out private rows for non-admins, and
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) { func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{ want := map[string]string{
"users": "admin", "users": "admin",
@@ -217,9 +193,7 @@ func TestGuardedQueriesArePinned(t *testing.T) {
} }
} }
// The directives are FIELD_DEFINITION only and are meant for the two root // Keep directives on root fields: the tests above only look there.
// types. One on an object's field would be enforced, but nothing above would
// notice it being removed, so keep them where the tests look.
func TestDirectivesOnlyOnRootFields(t *testing.T) { func TestDirectivesOnlyOnRootFields(t *testing.T) {
schema := schemaUnderTest() schema := schemaUnderTest()
for name, def := range schema.Types { for name, def := range schema.Types {
@@ -234,10 +208,7 @@ func TestDirectivesOnlyOnRootFields(t *testing.T) {
} }
} }
// execute runs one operation through the real executable schema, wired the // execute runs an operation as main wires it, with an empty Store.
// way main wires it, and returns the response's error messages. The Store is
// empty: every operation below is refused, or returns, before its resolver
// would touch the database.
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string { func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
t.Helper() t.Helper()
srv := handler.New(NewExecutableSchema(Config{ srv := handler.New(NewExecutableSchema(Config{
@@ -298,9 +269,7 @@ func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
} }
} }
// IDs: the wire form must be what it was when every type had a hand-written // IDs stay quoted decimal strings on the wire, accepting strings or numbers.
// resolver returning int. Both marshallers write a quoted decimal string and
// both read a string or a number.
func TestUintIDWireFormatMatchesIntID(t *testing.T) { func TestUintIDWireFormatMatchesIntID(t *testing.T) {
for _, id := range []uint{0, 1, 12, 4294967295} { for _, id := range []uint{0, 1, 12, 4294967295} {
var asUint, asInt bytes.Buffer var asUint, asInt bytes.Buffer
+11 -47
View File
@@ -1,51 +1,15 @@
// Package graph is the GraphQL layer: the single POST /graphql endpoint that // Package graph is the GraphQL layer behind POST /graphql.
// serves most of the site's data.
// //
// How the pieces fit: // graph/schema/*.graphql is the source of truth; gqlgen regenerates
// generated.go and model/models_gen.go (never edit them). gqlgen.yml maps
// object types onto the GORM structs in backend/models.
// //
// - graph/schema/*.graphql is the source of truth. Running // Nothing guards the endpoint itself. A field is protected only by an
// `go run github.com/99designs/gqlgen generate` regenerates generated.go // @admin or @signedIn directive (directives.go); a field with neither is
// and model/models_gen.go, and adds stubs for any new field to the // public. directives_test.go fails if a mutation has neither and isn't on its
// matching *.resolvers.go. Never edit those two generated files. // public allow-list. Finer rules (post ownership, hiding private messages)
// - gqlgen.yml maps most GraphQL object types straight onto the GORM // live in resolvers via IsAdminFromCtx / UserIDFromCtx.
// structs in backend/models, so model/ holds only input and payload
// types. A model's `ID uint` binds to `id: ID!` directly, because
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
// needed for it. A field resolver is only written where the Go type has
// no binding (Message.authorId and Rowing's time/distance are unsigned in
// Go and Int in the schema).
// - Resolvers reach the database and the third-party caches through
// Resolver.Store, the same handlers.Store the REST endpoints use.
// - context.go and middleware.go carry the caller's identity from Gin into
// the plain context.Context a resolver receives.
// //
// Authorisation, which is the thing most likely to catch out a newcomer: // gqlgen may move hand-written code in *.resolvers.go; _helpers.go files are
// there is NO middleware guarding this endpoint. AuthContextMiddleware only // untouched.
// annotates the context and lets everything through. What guards a field is a
// directive on it in the schema:
//
// createUser(input: CreateUserInput!): User! @admin
// places: [Place!]! @signedIn
//
// @admin requires an admin's access token, @signedIn any valid one. Both are
// implemented once, in directives.go, and run before the resolver, so a
// guarded resolver contains no check of its own. A field with NEITHER
// directive is fully public.
//
// The rule of thumb in this schema is that queries are public and mutations
// are @admin, with these exceptions: login, logout and refreshToken are
// public; the places mutations and query are @signedIn; and the users
// queries are @admin (they are private data).
// directives_test.go holds that list and fails when the schema departs from
// it — in particular when a mutation is added with no directive.
//
// A directive is only a gate. Anything finer stays in the resolver and uses
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
// author, `me` answers for the caller (with its own "unauthorized" error),
// the messages query hides private messages from non-admins rather than
// refusing, and spotifyNeedsReauth is simply false for non-admins.
//
// The files ending in _helpers.go are hand-written and are not touched by
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
// them by hand may be moved to the end of the file on the next generate.
package graph package graph
+1 -4
View File
@@ -24,10 +24,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
if err != nil { if err != nil {
return nil, err return nil, err
} }
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed // Not cached, so an empty feed is retried next time.
// would dereference it, so return null to the client instead. The cache
// is deliberately not written in that case, so an empty feed is retried
// on the next request.
if feed == nil { if feed == nil {
return nil, nil return nil, nil
} }
+1 -4
View File
@@ -5,10 +5,7 @@ import (
"adam-french.co.uk/backend/services" "adam-french.co.uk/backend/services"
) )
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the // mapGiteaFeed requires a non-nil feed.
// commit message out of the doubly-encoded Content field as it goes. It
// dereferences feed, so callers must rule out the (nil, nil) that
// FetchLatestFeed returns for an empty feed.
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem { func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
return &model.GiteaFeedItem{ return &model.GiteaFeedItem{
AvatarURL: feed.ActUser.AvatarURL, AvatarURL: feed.ActUser.AvatarURL,
+8 -33
View File
@@ -1,8 +1,5 @@
package graph package graph
// Hand-written helpers for layout.resolvers.go, kept out of the resolver file
// for the same reason as box_helpers.go.
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
@@ -17,9 +14,7 @@ import (
const maxLayoutNameLen = 100 const maxLayoutNameLen = 100
// layoutBox is one box as a layout stores it: what makes it look the way it // layoutBox is a box minus id and page. Renaming fields breaks saved layouts.
// does, without the id and page that tie a row to one canvas. Changing these
// field names would make older layouts load with the renamed fields empty.
type layoutBox struct { type layoutBox struct {
Kind string `json:"kind"` Kind string `json:"kind"`
Widget *string `json:"widget,omitempty"` Widget *string `json:"widget,omitempty"`
@@ -34,9 +29,7 @@ type layoutBox struct {
Shadow string `json:"shadow,omitempty"` Shadow string `json:"shadow,omitempty"`
HideOnMobile bool `json:"hideOnMobile"` HideOnMobile bool `json:"hideOnMobile"`
AdminOnly bool `json:"adminOnly"` AdminOnly bool `json:"adminOnly"`
// ComponentID is the component a linked box was linked to. HTML is // HTML is kept too, so a layout outlives a deleted component.
// stored too, so that a layout outlives the component: loading links the
// box again if the component is still there and uses HTML if not.
ComponentID *uint `json:"componentId,omitempty"` ComponentID *uint `json:"componentId,omitempty"`
} }
@@ -46,7 +39,6 @@ type layoutBackground struct {
Fit string `json:"fit"` Fit string `json:"fit"`
} }
// cleanLayoutName trims name and reports why it can't be a layout's name.
func cleanLayoutName(name string) (string, error) { func cleanLayoutName(name string) (string, error) {
name = strings.TrimSpace(name) name = strings.TrimSpace(name)
if name == "" { if name == "" {
@@ -58,18 +50,14 @@ func cleanLayoutName(name string) (string, error) {
return name, nil return name, nil
} }
// layoutNameTaken reports whether a live layout other than exceptID has this // Checked up front so the admin gets a sentence, not a constraint violation.
// name. Checked up front, like slugTaken, so the admin gets a sentence rather
// than a constraint violation.
func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) { func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64 var count int64
err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err return count > 0, err
} }
// canvasExists reports whether page is a canvas boxes can be put on: the // canvasExists: boxes on any other key would never be shown.
// landing page, or a live Page. Loading a layout onto any other key would
// leave its boxes where nothing shows them.
func canvasExists(db *gorm.DB, page string) (bool, error) { func canvasExists(db *gorm.DB, page string) (bool, error) {
if page == "index" { if page == "index" {
return true, nil return true, nil
@@ -82,16 +70,13 @@ func canvasExists(db *gorm.DB, page string) (bool, error) {
return count > 0, err return count > 0, err
} }
// pageBoxes is every box on page, adminOnly ones included, in the order the // pageBoxes includes adminOnly boxes; admin callers only.
// boxes query returns them. Only for admin-only callers.
func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) { func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) {
var boxes []models.Box var boxes []models.Box
err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error
return boxes, err return boxes, err
} }
// snapshotPage is an unsaved Layout holding page's boxes and background as
// they are now. empty is true when there was nothing to keep.
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) { func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
boxes, err := pageBoxes(db, page) boxes, err := pageBoxes(db, page)
if err != nil { if err != nil {
@@ -139,7 +124,6 @@ func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
return boxes, nil return boxes, nil
} }
// pageLabel is how a page key reads in a generated layout name.
func pageLabel(page string) string { func pageLabel(page string) string {
if page == "index" { if page == "index" {
return "/" return "/"
@@ -147,7 +131,6 @@ func pageLabel(page string) string {
return "/" + page return "/" + page
} }
// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken.
func uniqueLayoutName(db *gorm.DB, base string) (string, error) { func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
name := base name := base
for n := 2; ; n++ { for n := 2; ; n++ {
@@ -159,22 +142,17 @@ func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
} }
} }
// applyLayoutTo copies layout onto page inside tx; see applyLayout in // applyLayoutTo creates new rows, so nothing stays linked to the layout.
// layout.graphql for what replace does. The copies are new rows, so the page
// owns them outright.
func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error { func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error {
stored, err := decodeLayoutBoxes(layout) stored, err := decodeLayoutBoxes(layout)
if err != nil { if err != nil {
return err return err
} }
// Added on top, the copies keep their own stacking order but all sit // Added copies stack above the page's existing boxes.
// above what the page already has.
zShift := 0 zShift := 0
if replace { if replace {
// What is being replaced is kept first, so a replace can be undone by // Save what's being replaced first, so a replace can be undone.
// loading that layout back. A page with nothing on it has nothing to
// keep.
name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s", name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s",
pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04"))) pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04")))
if err != nil { if err != nil {
@@ -234,7 +212,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
} }
} }
// Adding on top leaves the page's own background alone.
if replace && layout.Background != nil { if replace && layout.Background != nil {
var saved layoutBackground var saved layoutBackground
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil { if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
@@ -251,8 +228,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
return nil return nil
} }
// liveComponents is the set of components the stored boxes were linked to
// that still exist, so applyLayoutTo knows which boxes to link again.
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) { func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
var ids []uint var ids []uint
for _, b := range stored { for _, b := range stored {
+3 -9
View File
@@ -12,21 +12,15 @@ import (
) )
// AuthorID is the resolver for the authorId field. // AuthorID is the resolver for the authorId field.
// AuthorID is the resolver for the authorId field. The value is the chat // The chat hub's connection number, not a User id.
// hub's per-connection counter, not a User id — see models.Message.
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) { func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
return int(obj.AuthorID), nil return int(obj.AuthorID), nil
} }
// Messages is the resolver for the messages field. // Messages is the resolver for the messages field.
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) { func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
// Non-admins get the public subset rather than an error, so the chat // Non-admins get the public subset. Keep in step with the WebSocket
// history loads for everyone. The same filter is applied to the history // history filter (services.HandleWebSocket), which is oldest first.
// replayed over the WebSocket (services.HandleWebSocket) — change one and
// the other must change too.
//
// Note the ordering differs between the two: newest first here, oldest
// first over the socket.
var messages []models.Message var messages []models.Message
query := r.Store.DB.Order("created_at DESC") query := r.Store.DB.Order("created_at DESC")
if !IsAdminFromCtx(ctx) { if !IsAdminFromCtx(ctx) {
+2 -21
View File
@@ -8,39 +8,20 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// AuthContextMiddleware prepares the request context for the GraphQL handler. // AuthContextMiddleware never rejects: a bad or missing token leaves the
// // context anonymous and the directives decide. No refresh fallback.
// It always attaches the *gin.Context, and attaches the JWT claims only when a
// valid access token is present. Crucially it never rejects a request: a
// missing, expired or forged token simply leaves the context anonymous, which
// is what lets public queries work and leaves every authorisation decision
// to the field being resolved — the @admin / @signedIn directives on it (see
// directives.go), or the resolver itself for anything finer. Both cookie and
// verify errors are swallowed for exactly that reason.
//
// It takes the database because validating a token means loading the user to
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
//
// Unlike the REST path there is no refresh-token fallback here, so once the
// access token expires GraphQL treats the caller as anonymous until the front
// end refreshes.
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc { func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), ginContextKey, c) ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
accessToken, err := c.Cookie("access_token") accessToken, err := c.Cookie("access_token")
if err == nil { if err == nil {
// The database is needed to check the token version, so a
// revoked token (logout, password change) leaves the request
// anonymous instead of continuing to authorise mutations.
_, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken) _, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken)
if err == nil { if err == nil {
ctx = context.WithValue(ctx, userClaimsKey, claims) ctx = context.WithValue(ctx, userClaimsKey, claims)
} }
} }
// The context is immutable, so the enriched one has to be written
// back onto the request for the gqlgen handler to see it.
c.Request = c.Request.WithContext(ctx) c.Request = c.Request.WithContext(ctx)
c.Next() c.Next()
} }
+2 -6
View File
@@ -45,9 +45,7 @@ func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePag
// UpdatePage is the resolver for the updatePage field. // UpdatePage is the resolver for the updatePage field.
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) { func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
// Partial update, like updateBox. A new slug moves the page's boxes and // Partial. A new slug moves the boxes and background in the same transaction.
// background with it in the same transaction, since both find their page
// by slug.
var page models.Page var page models.Page
if err := r.Store.DB.First(&page, id).Error; err != nil { if err := r.Store.DB.First(&page, id).Error; err != nil {
return nil, err return nil, err
@@ -134,9 +132,7 @@ func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
// Page is the resolver for the page field. // Page is the resolver for the page field.
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) { func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
// Null, not an error, for a missing page: the SPA's catch-all route asks // Null for missing or hidden pages: the SPA shows its 404 on null.
// this for every unknown path and shows its 404 on null. An adminOnly
// page reads as missing to everyone else, so its existence isn't leaked.
var page models.Page var page models.Page
err := r.Store.DB.Where("slug = ?", slug).First(&page).Error err := r.Store.DB.Where("slug = ?", slug).First(&page).Error
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
+5 -16
View File
@@ -13,20 +13,13 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// pageKeyPattern is the shape of a box's page key and of a page slug: lower // Slugs are URL-safe as they stand.
// case words joined by hyphens, in one or more /-separated segments. It is
// URL-safe as it stands, so the front end can use a slug as a path without
// escaping it.
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`) var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
const maxSlugLen = 100 const maxSlugLen = 100
// reservedFirstSegments are paths a page could never be reached at, because // Paths Caddy or the SPA's routes answer first, plus "index". "shrines" and
// Caddy or one of the SPA's own routes answers them first (see // "stp" are canvas pages, so not reserved.
// caddy/routes.caddy and vue/src/router/index.js), plus the
// landing page's key "index", whose boxes a page of the same slug would
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
// pages under it and the home page /stp are all canvas pages.
var reservedFirstSegments = map[string]bool{ var reservedFirstSegments = map[string]bool{
"stp2": true, "index": true, "admin": true, "cv": true, "stp2": true, "index": true, "admin": true, "cv": true,
"automata": true, "hotels": true, "api": true, "py": true, "radio": true, "automata": true, "hotels": true, "api": true, "py": true, "radio": true,
@@ -51,9 +44,7 @@ func validateSlug(slug string) error {
return nil return nil
} }
// pageHiddenFrom reports whether the page with this key is an adminOnly page // A key with no Page row is never hidden.
// and the caller is not an admin. A key with no Page row (the landing page,
// or a page that doesn't exist) is not hidden.
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) { func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
if IsAdminFromCtx(ctx) { if IsAdminFromCtx(ctx) {
return false, nil return false, nil
@@ -63,9 +54,7 @@ func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error)
return count > 0, err return count > 0, err
} }
// slugTaken reports whether a live page other than exceptID has this slug. // Checked up front for a readable error; the partial unique index backs it.
// Checked up front so the admin gets a sentence rather than a constraint
// violation; the partial unique index still backs it up.
func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) { func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) {
var count int64 var count int64
err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error
+1 -4
View File
@@ -14,10 +14,7 @@ import (
// CreatePlace is the resolver for the createPlace field. // CreatePlace is the resolver for the createPlace field.
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) { func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
// Any signed-in user, not just an admin — places are the one shared, // @signedIn: places are the site's one shared list, with no ownership.
// collaboratively edited list on the site, so the schema marks these
// fields @signedIn rather than @admin. There is no per-user ownership, so
// any signed-in user can edit or delete any place.
place := models.Place{ place := models.Place{
Title: input.Title, Title: input.Title,
Location: input.Location, Location: input.Location,
+4 -16
View File
@@ -16,16 +16,12 @@ import (
// CreatePost is the resolver for the createPost field. // CreatePost is the resolver for the createPost field.
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) { func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
// @admin has already established that there is a session; the id is read
// here because the post needs an author, not as a second gate. The !ok
// branch is only reachable with a token that has admin but no usable id.
userID, ok := UserIDFromCtx(ctx) userID, ok := UserIDFromCtx(ctx)
if !ok { if !ok {
return nil, fmt.Errorf("unauthorized") return nil, fmt.Errorf("unauthorized")
} }
// The admin form submits whatever is in its fields, so an accidental click // Stops a stray click publishing a blank post.
// on an empty form would otherwise publish a blank post to the feed.
if strings.TrimSpace(input.Title) == "" { if strings.TrimSpace(input.Title) == "" {
return nil, fmt.Errorf("a post needs a title") return nil, fmt.Errorf("a post needs a title")
} }
@@ -50,15 +46,12 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
return nil, fmt.Errorf("post not found") return nil, fmt.Errorf("post not found")
} }
// Admin alone (the @admin on the field) is not enough: a post may only be // Only the author may edit, even among admins.
// edited by its author, so one admin cannot rewrite another's posts. This
// is the kind of rule a directive cannot express, so it stays here.
if post.AuthorID != userID { if post.AuthorID != userID {
return nil, fmt.Errorf("you can only update your own posts") return nil, fmt.Errorf("you can only update your own posts")
} }
// Both fields are non-pointer in the input, so this is a full replace — // Full replace: an omitted field is blanked.
// omitting one in the mutation blanks it rather than leaving it alone.
post.Title = input.Title post.Title = input.Title
post.Content = input.Content post.Content = input.Content
if err := r.Store.DB.Save(&post).Error; err != nil { if err := r.Store.DB.Save(&post).Error; err != nil {
@@ -84,9 +77,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
return nil, fmt.Errorf("you can only delete your own posts") return nil, fmt.Errorf("you can only delete your own posts")
} }
// Soft delete. The error is propagated: reporting success for a delete
// that did not happen would leave the client showing the post as gone
// until the next reload.
if err := r.Store.DB.Delete(&post).Error; err != nil { if err := r.Store.DB.Delete(&post).Error; err != nil {
return nil, err return nil, err
} }
@@ -96,9 +86,7 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
// Posts is the resolver for the posts field. // Posts is the resolver for the posts field.
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) { func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
// Preload issues a second query for the authors and fills in Post.Author. // Without Preload, author resolves to null silently.
// Without it the field is nil and the schema's author field resolves to
// null — there is no lazy loading and no error to tell you why.
var posts []models.Post var posts []models.Post
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil { if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
return nil, err return nil, err
+1 -11
View File
@@ -7,17 +7,7 @@ import "adam-french.co.uk/backend/handlers"
// It serves as dependency injection for your app, add any dependencies you require // It serves as dependency injection for your app, add any dependencies you require
// here. // here.
// Resolver is the root of the GraphQL schema and the only dependency every // Resolver holds the same handlers.Store the REST handlers use.
// resolver has. Rather than listing dependencies individually it holds the
// same handlers.Store the REST handlers use, so GraphQL and REST share one
// database handle and one set of third-party caches.
//
// The generated code embeds *Resolver in per-type resolver structs, which is
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
// resolvers files. A type only gets one when a field of it needs a resolver:
// queryResolver and mutationResolver always, messageResolver and
// rowingResolver for their unsigned-to-Int fields. Most object types bind
// every field straight to the model and have none.
type Resolver struct { type Resolver struct {
Store *handlers.Store Store *handlers.Store
} }
-2
View File
@@ -21,8 +21,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
} }
// Time is the resolver for the time field. // Time is the resolver for the time field.
// Time is the resolver for the time field: total session seconds, narrowed
// from uint64 to GraphQL's Int.
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) { func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
return int(obj.Time), nil return int(obj.Time), nil
} }
+1 -7
View File
@@ -1,10 +1,4 @@
# The background behind a canvas page, keyed by the same page key as its # A page key's background; null for an adminOnly page unless admin.
# boxes ("index" for the landing page, or a Page's slug), so the landing
# page and every other canvas page are set the same way. Edited from the
# canvas's "Background" button; see models.Background.
#
# Anyone may read it, as part of the page, except that an adminOnly page's
# background is null to everyone but an admin.
type Background { type Background {
id: ID! id: ID!
+2 -10
View File
@@ -1,13 +1,5 @@
# Boxes on a canvas page: the landing page (page "index") or an # Boxes on a page key. Public reads, admin writes; adminOnly boxes go to
# admin-created Page (page = its slug; the home page /stp is the Page "stp"). # admins only. kind is "widget" or "html" (sandboxed iframe).
# Anyone may read a page's layout — it is the page — but only an admin may
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
# are px on a fixed 1400px-wide design canvas; see models.Box.
#
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
# componentId is linked to that Component: its html is the component's, and
# updateBox refuses to change it (component.graphql).
type Box { type Box {
id: ID! id: ID!
+2 -10
View File
@@ -1,13 +1,5 @@
# Components: named HTML boxes that can be placed on any canvas page, either # Named HTML boxes, placed as copies or linked (Box.componentId); linked boxes
# as a copy (an ordinary box) or linked (a Box whose componentId is set). # share only the html. Admin only, reads included.
# Linked boxes share only the html — editing a component changes every box
# linked to it — while title, geometry, frame and visibility stay each box's
# own. title, w, h, framed, shadow and adminOnly here are what a newly placed box
# starts with. See models.Component and graph/component_helpers.go.
#
# Admin only throughout, reads included, because a component may have been
# saved from an adminOnly note. A linked box's html still reaches visitors
# through the boxes query, which is the point.
type Component { type Component {
id: ID! id: ID!
+3 -14
View File
@@ -1,12 +1,5 @@
# Saved layouts: a named copy of one canvas page's boxes and background, # Saved snapshots of a page's boxes and background; loading copies them.
# which can be loaded onto any canvas page — the landing page ("index") or a # Admin only, reads included, since layouts keep adminOnly boxes.
# Page's slug. Loading copies: the new boxes belong to the target page, so
# editing a page afterwards never changes the layout or another page. Moving
# a layout is saving it on one page and loading it on another with
# replace: true. See models.Layout and graph/layout_helpers.go.
#
# Admin only throughout, reads included, because a layout keeps a page's
# adminOnly boxes along with the rest.
type Layout { type Layout {
id: ID! id: ID!
@@ -39,10 +32,6 @@ extend type Mutation {
# Renames it; what a layout holds never changes after it is saved. # Renames it; what a layout holds never changes after it is saved.
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
deleteLayout(id: ID!): Layout! @admin deleteLayout(id: ID!): Layout! @admin
# Copies the layout onto `page` and answers with that page's boxes. # replace: true first saves the page as a layout, then swaps in this one.
# replace: false adds the copies on top of what is there, leaving the
# background alone. replace: true first saves the page as a layout named
# "<page> before <layout>, <time>", then swaps its boxes and background
# for the layout's.
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
} }
+4 -29
View File
@@ -1,35 +1,10 @@
# Root of the GraphQL schema. # Root types; each file extends Query and Mutation. Use # comments, not """
# # (descriptions show up in introspection).
# Query and Mutation are declared here with no fields; every other file in this
# directory adds to them with `extend type Query` / `extend type Mutation`.
# That is what lets the schema be split one file per domain, matching the
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
#
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
# serialised as RFC 3339.
#
# These files are the source of truth: after editing one, run
# go run github.com/99designs/gqlgen generate
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
# Note that `#` comments like this one are invisible to clients; a `"""` block
# would become a schema description and show up in introspection.
scalar Time scalar Time
# Authorisation. There is no middleware in front of /graphql, so a field is # A field is public unless it has @admin or @signedIn (graph/directives.go).
# PUBLIC unless it carries one of these. Each is implemented once, in # directives_test.go enforces this for mutations.
# graph/directives.go, and runs before the field's resolver:
#
# @admin the request must carry an admin's access token
# (error: "admin access required")
# @signedIn any valid access token will do
# (error: "authentication required")
#
# Every mutation needs one of them unless it is deliberately public (login,
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
# which queries are guarded. Rules that are not a plain gate stay in the
# resolver: a post is only editable by its author, `me` answers for whoever is
# signed in, and `messages` filters private rows rather than refusing.
directive @admin on FIELD_DEFINITION directive @admin on FIELD_DEFINITION
directive @signedIn on FIELD_DEFINITION directive @signedIn on FIELD_DEFINITION
+2 -9
View File
@@ -3,15 +3,8 @@ package graph
// This file is hand-written and is never regenerated by gqlgen — it is not // This file is hand-written and is never regenerated by gqlgen — it is not
// named after a schema file, so `gqlgen generate` leaves it alone. // named after a schema file, so `gqlgen generate` leaves it alone.
// ptrs copies a slice of values into a slice of pointers to those values. // ptrs turns []T into []*T for gqlgen. Loading into []*T directly would
// // change the SQL GORM emits.
// Every list query loads rows with Find(&xs) into a []T and then has to hand
// gqlgen a []*T, because the schema returns lists of nullable objects. Taking
// &xs[i] is safe: the slice is never appended to after this point, so the
// backing array cannot move and the pointers stay valid.
//
// Loading straight into a []*T would avoid the copy but changes the query
// GORM emits, so the copy is kept deliberately.
func ptrs[T any](xs []T) []*T { func ptrs[T any](xs []T) []*T {
result := make([]*T, len(xs)) result := make([]*T, len(xs))
for i := range xs { for i := range xs {
+1 -5
View File
@@ -51,11 +51,7 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
} }
// SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field. // SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field.
// // False for non-admins.
// Admin-gated: false for everyone else, so this query leaks nothing. Admin is
// read from the access-token claims the AuthContextMiddleware resolved, not
// the database — the same trade-off AdminMiddleware makes (revocation waits
// for token expiry).
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) { func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
if r.Store.SpotifyClient != nil { if r.Store.SpotifyClient != nil {
return false, nil return false, nil
+1 -8
View File
@@ -5,10 +5,6 @@ import (
"github.com/zmb3/spotify/v2" "github.com/zmb3/spotify/v2"
) )
// Converters from the Spotify library's rich types to the deliberately narrow
// GraphQL types — the schema exposes only the handful of fields the home page
// renders.
// mapSpotifyImages keeps just the URLs of a set of album images. // mapSpotifyImages keeps just the URLs of a set of album images.
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage { func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
result := make([]*model.SpotifyImage, len(images)) result := make([]*model.SpotifyImage, len(images))
@@ -35,10 +31,7 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
} }
// mapRecentItems converts recently played history entries. // mapRecentItems converts recently played history entries.
// // A RecentlyPlayedItem holds a SimpleTrack, so mapSpotifyTrack can't be reused.
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
// takes — the duplication is forced by the library's types.
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem { func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
result := make([]*model.SpotifyRecentItem, len(items)) result := make([]*model.SpotifyRecentItem, len(items))
for i, item := range items { for i, item := range items {
+1 -4
View File
@@ -8,10 +8,7 @@ import (
) )
// mapSteamGames converts Steam API games into the GraphQL shape. // mapSteamGames converts Steam API games into the GraphQL shape.
// // Header images follow a predictable CDN path, saving an API call per game.
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
// serves every game's cover art at a predictable path keyed by app id, so
// building the URL here saves an extra API call per game.
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame { func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
result := make([]*model.SteamGame, len(games)) result := make([]*model.SteamGame, len(games))
for i, g := range games { for i, g := range games {
+4 -12
View File
@@ -18,9 +18,6 @@ import (
// CreateUser is the resolver for the createUser field. // CreateUser is the resolver for the createUser field.
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) { func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
// Only an existing admin can create accounts (@admin in the schema) —
// there is no public sign-up. New users are created non-admin;
// setUserAdmin promotes them.
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -55,8 +52,7 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return nil, fmt.Errorf("unauthorized") return nil, fmt.Errorf("unauthorized")
} }
// Guards against the last admin demoting themselves and locking everyone // Stops the last admin locking everyone out.
// out of the admin UI.
if uint(id) == callerID { if uint(id) == callerID {
return nil, fmt.Errorf("cannot change your own admin status") return nil, fmt.Errorf("cannot change your own admin status")
} }
@@ -76,10 +72,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
// SetUserPermissions is the resolver for the setUserPermissions field. // SetUserPermissions is the resolver for the setUserPermissions field.
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) { func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
// The whole list is replaced, so the admin panel sends every ticked box // Full replace. Unknown keys are refused so a stale UI can't silently
// each time. An unknown key is refused rather than dropped, so a stale // save less than it showed.
// front end cannot silently save less than it showed. The stored list is
// rebuilt in registry order, which also drops duplicates.
want := map[string]bool{} want := map[string]bool{}
for _, key := range permissions { for _, key := range permissions {
if !services.ValidPermission(key) { if !services.ValidPermission(key) {
@@ -99,8 +93,7 @@ func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permi
return nil, fmt.Errorf("user not found") return nil, fmt.Errorf("user not found")
} }
// No token bump needed: the permission gate reads this column on every // No token bump: the gate reads this column on every request.
// request, so the change applies to the user's next one.
user.Permissions = granted user.Permissions = granted
if err := r.Store.DB.Save(&user).Error; err != nil { if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err return nil, err
@@ -129,6 +122,5 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
// PermissionTypes is the resolver for the permissionTypes field. // PermissionTypes is the resolver for the permissionTypes field.
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) { func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
// A copy, so nothing downstream can write through to the registry.
return ptrs(slices.Clone(services.PermissionTypes)), nil return ptrs(slices.Clone(services.PermissionTypes)), nil
} }
+33 -132
View File
@@ -12,62 +12,36 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
// This file holds the REST authentication endpoints and the Gin middleware // REST auth endpoints and middleware. GraphQL's login/logout/refresh live in
// that guards the other REST routes. GraphQL has its own parallel // graph/auth.resolvers.go; both mint cookies through services.Auth.
// implementation of login/logout/refresh in graph/auth.resolvers.go; both
// mint the same cookies through services.Auth.
//
// Cookie model: `access_token` is short-lived and carries id + admin, so most
// requests authorise without a database hit; `refresh_token` carries only the
// id and is exchanged for a fresh pair. Both are set HttpOnly and Secure, so
// JavaScript cannot read them and the browser attaches them automatically.
// UserCredentials is the JSON body of POST /auth/login. The binding tags make
// Gin reject a request missing either field.
type UserCredentials struct { type UserCredentials struct {
Username string `json:"username" binding:"required"` Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"` Password string `json:"password" binding:"required"`
} }
// AuthMiddlewear requires a valid access token on a REST route and stashes // AuthMiddleware requires a valid, unrevoked access token. It does not fall
// the claims for AdminMiddleware to read. // back to the refresh token: the client refreshes and retries on 401.
// func (store *Store) AuthMiddleware(ctx *gin.Context) {
// (The name is misspelled but it is exported and referenced from main.go, so
// it is left alone rather than renamed.)
//
// It deliberately does NOT fall back to the refresh token: an expired access
// token yields a 401 and the front end is expected to call /auth/refresh and
// retry. A token whose version has been revoked is also a 401.
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token") access_token, err := ctx.Cookie("access_token")
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"}) ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return return
} }
// Validated against the database, not just cryptographically: that is
// what makes a logged-out or password-changed token stop working here
// rather than lingering until it expires.
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token) _, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
if err != nil { if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"}) ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return return
} }
// Stored under a plain string key in the *Gin* context. This is a // Gin context key; graph/context.go uses its own, separate mechanism.
// different mechanism from graph/context.go, which puts the same claims
// into the standard library request context under an unexported typed
// key; the two do not see each other's values.
ctx.Set("userClaims", claims) ctx.Set("userClaims", claims)
ctx.Next() ctx.Next()
} }
// AdminMiddleware requires the access token to carry admin=true. It must be // AdminMiddleware must follow AuthMiddleware, whose claims carry the row's
// chained after AuthMiddlewear, which is what populates "userClaims"; on its // admin flag.
// own it always rejects.
//
// Admin is read from the token, not the database, so revoking someone's admin
// flag only takes effect once their current access token expires.
func (store *Store) AdminMiddleware(ctx *gin.Context) { func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims") claims, exists := ctx.Get("userClaims")
if !exists { if !exists {
@@ -81,8 +55,7 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
return return
} }
// A token minted before the admin claim existed simply has no "admin" // Tokens minted before the admin claim have none: not an admin.
// key, so a failed type assertion is treated as "not an admin".
admin, ok := (*mapClaims)["admin"].(bool) admin, ok := (*mapClaims)["admin"].(bool)
if !ok || !admin { if !ok || !admin {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"}) ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
@@ -92,37 +65,18 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
ctx.Next() ctx.Next()
} }
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to // ValidateAdmin answers 200/403/401 with no body, for the SPA, Caddy's admin
// decide whether to show admin UI, Caddy's admin gate calls as an // gate and the jobs container. It falls back to the refresh token and may
// auth_request, and the jobs container calls with the visitor's cookies. It // mint new cookies, so a returning admin needn't log in again.
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
// new cookie pair as a side effect, so a returning admin is recognised
// without a visible re-login.
func (store *Store) ValidateAdmin(ctx *gin.Context) { func (store *Store) ValidateAdmin(ctx *gin.Context) {
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool { store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
// On the access-token path admin is read from the token, as return user.Admin
// everywhere else; on the refresh path there is no admin claim, and
// the row is what makes that path pick up a revoked admin flag.
if claims == nil {
return user.Admin
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
}) })
} }
// ValidatePermission backs GET /auth/validate/:permission, Caddy's permission // ValidatePermission backs Caddy's permission gate, like ValidateAdmin but
// gate (see services/permissions.go). Same bare-status contract and refresh // reading the user row. An unknown key is 404, so a typo in a Caddy route
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the // fails visibly rather than looking like a missing grant.
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in a Caddy route fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The decision reads the user row, not the token, for admins as well: a
// grant, a revoke or a demotion applies on the very next request.
func (store *Store) ValidatePermission(ctx *gin.Context) { func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission") key := ctx.Param("permission")
if !services.ValidPermission(key) { if !services.ValidPermission(key) {
@@ -134,17 +88,9 @@ func (store *Store) ValidatePermission(ctx *gin.Context) {
}) })
} }
// validateSession is the body shared by the two validate endpoints: identify // validateSession identifies the caller by access token, else refresh token
// the caller from the access token, or failing that the refresh token, and // (allow then gets nil claims), and answers 200/403/401. On 200 the username
// answer 200 / 403 / 401 according to allow. // goes in X-Auth-User for Caddy to pass upstream.
//
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which Caddy's forward_auth
// copies onto the proxied request (as X-Remote-User for /receipt/), so the
// service behind the gate knows who is using it without having accounts of
// its own.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) { 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 {
@@ -160,27 +106,19 @@ func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *
} }
} }
// No access token, or an expired, invalid or revoked one — try refreshing.
if !store.tryRefreshAndValidate(ctx, allow) { if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized) ctx.Status(http.StatusUnauthorized)
} }
} }
// tryRefreshAndValidate re-authenticates from the refresh token. // tryRefreshAndValidate returns whether it wrote the response (200 or 403),
// // not whether access is allowed. On false the caller sends 401.
// The bool does not mean "allowed" — it means "this function already wrote
// the response". It returns true both for a successful refresh (200, new
// cookies set) and for a valid but unauthorised user (403, no new cookies),
// and false only when it could not decide, leaving the caller to send 401.
// Getting this backwards would send two status codes for one request.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool { func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token") refreshToken, err := ctx.Cookie("refresh_token")
if err != nil { if err != nil {
return false return false
} }
// Any failure at all (bad token, unknown user, revoked version) is
// "cannot decide" here, exactly as before: the caller sends 401.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken) user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil { if err != nil {
return false return false
@@ -203,17 +141,12 @@ func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.U
return true return true
} }
// setAuthCookies writes the access/refresh cookie pair. The cookie
// attributes live in services.SetAuthCookies so that REST and GraphQL cannot
// disagree about them; this method is just the Store-shaped spelling of it.
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) { func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
services.SetAuthCookies(ctx, store.Auth.Config, tokens) services.SetAuthCookies(ctx, store.Auth.Config, tokens)
} }
// CheckToken backs GET /auth/check: it returns the current user for a valid // CheckToken returns the current user. A valid token for a deleted user gets
// access token, or 401. If the token is valid but the user no longer exists // 404 and cleared cookies.
// it answers 404 and clears the cookies, so the browser stops presenting a
// token for a deleted account.
func (store *Store) CheckToken(ctx *gin.Context) { func (store *Store) CheckToken(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token") access_token, err := ctx.Cookie("access_token")
if err != nil { if err != nil {
@@ -221,11 +154,6 @@ func (store *Store) CheckToken(ctx *gin.Context) {
return return
} }
// Status codes here are unchanged from the hand-rolled version: a bad
// token or bad claims are both 401, and only a missing user is 404 with
// the cookies cleared. A revoked (out-of-date version) token joins the
// 401 case, since from the client's point of view it is simply no longer
// a valid token.
user, err := store.Auth.AuthenticateToken(store.DB, access_token) user, err := store.Auth.AuthenticateToken(store.DB, access_token)
if err != nil { if err != nil {
if errors.Is(err, services.ErrUserNotFound) { if errors.Is(err, services.ErrUserNotFound) {
@@ -241,11 +169,8 @@ func (store *Store) CheckToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, user) ctx.JSON(http.StatusOK, user)
} }
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token // RefreshToken exchanges the refresh token for a new pair. It is not rotated,
// for a new cookie pair and returns the user. // but logout and password changes revoke it via the token version.
//
// The old refresh token is not rotated, but it does die when the user logs out
// or changes their password, because those bump the token version this checks.
func (store *Store) RefreshToken(ctx *gin.Context) { func (store *Store) RefreshToken(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token") refreshToken, err := ctx.Cookie("refresh_token")
if err != nil { if err != nil {
@@ -253,11 +178,6 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
return return
} }
// The three outcomes below preserve the original status codes exactly:
// an unusable token is 401, unreadable claims are 500, and a token for a
// user that no longer exists is 404 with the cookies cleared. A revoked
// token is treated as an unusable one (401) — the client's correct
// response is to log in again.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken) user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil { if err != nil {
switch { switch {
@@ -285,13 +205,9 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
ctx.JSON(http.StatusAccepted, user) ctx.JSON(http.StatusAccepted, user)
} }
// Login backs POST /auth/login. The user object it returns omits the password
// because models.User tags that field `json:"-"`.
func (store *Store) Login(ctx *gin.Context) { func (store *Store) Login(ctx *gin.Context) {
// Per-IP limit (5/min) on top of Caddy's own login rate limit. // On top of Caddy's limit. ClientIP is trustworthy because main.go pins
// ctx.ClientIP is only trustworthy because main.go pins the trusted // the trusted proxy range.
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
// 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
@@ -303,9 +219,7 @@ func (store *Store) Login(ctx *gin.Context) {
return return
} }
// Unknown user and wrong password return the identical message, so the // Same message for unknown user and wrong password.
// response cannot be used to enumerate usernames. (The timing does
// differ, since only the second path runs bcrypt.)
user := models.User{} user := models.User{}
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil { if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"}) ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
@@ -329,13 +243,8 @@ func (store *Store) Login(ctx *gin.Context) {
ctx.JSON(http.StatusAccepted, user) ctx.JSON(http.StatusAccepted, user)
} }
// Logout backs POST /auth/logout. As well as clearing the browser's cookies // Logout clears the cookies and bumps the token version, revoking every copy
// it bumps the user's token version, so the tokens it just discarded — and // of the tokens. Always 200.
// any copy taken beforehand — stop being accepted immediately.
//
// It always answers 200: identifying the caller is best effort (the cookies
// may already be gone or expired), and a client that cannot be identified has
// nothing to revoke anyway.
func (store *Store) Logout(ctx *gin.Context) { func (store *Store) Logout(ctx *gin.Context) {
store.revokeCallerTokens(ctx) store.revokeCallerTokens(ctx)
store.removeCookies(ctx) store.removeCookies(ctx)
@@ -343,12 +252,8 @@ func (store *Store) Logout(ctx *gin.Context) {
ctx.Status(http.StatusOK) ctx.Status(http.StatusOK)
} }
// revokeCallerTokens bumps the token version of whoever made this request, // revokeCallerTokens verifies the token before bumping, or a forged cookie
// identified from the access token or, failing that, the refresh token. // could revoke any user's sessions.
//
// It deliberately verifies the token rather than just reading the id out of
// it: without that, anyone could bump an arbitrary user's version by posting a
// forged cookie, which is a denial-of-service on that account's sessions.
func (store *Store) revokeCallerTokens(ctx *gin.Context) { func (store *Store) revokeCallerTokens(ctx *gin.Context) {
for _, name := range []string{"access_token", "refresh_token"} { for _, name := range []string{"access_token", "refresh_token"} {
token, err := ctx.Cookie(name) token, err := ctx.Cookie(name)
@@ -360,16 +265,12 @@ func (store *Store) revokeCallerTokens(ctx *gin.Context) {
continue continue
} }
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil { if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
// Logged rather than returned: the cookies are still cleared, but
// this means the logout did not actually revoke anything.
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err) log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
} }
return return
} }
} }
// removeCookies expires both auth cookies; see services.ClearAuthCookies for
// why the attributes have to match those used when setting them.
func (store *Store) removeCookies(ctx *gin.Context) { func (store *Store) removeCookies(ctx *gin.Context) {
services.ClearAuthCookies(ctx, store.Auth.Config) services.ClearAuthCookies(ctx, store.Auth.Config)
} }
+2 -7
View File
@@ -7,10 +7,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// GetNoteFile serves one file from the notes directory for the admin-only // GetNoteFile: Notes.ParsePath does the containment check.
// route GET /notes/*path. The wildcard means `path` arrives with a leading
// slash and may contain further slashes, so it has to be validated rather
// than trusted — Notes.ParsePath does the containment check.
func (store *Store) GetNoteFile(ctx *gin.Context) { func (store *Store) GetNoteFile(ctx *gin.Context) {
path := ctx.Param("path") path := ctx.Param("path")
@@ -29,9 +26,7 @@ func (store *Store) GetNoteFile(ctx *gin.Context) {
return return
} }
// The SPA reads Last-Modified to show a note's edit date. Browsers hide // Exposed so cross-origin fetch() can read it.
// non-safelisted headers from cross-origin fetch() unless they are listed
// in Access-Control-Expose-Headers, hence the second header.
ctx.Header("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat)) ctx.Header("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
ctx.Header("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified") ctx.Header("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified")
+13 -41
View File
@@ -9,27 +9,18 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Admin management of the radio's fallback music. These handlers only move // Radio fallback music management. Disabled songs live in a "disabled"
// files around on disk; the Python service is what actually streams them, and // subdirectory: that is the whole of the radio's state.
// it picks up the directory contents on its own.
//
// Disabling a song moves it into a "disabled" subdirectory rather than
// deleting it — so presence in that directory IS the disabled flag, and there
// is no database state for the radio at all.
// fallbackMusicDir is a shared volume, also mounted by the radio service.
const fallbackMusicDir = "/backend/fallback_music" const fallbackMusicDir = "/backend/fallback_music"
// allowedAudioExtensions is the upload allow-list, keyed by lower-cased // Not sniffed: admin-only, and audio sniffs unreliably.
// extension. Unlike chat uploads, the content is not sniffed: the route is
// admin-only and audio formats sniff unreliably.
var allowedAudioExtensions = map[string]bool{ var allowedAudioExtensions = map[string]bool{
".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true, ".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true,
} }
// UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat // UploadRadioSong keeps the original filename, which the admin sees, so it is
// uploads the original filename is kept, because it is what the admin sees in // sanitised.
// the song list — hence the sanitisation below.
func (store *Store) UploadRadioSong(ctx *gin.Context) { func (store *Store) UploadRadioSong(ctx *gin.Context) {
file, err := ctx.FormFile("file") file, err := ctx.FormFile("file")
if err != nil { if err != nil {
@@ -49,22 +40,18 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
return return
} }
// filepath.Base strips any directory component, so "../../etc/passwd" // Base strips traversal; the absolute-path check below is a second guard.
// becomes "passwd". The absolute-path check below is a second, redundant
// guard in case Base ever fails to neutralise some input.
filename := filepath.Base(file.Filename) filename := filepath.Base(file.Filename)
dest := filepath.Join(fallbackMusicDir, filename) dest := filepath.Join(fallbackMusicDir, filename)
// The separator is appended before comparing so a sibling directory whose // The trailing separator stops a same-prefix sibling directory passing.
// name merely starts with the same characters cannot pass.
absDest, err := filepath.Abs(dest) absDest, err := filepath.Abs(dest)
if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) { if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"}) ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return return
} }
// Refuse to overwrite. There is a check-then-write race here, but the // Check-then-write race accepted: admin-only.
// route is admin-only and single-user in practice.
if _, err := os.Stat(dest); err == nil { if _, err := os.Stat(dest); err == nil {
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"}) ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
return return
@@ -78,11 +65,7 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"name": filename}) ctx.JSON(http.StatusOK, gin.H{"name": filename})
} }
// ListRadioSongs backs the admin-only GET /radio/songs, returning both the
// enabled songs and those parked in the disabled subdirectory, flagged.
func (store *Store) ListRadioSongs(ctx *gin.Context) { func (store *Store) ListRadioSongs(ctx *gin.Context) {
// Declared inside the function because it is purely the JSON shape of
// this one response.
type songInfo struct { type songInfo struct {
Name string `json:"name"` Name string `json:"name"`
Size int64 `json:"size"` Size int64 `json:"size"`
@@ -90,17 +73,15 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
Disabled bool `json:"disabled"` Disabled bool `json:"disabled"`
} }
// Initialised empty rather than nil so the response is [] and not null. // [] not null in the JSON.
songs := []songInfo{} songs := []songInfo{}
// Read enabled songs
entries, err := os.ReadDir(fallbackMusicDir) entries, err := os.ReadDir(fallbackMusicDir)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"}) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"})
return return
} }
// Skipping directories is also what keeps the "disabled" subdirectory out // Skipping directories also skips "disabled".
// of the enabled list; dotfiles skip editor and OS cruft.
for _, entry := range entries { for _, entry := range entries {
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") { if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
continue continue
@@ -117,9 +98,7 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
}) })
} }
// The disabled directory is created lazily by DisableRadioSong, so a read // Created lazily, so a missing directory just means none disabled.
// failure here is normally just "nothing has ever been disabled" and is
// ignored rather than reported.
disabledDir := filepath.Join(fallbackMusicDir, "disabled") disabledDir := filepath.Join(fallbackMusicDir, "disabled")
disabledEntries, err := os.ReadDir(disabledDir) disabledEntries, err := os.ReadDir(disabledDir)
if err == nil { if err == nil {
@@ -143,12 +122,8 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"songs": songs}) ctx.JSON(http.StatusOK, gin.H{"songs": songs})
} }
// DisableRadioSong moves a song into the disabled subdirectory so the radio
// stops playing it, keeping the file.
func (store *Store) DisableRadioSong(ctx *gin.Context) { func (store *Store) DisableRadioSong(ctx *gin.Context) {
// filepath.Base neutralises traversal in the :filename route parameter. // Base returns "." or "/" for degenerate input; both are rejected.
// It returns "." for an empty input and "/" for "/", neither of which is
// a real file, so both are rejected explicitly.
filename := filepath.Base(ctx.Param("filename")) filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" { if filename == "." || filename == "/" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"}) ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
@@ -176,7 +151,6 @@ func (store *Store) DisableRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"disabled": filename}) ctx.JSON(http.StatusOK, gin.H{"disabled": filename})
} }
// EnableRadioSong moves a song back out of the disabled subdirectory.
func (store *Store) EnableRadioSong(ctx *gin.Context) { func (store *Store) EnableRadioSong(ctx *gin.Context) {
filename := filepath.Base(ctx.Param("filename")) filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" { if filename == "." || filename == "/" {
@@ -199,9 +173,7 @@ func (store *Store) EnableRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"enabled": filename}) ctx.JSON(http.StatusOK, gin.H{"enabled": filename})
} }
// DeleteRadioSong permanently removes an enabled song. It cannot reach the // DeleteRadioSong can't reach disabled songs; enable one first.
// disabled subdirectory, so a disabled song must be enabled before it can be
// deleted.
func (store *Store) DeleteRadioSong(ctx *gin.Context) { func (store *Store) DeleteRadioSong(ctx *gin.Context) {
filename := filepath.Base(ctx.Param("filename")) filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" { if filename == "." || filename == "/" {
+22 -68
View File
@@ -15,51 +15,30 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Rowing log. The interesting endpoint is CreateRowing: rather than a form, // CreateRowing reads a photo of the rowing machine display. The Claude call
// the admin uploads a photo of the rowing machine display and Claude reads the // is in python/app/rowing.py; auth, EXIF, dedup and bounds checks stay here.
// numbers off it. The session date comes from the photo's EXIF metadata, which
// also doubles as the deduplication key.
//
// The Claude call itself lives in the Python service (python/app/rowing.py),
// reached directly over the Docker network. Everything that needs the session
// or the database — the admin gate, EXIF, the duplicate check, the sanity
// bounds, the insert — stays here.
// ExtractedRowingData is the JSON contract for what Claude reads off the // ExtractedRowingData matches RowingReading in python/app/rowing.py.
// display: the body of the Python service's reply, whose keys are the ones
// its prompt asks the model for (RowingReading in python/app/rowing.py).
type ExtractedRowingData struct { type ExtractedRowingData struct {
TimeMinutes uint64 `json:"timeMinutes"` TimeMinutes uint64 `json:"timeMinutes"`
TimeSeconds uint64 `json:"timeSeconds"` TimeSeconds uint64 `json:"timeSeconds"`
Distance uint64 `json:"distance"` Distance uint64 `json:"distance"`
} }
// rowingReadPath is the Python route. It is internal: Caddy refuses // Internal: Caddy refuses /py/internal/, so only a direct container call works.
// /py/internal/ and the route itself refuses anything Caddy forwarded, so the
// only way in is the direct container-to-container call services.CallPython
// makes.
const rowingReadPath = "/internal/rowing/read" const rowingReadPath = "/internal/rowing/read"
// readRowingDisplay sends the image to the Python service and returns what
// Claude read off it. No plausibility checking happens on either side of this
// call; that is CreateRowing's job. A failure the reader described in its own
// words comes back as a *services.PythonError (see services.CallPython).
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) { func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
// Data is a []byte so that it is sent as standard base64, the encoding // []byte marshals as standard base64, as the Anthropic API expects.
// the Anthropic API expects.
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct { return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
MediaType string `json:"media_type"` MediaType string `json:"media_type"`
Data []byte `json:"data"` Data []byte `json:"data"`
}{mediaType, image}) }{mediaType, image})
} }
// GetRowing backs the public GET /rowing with every logged session, newest
// first.
func (store *Store) GetRowing(ctx *gin.Context) { func (store *Store) GetRowing(ctx *gin.Context) {
var rowing []models.Rowing var rowing []models.Rowing
// "Created_At" works because Postgres folds unquoted identifiers to lower if err := store.DB.Order("created_at DESC").Find(&rowing).Error; err != nil {
// case; the column is created_at.
if err := store.DB.Order("Created_At DESC").Find(&rowing).Error; err != nil {
log.Println(err) log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"}) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return return
@@ -67,13 +46,8 @@ func (store *Store) GetRowing(ctx *gin.Context) {
ctx.JSON(http.StatusOK, rowing) ctx.JSON(http.StatusOK, rowing)
} }
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the // CreateRowing is admin-only, so its checks target misreadings, not hostile
// rowing machine display, dates it from EXIF, has Claude read the time and // input.
// distance (via the Python service), sanity-checks the result and stores a
// session.
//
// Note it is admin-gated and costs a paid API call once per request, so the
// validation below exists to catch misreadings rather than hostile input.
func (store *Store) CreateRowing(ctx *gin.Context) { func (store *Store) CreateRowing(ctx *gin.Context) {
file, err := ctx.FormFile("image") file, err := ctx.FormFile("image")
if err != nil { if err != nil {
@@ -88,9 +62,7 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
} }
defer f.Close() defer f.Close()
// EXIF is required, not optional: it is both the session date and the // EXIF is required: it is both the session date and the duplicate key.
// duplicate key, so a stripped-metadata image (anything that has been
// through most messaging apps) is rejected outright.
exifData, err := exif.Decode(f) exifData, err := exif.Decode(f)
if err != nil { if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"}) ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
@@ -103,19 +75,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return return
} }
// exif.Decode consumed part of the stream, so rewind before reading the
// bytes to send on for reading.
if _, err := f.Seek(0, io.SeekStart); err != nil { if _, err := f.Seek(0, io.SeekStart); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"}) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
return return
} }
// Cap the upload before buffering it (and then base64-encoding it, 1.33x // Bounded before buffering, to cap memory and the paid API call.
// bigger, on its way to the Python service): the route is admin-only but const maxPhotoSize = 10 << 20
// an unbounded read would still let a giant file exhaust the Pi's memory if file.Size > maxPhotoSize {
// and produce a huge paid API call. 10MB is well above any photo this
// endpoint is meant to take; the Python side's own limit is sized from it.
if file.Size > 10<<20 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"}) ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
return return
} }
@@ -132,24 +99,16 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
"image/gif": true, "image/gif": true,
"image/webp": true, "image/webp": true,
} }
// This is the browser's claimed type, not a sniffed one; it is passed // The browser's claimed type, checked only to keep the API call
// straight through to the Anthropic API, so the allow-list is there to // well-formed and give a clear 400.
// keep the API call well-formed rather than to police the file. The
// Python service enforces the same list; checking here first gives the
// admin a clear 400 instead of that side's validation error.
mediaType := file.Header.Get("Content-Type") mediaType := file.Header.Get("Content-Type")
if !allowedMediaTypes[mediaType] { if !allowedMediaTypes[mediaType] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"}) ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
return return
} }
// Duplicate guard: two photos of the same session share an EXIF capture // Checked before the paid call. Fails closed: only ErrRecordNotFound
// time to the second. Checked before the Claude call so a re-upload costs // means "no duplicate".
// nothing.
//
// Fails closed: only gorm.ErrRecordNotFound means "no duplicate". Any
// other error is a real database problem, and treating it as "not found"
// would both insert a duplicate and spend a paid Claude call to do it.
var existing models.Rowing var existing models.Rowing
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
switch { switch {
@@ -165,9 +124,7 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data) extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
// The reader's own messages ("failed to parse image data", ...) are // Pass on the reader's own messages; hide plumbing failures.
// passed on; anything else is a plumbing failure the admin can do
// nothing with.
msg := "failed to process image" msg := "failed to process image"
var readErr *services.PythonError var readErr *services.PythonError
if errors.As(err, &readErr) { if errors.As(err, &readErr) {
@@ -184,10 +141,8 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
// Sanity bounds on what Claude claims to have read. A misread digit // A misread digit usually lands outside human performance; the pace check
// typically lands far outside human rowing performance, and the pace // catches plausible time and distance that disagree.
// check catches the case where time and distance are individually
// plausible but inconsistent with each other.
const ( const (
minDistance = 100 // metres minDistance = 100 // metres
maxDistance = 100000 // metres maxDistance = 100000 // metres
@@ -211,10 +166,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return return
} }
// Rough calorie estimate from distance alone: roughly 500 kcal per // A display-only estimate, ~500 kcal per 7500 m.
// 7500 m. Not from the machine and not physiologically derived — it is a const kcalPerMetre = 500.0 / 7500.0
// display figure only. calories := float64(extractedData.Distance) * kcalPerMetre
calories := float64(extractedData.Distance) / 7500.0 * 500.0
rowing := models.Rowing{ rowing := models.Rowing{
Date: dateTaken, Date: dateTaken,
+9 -37
View File
@@ -10,35 +10,22 @@ import (
"github.com/zmb3/spotify/v2" "github.com/zmb3/spotify/v2"
) )
// These REST endpoints predate the equivalent GraphQL queries in // The callback must be REST (Spotify redirects a browser to it); the rest
// graph/spotify.resolvers.go and are kept for the OAuth callback (which must // predate the GraphQL equivalents.
// be REST, because Spotify redirects a browser to it) and for direct use.
// CompleteSpotifyAuth handles Spotify's OAuth redirect to // CompleteSpotifyAuth installs the client on the Store, so no restart is needed.
// GET /spotify/callback. It swaps the code for a token, saves it so the
// authorisation survives restarts, and installs the authenticated client on
// the Store — which is how Store.SpotifyClient becomes non-nil without a
// restart.
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) { func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
state := ctx.Query("state") state := ctx.Query("state")
// CSRF check: the state must be a nonce this process handed out from // The real CSRF check: the library compares state against the value we
// StartSpotifyAuth and has not seen come back yet. Without it, anyone who // pass it, which is the one just received.
// could get the site owner's browser to hit this URL with an attacker's
// authorisation code would bind the site to the attacker's Spotify
// account. The library also compares the state to the value passed below,
// but since that value is the one just received, this check is the real
// one.
if !store.ConsumeSpotifyState(state) { if !store.ConsumeSpotifyState(state) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"}) ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
return return
} }
// context.Background, not the request context: the client built below // The client outlives this request.
// outlives this request and would otherwise be cancelled when it ends.
c := context.Background() c := context.Background()
// The library pulls the `code` out of the request itself and checks the
// state parameter matches the one passed here.
token, err := store.SpotifyAuth.Token(c, state, ctx.Request) token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
@@ -61,13 +48,7 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
}) })
} }
// StartSpotifyAuth backs the admin-only GET /spotify/auth. It returns the // StartSpotifyAuth returns the authorisation URL with a fresh state nonce.
// Spotify authorisation URL carrying a freshly minted one-shot state nonce,
// which CompleteSpotifyAuth then verifies and consumes.
//
// This exists because the state has to be per-request to be a CSRF defence,
// and the start of the flow therefore has to be a request rather than a line
// printed at start-up.
func (store *Store) StartSpotifyAuth(ctx *gin.Context) { func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
state, err := store.NewSpotifyState() state, err := store.NewSpotifyState()
if err != nil { if err != nil {
@@ -79,9 +60,6 @@ func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"url": store.SpotifyAuth.AuthURL(state)}) ctx.JSON(http.StatusOK, gin.H{"url": store.SpotifyAuth.AuthURL(state)})
} }
// ListeningTo backs GET /spotify/listening with the currently playing track.
// A nil client means the OAuth flow has never been completed, reported here
// as a 500.
func (store *Store) ListeningTo(ctx *gin.Context) { func (store *Store) ListeningTo(ctx *gin.Context) {
c := ctx.Request.Context() c := ctx.Request.Context()
@@ -100,9 +78,7 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
ctx.JSON(200, playing) ctx.JSON(200, playing)
} }
// RecentlyPlayed backs GET /spotify/recent, serving the shared one-minute // RecentlyPlayed shares its cache with the GraphQL spotifyRecent resolver.
// cache. Both this endpoint and the GraphQL spotifyRecent resolver go through
// RecentlyPlayedTracks, so either one can fill the cache for the other.
func (store *Store) RecentlyPlayed(ctx *gin.Context) { func (store *Store) RecentlyPlayed(ctx *gin.Context) {
if store.SpotifyClient == nil { if store.SpotifyClient == nil {
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"}) ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
@@ -119,11 +95,7 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
ctx.JSON(200, played) ctx.JSON(200, played)
} }
// RecentlyPlayedTracks returns the last few played tracks, from the cache when // RecentlyPlayedTracks requires a non-nil SpotifyClient.
// it is fresh and from Spotify otherwise — populating the cache in that case.
//
// This is the single fetch-and-cache path for recently-played data; the caller
// must have checked SpotifyClient is non-nil.
func (store *Store) RecentlyPlayedTracks(ctx context.Context) ([]spotify.RecentlyPlayedItem, error) { func (store *Store) RecentlyPlayedTracks(ctx context.Context) ([]spotify.RecentlyPlayedItem, error) {
if cached, ok := store.CachedRecentSongs(); ok { if cached, ok := store.CachedRecentSongs(); ok {
return cached, nil return cached, nil
+5 -25
View File
@@ -10,19 +10,8 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
// Upload backs POST /uploads (login required): the one endpoint the frontend // Upload stores a multipart `file` via services.Uploads.Save and returns its
// stores a file through (vue/src/uploads.js). Multipart form: // URL. `private` is admin-only, as private messages are.
//
// file the file (required)
// private "true" to store it as an admin-only chat attachment
//
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
// the file was refused (wrong type, too large) and 500 when storing failed.
// Validation, naming and storage are all services.Uploads.Save; this handler
// only reads the form and decides who may use `private`.
//
// `private` is admin-only because private messages themselves are: an
// attachment URL leaking out is the same disclosure as the message leaking.
func (store *Store) Upload(ctx *gin.Context) { func (store *Store) Upload(ctx *gin.Context) {
private := ctx.PostForm("private") == "true" private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) { if private && !requestIsAdmin(ctx) {
@@ -49,12 +38,7 @@ func (store *Store) Upload(ctx *gin.Context) {
} }
} }
// ListUploads backs GET /uploads (admin): every public upload, newest first, // ListUploads is admin-only: listing is what turns unguessable URLs into known ones.
// for the upload picker on the canvas pages (vue/src/components/util/
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
//
// Admin-only because the listing is the one thing that turns unguessable
// upload URLs into known ones; see services.Uploads.List.
func (store *Store) ListUploads(ctx *gin.Context) { func (store *Store) ListUploads(ctx *gin.Context) {
files, err := store.Uploads.List(ctx.Request.Context()) files, err := store.Uploads.List(ctx.Request.Context())
if err != nil { if err != nil {
@@ -68,12 +52,8 @@ func (store *Store) ListUploads(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"files": files}) ctx.JSON(http.StatusOK, gin.H{"files": files})
} }
// requestIsAdmin reports whether the caller's access token carries admin=true. // requestIsAdmin: this route is in `protected`, not `admin`, since any
// // signed-in user may upload public files.
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool { func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims") claims, exists := ctx.Get("userClaims")
if !exists { if !exists {
+7 -33
View File
@@ -12,24 +12,8 @@ import (
"github.com/zmb3/spotify/v2" "github.com/zmb3/spotify/v2"
) )
// What is deliberately NOT covered here, and why: // Handlers needing a live DB, multipart requests or container paths aren't
// // covered here.
// - Every handler method (Login, Upload, the radio file movers,
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
// multipart request, the container's /backend/... directories, or a paid
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
// CI.
// - The radio upload's filename sanitisation. It is written inline in the
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
// the radio allow-list.
// --- Spotify OAuth CSRF nonces ------------------------------------------- // --- Spotify OAuth CSRF nonces -------------------------------------------
@@ -115,15 +99,13 @@ func TestNewSpotifyStatePrunesExpired(t *testing.T) {
// --- Cache TTL rules ------------------------------------------------------ // --- Cache TTL rules ------------------------------------------------------
// Each cache treats "empty" as stale, which is deliberate (an empty listening // Empty counts as stale on purpose; pinned so it isn't "fixed".
// history or games list is re-fetched rather than cached). These tables pin
// that down so it cannot be "fixed" into caching emptiness by accident.
func TestCachedRecentSongsFreshness(t *testing.T) { func TestCachedRecentSongsFreshness(t *testing.T) {
song := []spotify.RecentlyPlayedItem{{}} song := []spotify.RecentlyPlayedItem{{}}
cases := []struct { cases := []struct {
name string name string
setup func(s *Store) setup func(s *Store)
wantOK bool wantOK bool
}{ }{
{"never fetched", func(*Store) {}, false}, {"never fetched", func(*Store) {}, false},
@@ -215,9 +197,6 @@ func TestCachedSteamFreshness(t *testing.T) {
// --- Upload trust boundary ------------------------------------------------ // --- Upload trust boundary ------------------------------------------------
// requestIsAdmin gates private (admin-only) attachment uploads, so every way
// the claim can be absent or the wrong shape must read as "not admin". No DB
// or network is involved: it only inspects the Gin context.
func TestRequestIsAdmin(t *testing.T) { func TestRequestIsAdmin(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
@@ -231,7 +210,7 @@ func TestRequestIsAdmin(t *testing.T) {
}{ }{
{"no claims in context at all", nil, false}, {"no claims in context at all", nil, false},
{"claims of the wrong type are not trusted", "not-claims", false}, {"claims of the wrong type are not trusted", "not-claims", false},
// A by-value jwt.MapClaims is not what AuthMiddlewear stores; accepting // A by-value jwt.MapClaims is not what AuthMiddleware stores; accepting
// it would mean the type assertion had been loosened. // it would mean the type assertion had been loosened.
{"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false}, {"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false},
{"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false}, {"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false},
@@ -254,9 +233,7 @@ func TestRequestIsAdmin(t *testing.T) {
// --- Permission gate ------------------------------------------------------ // --- Permission gate ------------------------------------------------------
// An unknown key must be refused before any session lookup (Store has no DB // Must 404 before any session lookup (a nil Store would panic).
// or Auth here, so reaching one would panic): it is how a typo in a Caddy
// location shows up as a 404 rather than as a missing grant.
func TestValidatePermissionUnknownKey(t *testing.T) { func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
s := &Store{} s := &Store{}
@@ -272,9 +249,6 @@ func TestValidatePermissionUnknownKey(t *testing.T) {
} }
} }
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
func TestRadioAllowList(t *testing.T) { func TestRadioAllowList(t *testing.T) {
for ext := range allowedAudioExtensions { for ext := range allowedAudioExtensions {
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in // The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
+15 -65
View File
@@ -13,18 +13,8 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Package handlers holds the REST endpoints and the shared Store that every // Store is the dependency container shared by every handler and resolver.
// request handler — and, through graph.Resolver, every GraphQL resolver — // Cache fields are guarded by cacheMu: use the accessors, never the fields.
// depends on.
//
// Store is the backend's dependency container: it is built once in main and
// passed around by pointer, so the caches on it are shared process-wide.
//
// Concurrency note: the third-party caches below are read and written by
// concurrent requests, so every access goes through cacheMu and the accessor
// methods at the bottom of this file. Do not touch the cache fields directly
// — an unsynchronised read of one of them is a data race, not merely a stale
// value.
type Store struct { type Store struct {
DB *gorm.DB DB *gorm.DB
SpotifyAuth *spotifyauth.Authenticator SpotifyAuth *spotifyauth.Authenticator
@@ -33,63 +23,43 @@ type Store struct {
Notes *services.Notes Notes *services.Notes
LoginLimiter *services.RateLimiter LoginLimiter *services.RateLimiter
// Base URL of the Python service on the Docker network, no trailing // The Python service on the Docker network, no trailing slash.
// slash. Used for the calls that bypass Caddy, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string PythonURL string
// Stores uploaded files and says where they are served
// (services.Uploads.Save). Used by the Upload handler.
Uploads *services.Uploads Uploads *services.Uploads
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
// mean "never fetched" distinctly from "fetched, empty".
// cacheMu guards every cache field below (and only those). One mutex for
// all of them keeps the locking obvious; the critical sections are just
// field copies, never network calls, so there is no contention worth
// splitting it up for.
cacheMu sync.RWMutex cacheMu sync.RWMutex
RecentSongs *[]spotify.RecentlyPlayedItem RecentSongs *[]spotify.RecentlyPlayedItem
RecentSongsFetchedAt time.Time RecentSongsFetchedAt time.Time
// Cached latest Gitea activity entry, 1 minute TTL. // 1 minute TTL.
GiteaHost string GiteaHost string
GiteaPort string GiteaPort string
GiteaFeed *services.GiteaFeedResponse GiteaFeed *services.GiteaFeedResponse
GiteaFeedFetchedAt time.Time GiteaFeedFetchedAt time.Time
// Cached Steam status and recent games, 5 minute TTL. // 5 minute TTL.
SteamAPIKey string SteamAPIKey string
SteamID string SteamID string
SteamRecentGames []services.SteamRecentGame SteamRecentGames []services.SteamRecentGame
SteamOnline bool SteamOnline bool
SteamFetchedAt time.Time SteamFetchedAt time.Time
// spotifyStates holds the one-shot CSRF nonces handed out by // One-shot OAuth CSRF nonces. In memory: a lost nonce only restarts a
// GET /spotify/auth, mapped to their creation time. In-memory is enough: // seconds-long flow.
// there is one backend instance, and losing them on restart only means
// restarting an OAuth flow that takes seconds.
spotifyStatesMu sync.Mutex spotifyStatesMu sync.Mutex
spotifyStates map[string]time.Time spotifyStates map[string]time.Time
// spotifyNilLoggedAt rate-limits the "Spotify not authenticated" log line: // Every page visit would otherwise log "Spotify not authenticated".
// every page visit hits spotifyRecent, so an unauthenticated backend would
// otherwise write a flood of identical lines. nil means "recently logged".
spotifyNilLoggedMu sync.Mutex spotifyNilLoggedMu sync.Mutex
spotifyNilLoggedAt time.Time spotifyNilLoggedAt time.Time
} }
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
// enough to log in at Spotify and approve the scopes, short enough that a
// leaked authorisation URL is not reusable later.
const spotifyStateTTL = 10 * time.Minute const spotifyStateTTL = 10 * time.Minute
// NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation // NewSpotifyState mints a nonce. Pruning here is the only cleanup; only an
// URL and remembers it. Expired entries are pruned on the way through, which // admin can add entries.
// is the only cleanup there is — the map is otherwise unbounded, and only an
// admin can add to it.
func (s *Store) NewSpotifyState() (string, error) { func (s *Store) NewSpotifyState() (string, error) {
b := make([]byte, 32) b := make([]byte, 32)
if _, err := rand.Read(b); err != nil { if _, err := rand.Read(b); err != nil {
@@ -112,9 +82,7 @@ func (s *Store) NewSpotifyState() (string, error) {
return state, nil return state, nil
} }
// ConsumeSpotifyState checks a nonce returned by Spotify's redirect and // ConsumeSpotifyState removes the nonce, so a replayed callback fails.
// removes it, so a replayed callback fails. An unknown or expired nonce
// returns false, which the callback must treat as a rejected request.
func (s *Store) ConsumeSpotifyState(state string) bool { func (s *Store) ConsumeSpotifyState(state string) bool {
if state == "" { if state == "" {
return false return false
@@ -131,15 +99,7 @@ func (s *Store) ConsumeSpotifyState(state string) bool {
return time.Since(created) <= spotifyStateTTL return time.Since(created) <= spotifyStateTTL
} }
// The cache accessors below are the only supported way to touch the cache // LogSpotifyUnauthenticated logs at most once an hour.
// fields. Each "Cached..." method returns the value plus a bool that is true
// only when the entry is present and inside its TTL; each "Set..." method
// stores a value and stamps it.
// LogSpotifyUnauthenticated logs that the Spotify OAuth flow has never been
// completed (or a stored token stopped working), with a where hint. It is
// rate-limited to one line per hour — see spotifyNilLoggedAt — because
// spotifyRecent is hit by every home-page visit.
func (s *Store) LogSpotifyUnauthenticated(where string) { func (s *Store) LogSpotifyUnauthenticated(where string) {
s.spotifyNilLoggedMu.Lock() s.spotifyNilLoggedMu.Lock()
defer s.spotifyNilLoggedMu.Unlock() defer s.spotifyNilLoggedMu.Unlock()
@@ -150,9 +110,7 @@ func (s *Store) LogSpotifyUnauthenticated(where string) {
log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where) log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where)
} }
// CachedRecentSongs returns the cached Spotify recently-played list if it is // CachedRecentSongs treats an empty list as stale.
// within its one-minute TTL. An empty list counts as stale, so an empty
// listening history is re-fetched every time (unchanged behaviour).
func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) { func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
s.cacheMu.RLock() s.cacheMu.RLock()
defer s.cacheMu.RUnlock() defer s.cacheMu.RUnlock()
@@ -166,7 +124,6 @@ func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
return *s.RecentSongs, true return *s.RecentSongs, true
} }
// SetRecentSongs replaces the cached recently-played list.
func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) { func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
s.cacheMu.Lock() s.cacheMu.Lock()
defer s.cacheMu.Unlock() defer s.cacheMu.Unlock()
@@ -175,9 +132,6 @@ func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
s.RecentSongsFetchedAt = time.Now() s.RecentSongsFetchedAt = time.Now()
} }
// CachedGiteaFeed returns the cached Gitea activity entry if it is within its
// one-minute TTL. A nil cache is never fresh, so the first request always hits
// Gitea.
func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) { func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
s.cacheMu.RLock() s.cacheMu.RLock()
defer s.cacheMu.RUnlock() defer s.cacheMu.RUnlock()
@@ -188,7 +142,6 @@ func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
return s.GiteaFeed, true return s.GiteaFeed, true
} }
// SetGiteaFeed replaces the cached Gitea feed entry.
func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) { func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.cacheMu.Lock() s.cacheMu.Lock()
defer s.cacheMu.Unlock() defer s.cacheMu.Unlock()
@@ -197,10 +150,8 @@ func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.GiteaFeedFetchedAt = time.Now() s.GiteaFeedFetchedAt = time.Now()
} }
// CachedSteam returns the cached Steam recent games and online flag if they // CachedSteam judges freshness on the games list only, so an empty list is
// are within their five-minute TTL. As before, freshness is judged only on the // always re-fetched.
// games list: if Steam legitimately returns no recent games the cache never
// registers as fresh and every request re-queries the API.
func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) { func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) {
s.cacheMu.RLock() s.cacheMu.RLock()
defer s.cacheMu.RUnlock() defer s.cacheMu.RUnlock()
@@ -211,7 +162,6 @@ func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok
return s.SteamRecentGames, s.SteamOnline, true return s.SteamRecentGames, s.SteamOnline, true
} }
// SetSteam replaces the cached Steam data.
func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) { func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) {
s.cacheMu.Lock() s.cacheMu.Lock()
defer s.cacheMu.Unlock() defer s.cacheMu.Unlock()
+22 -91
View File
@@ -20,18 +20,9 @@ import (
"adam-french.co.uk/backend/services" "adam-french.co.uk/backend/services"
) )
// Command backend is the Go API for adam-french.co.uk. // Command backend is the site's Go API. GraphQL is guarded by schema
// // directives, not middleware; see backend/README.md.
// main is the single place everything is wired together: it reads every
// setting from the environment, builds the services, packs them into one
// handlers.Store, and registers the routes. There are three route groups —
// open, `protected` (valid access token) and `admin` (token with admin=true)
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
// directives in its schema instead of by middleware. See backend/README.md
// for the wider picture.
func main() { func main() {
// Logs go to both stdout (so `docker compose logs` works) and a file in a
// mounted volume (so they survive the container).
logsDir := "/backend/logs" logsDir := "/backend/logs"
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
@@ -44,16 +35,11 @@ func main() {
} }
r := gin.New() r := gin.New()
// Custom traffic formatter (services/traffic_log.go) instead of gin's
// default: quiets heartbeat subrequests, surfaces external visitors and
// server errors. Same writer pair as above.
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter)) r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
r.Use(gin.Recovery()) r.Use(gin.Recovery())
// Only the Docker network Caddy sits on may set X-Forwarded-For. Without // Only the Docker network may set X-Forwarded-For, or clients could spoof
// this pin any client could spoof its IP and defeat the per-IP login rate // their IP past the login rate limiter. Must match docker-compose.yml.
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
err = r.SetTrustedProxies([]string{"172.28.0.0/16"}) err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
if err != nil { if err != nil {
panic(err) panic(err)
@@ -69,38 +55,25 @@ func main() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
// Dev only; the seeder creates an admin with a known password.
if os.Getenv("SEED_DB") == "true" { if os.Getenv("SEED_DB") == "true" {
services.SeedDatabase(db) services.SeedDatabase(db)
} }
// DOMAIN does double duty: the WebSocket origin allow-list and the auth // Used for both the WebSocket origin check and the cookie domain.
// cookie domain.
domainName := os.Getenv("DOMAIN") domainName := os.Getenv("DOMAIN")
// The chat hub is a package-level singleton rather than a value on the
// Store, so it is initialised rather than constructed.
services.InitWebSocket(db, domainName) services.InitWebSocket(db, domainName)
r.Use(services.RequireSameOrigin(domainName))
// SPOTIFY
// No SPOTIFY_AUTH_STATE: the OAuth `state` is now a one-shot nonce minted
// per authorisation request, so there is nothing to configure.
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI") spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID") spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET") spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET")
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret} spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig) spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
// No Claude client here: the site's one Claude call, the rowing photo
// reader, is made by the Python service, which is the only container of
// the site's own that reads CLAUDE_API_KEY. The backend reaches it at
// pythonURL, below. (The job tracker, a separate container, makes its own.)
authSecret := os.Getenv("BACKEND_SECRET") authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT") backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
// Long-lived by design: this is a personal site with a single admin, and
// there is no server-side revocation, so a leaked token stays valid for
// its whole lifetime.
accessTokenLifetime := 7 * 24 * time.Hour accessTokenLifetime := 7 * 24 * time.Hour
refreshTokenLifetime := 365 * 24 * time.Hour // Sliding: every refresh, including the gates', mints a new one.
refreshTokenLifetime := 90 * 24 * time.Hour
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint} authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
auth := services.InitAuth(&authConfig) auth := services.InitAuth(&authConfig)
@@ -114,10 +87,7 @@ func main() {
steamAPIKey := os.Getenv("STEAM_API_KEY") steamAPIKey := os.Getenv("STEAM_API_KEY")
steamID := os.Getenv("STEAM_ID") steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE // Called over the Docker network, not through Caddy.
// Called directly over the Docker network, not through Caddy, for its
// /internal/ Claude route (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
pythonHost := os.Getenv("PYTHON_HOST") pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" { if pythonHost == "" {
pythonHost = "python" pythonHost = "python"
@@ -128,11 +98,7 @@ func main() {
} }
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort) pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// UPLOADS // Defaults match stpcore's garage/garage.toml and garage/bootstrap.sh.
// Public uploads go to the Garage bucket (and to the shared `uploads`
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
// private ones to the volume. See services/uploads.go. Region and bucket
// default to what garage/garage.toml and garage/bootstrap.sh set up.
s3Region := os.Getenv("S3_REGION") s3Region := os.Getenv("S3_REGION")
if s3Region == "" { if s3Region == "" {
s3Region = "garage" s3Region = "garage"
@@ -144,24 +110,18 @@ func main() {
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")} s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
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 // Shared by REST and GraphQL login, on top of Caddy's limit.
// 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}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in // Caddy strips /api before proxying.
// the Gin context, so the order in the admin group matters. protected := r.Group("/", store.AuthMiddleware)
// admin := r.Group("/", store.AuthMiddleware, store.AdminMiddleware)
// Paths below have no /api prefix: Caddy strips it before proxying.
protected := r.Group("/", store.AuthMiddlewear)
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
// ROWING
r.GET("/rowing", store.GetRowing) r.GET("/rowing", store.GetRowing)
admin.POST("/rowing", store.CreateRowing) admin.POST("/rowing", store.CreateRowing)
// AUTH
r.POST("/auth/login", store.Login) r.POST("/auth/login", store.Login)
r.POST("/auth/refresh", store.RefreshToken) r.POST("/auth/refresh", store.RefreshToken)
r.GET("/auth/check", store.CheckToken) r.GET("/auth/check", store.CheckToken)
@@ -169,69 +129,43 @@ func main() {
r.GET("/auth/validate-admin", store.ValidateAdmin) r.GET("/auth/validate-admin", store.ValidateAdmin)
r.GET("/auth/validate/:permission", store.ValidatePermission) r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY // The callback is open (Spotify redirects a logged-out browser) and is
// The callback must be open — Spotify redirects a logged-out browser to // protected by the state nonce that only the admin-only start mints.
// it — and is protected by the state nonce instead. Starting the flow is
// admin-only, since that is what mints the nonce.
r.GET("/spotify/callback", store.CompleteSpotifyAuth) r.GET("/spotify/callback", store.CompleteSpotifyAuth)
admin.GET("/spotify/auth", store.StartSpotifyAuth) admin.GET("/spotify/auth", store.StartSpotifyAuth)
r.GET("/spotify/listening", store.ListeningTo) r.GET("/spotify/listening", store.ListeningTo)
r.GET("/spotify/recent", store.RecentlyPlayed) r.GET("/spotify/recent", store.RecentlyPlayed)
// r.POST("/spotify", store.SendSong)
// RADIO
admin.POST("/radio/upload", store.UploadRadioSong) admin.POST("/radio/upload", store.UploadRadioSong)
admin.GET("/radio/songs", store.ListRadioSongs) admin.GET("/radio/songs", store.ListRadioSongs)
admin.DELETE("/radio/songs/:filename", store.DeleteRadioSong) admin.DELETE("/radio/songs/:filename", store.DeleteRadioSong)
admin.PATCH("/radio/songs/:filename/disable", store.DisableRadioSong) admin.PATCH("/radio/songs/:filename/disable", store.DisableRadioSong)
admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong) admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong)
// MESSAGES // Public: the handler reads the cookies itself for admin privileges.
// /ws is deliberately outside the protected group: chat is public, and
// the handler checks the cookies itself to decide admin privileges.
r.GET("/ws", store.ConnectWebSocket) r.GET("/ws", store.ConnectWebSocket)
protected.POST("/uploads", store.Upload) protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads) admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile) admin.GET("/notes/*path", store.GetNoteFile)
// GRAPHQL // One unguarded POST route: authorisation is the schema's @admin and
// GraphQL is assembled by hand rather than with handler.NewDefaultServer // @signedIn directives, so a field with neither is public. gqlgen fails
// so the transports and extensions below are explicit. // closed if Directives is dropped.
//
// Note the whole API is one POST route with no middleware guard.
// Authorisation is declared in the schema instead: a field marked @admin
// or @signedIn is refused by the matching function in graph.Directives()
// before its resolver runs. A field with neither is PUBLIC, so a new
// mutation needs one — graph/directives_test.go fails until it has one or
// is added to the list of deliberately public fields there.
//
// Directives must stay wired here: gqlgen fails closed on a nil directive
// (the field errors with "directive admin is not implemented"), so
// dropping this line breaks every guarded field rather than opening it.
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{ gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
Resolvers: &graph.Resolver{Store: &store}, Resolvers: &graph.Resolver{Store: &store},
Directives: graph.Directives(), Directives: graph.Directives(),
})) }))
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
gqlSrv.AddTransport(transport.Options{}) gqlSrv.AddTransport(transport.Options{})
gqlSrv.AddTransport(transport.POST{}) gqlSrv.AddTransport(transport.POST{})
gqlSrv.AddTransport(transport.MultipartForm{}) gqlSrv.AddTransport(transport.MultipartForm{})
// Caches parsed query documents so repeated queries skip parsing.
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000)) gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
// Rejects queries above a computed complexity, the standard defence
// against a deeply nested query being used to exhaust the server.
gqlSrv.Use(extension.FixedComplexityLimit(200)) gqlSrv.Use(extension.FixedComplexityLimit(200))
// Introspection and the playground are both off unless DEV_MODE *and* // Production never publishes its schema.
// their own flag are set, so production does not publish its schema.
devMode := os.Getenv("DEV_MODE") == "true" devMode := os.Getenv("DEV_MODE") == "true"
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" { if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
gqlSrv.Use(extension.Introspection{}) gqlSrv.Use(extension.Introspection{})
} }
// AuthContextMiddleware copies the Gin context and any verified claims
// into the request context, which is what resolvers read. The closure is
// needed because gqlgen speaks net/http, not gin.
r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) { r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) {
gqlSrv.ServeHTTP(c.Writer, c.Request) gqlSrv.ServeHTTP(c.Writer, c.Request)
}) })
@@ -241,15 +175,12 @@ func main() {
}) })
} }
// HELLO WORLD
r.GET("/", func(c *gin.Context) { r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Hello World"}) c.JSON(200, gin.H{"message": "Hello World"})
}) })
port := os.Getenv("BACKEND_PORT") port := os.Getenv("BACKEND_PORT")
// Blocks until the server stops. Any return is a failure — a port clash, // Exit non-zero so Docker doesn't report a port clash as success.
// most often — so it must exit non-zero, or Docker sees a clean shutdown
// and reports the container as having succeeded.
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil { if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
log.Fatalf("http server stopped: %v", err) log.Fatalf("http server stopped: %v", err)
} }
+50 -139
View File
@@ -6,64 +6,29 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Package models holds the GORM entities, which are also the GraphQL object // These structs are also the GraphQL object types (gqlgen.yml), so a field or
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so // tag change affects the DB, REST JSON and GraphQL at once.
// graph/model/ only contains generated input and payload types. That means
// these structs carry three sets of contracts at once — database columns,
// JSON field names for the REST endpoints, and the shape resolvers return —
// and renaming a field or changing a tag breaks at least one of them.
//
// Conventions across every model:
// - There are no migration files; services.migrateDatabase runs AutoMigrate,
// so a model must be listed there to get a table.
// - A gorm.DeletedAt field means soft delete: Delete sets deleted_at, and
// every subsequent query silently filters those rows out. Rows are never
// actually removed, and a uniqueIndex still sees deleted rows, so a
// soft-deleted username cannot be reused.
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
// On the wire an id is a quoted decimal string, "12".
// User is an account. There is no public sign-up: users are created by an // User is an account, created only by an admin or the dev seeder.
// existing admin through the createUser mutation, or by the dev seeder.
type User struct { type User struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Username string `gorm:"uniqueIndex" json:"username"` Username string `gorm:"uniqueIndex" json:"username"`
// bcrypt hash, never the plaintext. `json:"-"` keeps it out of REST // bcrypt hash; gqlgen.yml hides it from GraphQL too.
// responses, and gqlgen.yml marks the GraphQL password field
// resolver:false so it is not exposed there either.
Password []byte `json:"-"` Password []byte `json:"-"`
// Admin gates almost every mutation. It is copied into the access token, // Copied into the access token, so changes apply on the next refresh.
// so a change here only takes effect on the user's next token refresh.
Admin bool `json:"admin"` Admin bool `json:"admin"`
// Permissions names the gated services this non-admin user may use, one // Keys from services.PermissionTypes. Read from the row on each request,
// key each from services.PermissionTypes (admins pass every check // not the token, so grants apply immediately.
// regardless). Unlike Admin it is never copied into a token: the gate
// reads it from the row, which services.Auth loads on every request
// anyway, so a grant or revoke takes effect on the user's next request.
// Stored as a JSON array in one text column; a row from before the
// column existed reads as NULL, i.e. no permissions.
Permissions []string `gorm:"serializer:json" json:"permissions"` Permissions []string `gorm:"serializer:json" json:"permissions"`
// TokenVersion is the session generation counter. Every issued JWT // Every JWT carries this; bumping it revokes all of the user's tokens.
// carries the value current at the time it was minted, and // 0 and a missing claim are both treated as 1 (services.tokenVersionOf).
// services.Auth rejects a token whose value no longer matches, so
// incrementing this column revokes every outstanding token for the user
// at once (logout, password change). It is the only server-side
// revocation mechanism there is.
//
// Pre-migration rows: AutoMigrate adds the column with DEFAULT 1, but a
// row that somehow ends up at 0 is normalised to 1 by
// services.tokenVersionOf, as is a token minted before the "tv" claim
// existed. So the migration invalidates nobody's existing session, and
// the first bump moves a user to 2 and invalidates everything older.
TokenVersion uint `gorm:"not null;default:1" json:"-"` TokenVersion uint `gorm:"not null;default:1" json:"-"`
} }
// Post is a blog entry. Author is loaded with Preload("Author") by the post // Post is a blog entry. Author is nil unless preloaded.
// resolvers; without that preload it is nil rather than an error.
type Post struct { type Post struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -75,27 +40,20 @@ type Post struct {
Content string `json:"content"` Content string `json:"content"`
} }
// Message is one chat message. The table is capped at 50 rows by the // Message is a chat message; the WebSocket hub keeps only the latest 50.
// WebSocket hub, which soft-deletes older ones on every insert. // AuthorID is the hub's per-process connection number, not a User ID.
//
// Two things to watch: Content is exposed as "text", not "content"; and
// AuthorID is a per-process connection counter from the WebSocket hub, NOT a
// User ID — chat is pseudonymous and the number is meaningless across
// restarts.
type Message struct { type Message struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
Content string `json:"text"` Content string `json:"text"`
AuthorID uint `json:"authorId"` AuthorID uint `json:"authorId"`
FileURL string `json:"fileUrl,omitempty"` FileURL string `json:"fileUrl,omitempty"`
// Private messages are visible only to admins; both the WebSocket // Visible only to admins.
// broadcast and the messages query filter on it.
Private bool `gorm:"not null;default:false" json:"private"` Private bool `gorm:"not null;default:false" json:"private"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
} }
// Activity is a "currently doing" entry on the home page. Structurally // Activity is a "currently doing" entry on the home page.
// identical to Favorite but kept separate so the two lists can diverge.
type Activity struct { type Activity struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -117,13 +75,9 @@ type Favorite struct {
Link *string `json:"link"` Link *string `json:"link"`
} }
// Rowing is one rowing machine session, created by uploading a photo of the // Rowing is one rowing machine session read from a photo of the display.
// display (see handlers.CreateRowing). // Date is the photo's EXIF time and the dedup key. Time is seconds, Distance
// // metres; Calories is estimated from distance.
// Date is the photo's EXIF capture time and acts as the deduplication key —
// it is not the row's creation time. Time is total seconds; Distance is
// metres; TimePer500m is seconds and derived from the other two; Calories is
// an estimate computed from distance, not read off the machine.
type Rowing struct { type Rowing struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -146,9 +100,7 @@ type Bookmark struct {
Link string `gorm:"not null" json:"link"` Link string `gorm:"not null" json:"link"`
} }
// Place is an entry on the places-to-go list. Creating or editing one needs // Place is a places-to-go entry; any signed-in user may edit it.
// only a signed-in user, not an admin — the one exception to the
// admin-writes-everything rule.
type Place struct { type Place struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -164,20 +116,15 @@ type Place struct {
Done bool `gorm:"default:false" json:"done"` Done bool `gorm:"default:false" json:"done"`
} }
// Box is one panel on a canvas page. Page names the canvas it belongs to: // Box is one panel on a canvas. Page is a page key ("index" or a Page.Slug),
// "index" for the landing page, or a Page.Slug for an admin-created page // not a foreign key. Geometry is px on a fixed 1400px-wide canvas. "html"
// (the home page is the Page "stp") — it is a key, not a foreign key, so the // boxes render in a sandboxed iframe.
// built-in landing canvas needs no Page row. Its position and size are in px on a
// fixed 1400px-wide design canvas, which the page scales down on narrower
// screens — so the stored numbers mean the same thing for every visitor. Kind "widget" renders a built-in Vue component named by Widget;
// kind "html" renders HTML in a sandboxed iframe on the front end, which is
// what makes storing admin-authored script here acceptable.
type Box struct { type Box struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
// default:stp is what the boxes that predate pages are migrated to. // Boxes from before pages existed migrate to "stp".
Page string `gorm:"not null;default:stp;index" json:"page"` Page string `gorm:"not null;default:stp;index" json:"page"`
Kind string `gorm:"not null" json:"kind"` Kind string `gorm:"not null" json:"kind"`
Widget *string `json:"widget"` Widget *string `json:"widget"`
@@ -188,30 +135,20 @@ type Box struct {
W int `gorm:"not null;default:300" json:"w"` W int `gorm:"not null;default:300" json:"w"`
H int `gorm:"not null;default:200" json:"h"` H int `gorm:"not null;default:200" json:"h"`
Z int `gorm:"not null;default:0" json:"z"` Z int `gorm:"not null;default:0" json:"z"`
// No gorm default on Framed: GORM omits zero values for defaulted columns // No gorm default: GORM skips zero values on insert, so default:true would
// on insert, so default:true would turn an explicit false into true. // turn an explicit false into true. CreateBox defaults it.
// CreateBox applies the true default itself.
Framed bool `gorm:"not null" json:"framed"` Framed bool `gorm:"not null" json:"framed"`
// Shadow is a CSS box-shadow value drawn around the box, or "" for none. // A CSS box-shadow, or "".
// It is independent of Framed, so an unframed box can still cast one.
Shadow string `gorm:"not null;default:''" json:"shadow"` Shadow string `gorm:"not null;default:''" json:"shadow"`
HideOnMobile bool `gorm:"not null;default:false" json:"hideOnMobile"` HideOnMobile bool `gorm:"not null;default:false" json:"hideOnMobile"`
// AdminOnly boxes are never sent to anyone but an admin (the boxes AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
// resolver filters them out), so they suit private notes. // The box shows the component's HTML (its own is nil). No association
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"` // field, or DB.Save(&box) would write the component back too.
// ComponentID links an html box to a Component, whose HTML it shows
// instead of its own: the row's HTML is nil, and the resolvers fill it in
// from the component before answering (graph/component_helpers.go). There
// is deliberately no association field — with one, DB.Save(&box) would
// write the component back too.
ComponentID *uint `gorm:"index" json:"componentId"` ComponentID *uint `gorm:"index" json:"componentId"`
} }
// Page is an admin-created canvas page, served by the SPA's catch-all route // Page is an admin-created canvas page at /<Slug>. The unique index is
// at /<Slug> (e.g. "shrines/evangelion"). Its content is the Boxes whose Page // partial so a soft-deleted slug can be reused.
// equals Slug. The unique index is partial so that a deleted page's slug can
// be reused — a plain uniqueIndex would still collide with the soft-deleted
// row.
type Page struct { type Page struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -219,60 +156,40 @@ type Page struct {
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Slug string `gorm:"not null;index:idx_pages_slug,unique,where:deleted_at IS NULL" json:"slug"` Slug string `gorm:"not null;index:idx_pages_slug,unique,where:deleted_at IS NULL" json:"slug"`
Title string `gorm:"not null" json:"title"` Title string `gorm:"not null" json:"title"`
// AdminOnly hides the whole page, boxes included, from everyone else. AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
} }
// Background is the page background behind one canvas (Page is the same page // Background is a canvas page's background; no row means the theme default.
// key a Box has: "index" for the landing page, or a Page's slug), so
// built-in canvases and admin-created pages are set the same way. A page with
// no row shows the theme's halftone; deleting the row is "reset to default".
// The unique index is partial for the same reason as Page's.
type Background struct { type Background struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Page string `gorm:"not null;index:idx_backgrounds_page,unique,where:deleted_at IS NULL" json:"page"` Page string `gorm:"not null;index:idx_backgrounds_page,unique,where:deleted_at IS NULL" json:"page"`
// Color is a CSS colour, or "" for the theme's page colour. // "" means the theme colour.
Color string `gorm:"not null;default:''" json:"color"` Color string `gorm:"not null;default:''" json:"color"`
// Image is a URL, or "" for none. Drawn over Color.
Image string `gorm:"not null;default:''" json:"image"` Image string `gorm:"not null;default:''" json:"image"`
// Fit is how Image fills the window: "cover", "contain" or "tile". // "cover", "contain" or "tile".
Fit string `gorm:"not null;default:cover" json:"fit"` Fit string `gorm:"not null;default:cover" json:"fit"`
} }
// Layout is a named copy of one canvas page's boxes and background, saved so // Layout is a saved snapshot of a page's boxes and background. Loading it
// it can be loaded onto any page later (graph/layout_helpers.go). It is a // creates new boxes, so nothing stays linked. Stored as JSON because it is
// snapshot, not a link: loading it creates new boxes that belong to the // only ever read and written whole.
// target page, so editing either page afterwards never touches the other or
// the layout. The content is JSON rather than child rows because nothing
// queries inside it — it is only ever written whole and read whole. The
// unique index is partial for the same reason as Page's.
type Layout struct { type Layout struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"` Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
// SourcePage is the page key it was saved from, for the list only. SourcePage string `gorm:"not null" json:"sourcePage"`
SourcePage string `gorm:"not null" json:"sourcePage"` // JSON array of box content and geometry, without id or page.
// Boxes is a JSON array of the boxes' content and geometry, without id Boxes string `gorm:"type:text;not null" json:"-"`
// or page.
Boxes string `gorm:"type:text;not null" json:"-"`
// Background is the page's background as JSON, or nil if it had none.
Background *string `gorm:"type:text" json:"-"` Background *string `gorm:"type:text" json:"-"`
} }
// Component is a named HTML box that can be placed on any canvas page, either // Component is a named HTML box. Linked boxes share only its HTML; the other
// as a copy (an ordinary box) or linked (a box with ComponentID set). Linked // fields are the defaults for a newly placed box.
// boxes share only the HTML — editing it changes every one of them at once —
// while title, geometry, frame and visibility stay each box's own, since
// those are about where it sits on a page rather than what it is. Title, W,
// H, Framed, Shadow and AdminOnly are the defaults a newly placed box starts
// with.
// Widgets are not components: a widget box is just a name, with nothing
// worth sharing. The unique index is partial for the same reason as Page's.
type Component struct { type Component struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -283,17 +200,13 @@ type Component struct {
HTML string `gorm:"type:text;not null" json:"html"` HTML string `gorm:"type:text;not null" json:"html"`
W int `gorm:"not null" json:"w"` W int `gorm:"not null" json:"w"`
H int `gorm:"not null" json:"h"` H int `gorm:"not null" json:"h"`
// No gorm default on Framed, for the same reason as Box.Framed. // No gorm default, as for Box.Framed.
Framed bool `gorm:"not null" json:"framed"` Framed bool `gorm:"not null" json:"framed"`
Shadow string `gorm:"not null;default:''" json:"shadow"` Shadow string `gorm:"not null;default:''" json:"shadow"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"` AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
} }
// CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the // CoverLetter is a saved letter; Body is JSON in views/CV/coverLetter.js's shape.
// whole letter as JSON (contact block, sections, paragraphs; the shape is
// views/CV/coverLetter.js's) because only the frontend ever reads inside it —
// the same reasoning as Layout.Boxes. The unique index is partial for the
// same reason as Page's.
type CoverLetter struct { type CoverLetter struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
@@ -303,9 +216,7 @@ type CoverLetter struct {
Body string `gorm:"type:text;not null" json:"body"` Body string `gorm:"type:text;not null" json:"body"`
} }
// CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into // CoverSnippet is a reusable cover-letter paragraph; Section only groups the bank.
// a letter as a copy. Section is the title of the section it was written for,
// only used to group the bank; a snippet can be dropped into any section.
type CoverSnippet struct { type CoverSnippet struct {
ID uint `gorm:"primarykey" json:"id"` ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
+40 -122
View File
@@ -11,20 +11,13 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Auth mints and verifies the HS256 JWTs that back the site's login. Tokens // Auth mints and verifies HS256 JWTs. Revocation is by User.TokenVersion:
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login). // every token carries it as "tv", and bumping it kills them all.
//
// There is no token blacklist, but there is coarse server-side revocation:
// every token carries the user's models.User.TokenVersion in a "tv" claim,
// and AuthenticateToken rejects a token whose version has moved on. Bumping
// that column (BumpTokenVersion) therefore kills all of a user's outstanding
// tokens at once — which is what logout and a password change do.
type Auth struct { type Auth struct {
Config *AuthConfig Config *AuthConfig
} }
// AuthConfig carries the signing secret and cookie/token lifetimes. Domain is // Domain is the cookie domain; Endpoint is the backend's public base URL.
// the cookie domain; Endpoint is the backend's public base URL.
type AuthConfig struct { type AuthConfig struct {
Secret []byte Secret []byte
Domain string Domain string
@@ -33,16 +26,13 @@ type AuthConfig struct {
Endpoint string Endpoint string
} }
// Tokens is a freshly minted access/refresh token pair, both already signed.
type Tokens struct { type Tokens struct {
AccessToken string AccessToken string
RefreshToken string RefreshToken string
} }
// InitAuth builds the Auth service from config. An absent or too-short // InitAuth panics on a short secret: HS256 accepts a zero-length key, which
// secret is fatal: HS256 happily signs and verifies with a zero-length key, // would make admin tokens forgeable.
// so starting up with an empty BACKEND_SECRET would let anyone forge admin
// tokens. Fail loudly at boot rather than serving a forgeable auth system.
func InitAuth(config *AuthConfig) *Auth { func InitAuth(config *AuthConfig) *Auth {
if len(config.Secret) < 32 { if len(config.Secret) < 32 {
panic("auth secret must be set and at least 32 bytes (check BACKEND_SECRET)") panic("auth secret must be set and at least 32 bytes (check BACKEND_SECRET)")
@@ -51,18 +41,8 @@ func InitAuth(config *AuthConfig) *Auth {
return &Auth{Config: config} return &Auth{Config: config}
} }
// GenerateJWT issues an access/refresh pair for user. // GenerateJWT issues an access/refresh pair. The admin claim is informational:
// // AuthenticateTokenWithClaims overwrites it from the user row.
// The access token carries the authorisation data the API needs (id, admin)
// so that most requests can be authorised without touching the database. The
// refresh token deliberately carries only the id (plus the version): admin
// status is re-read from the database when refreshing, so revoking someone's
// admin flag takes effect on their next refresh rather than only when they
// log in again.
//
// Both tokens carry "tv", the user's TokenVersion at minting time. Anything
// that validates a token against the database checks it, so the pair dies the
// moment the column is bumped.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) { func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username, "username": user.Username,
@@ -91,20 +71,13 @@ func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil
} }
// keyFunc supplies the HMAC secret to the JWT parser. The token argument is // The key is fixed; VerifyJWT pins the algorithm, which is what stops
// ignored because only one key is ever in use; VerifyJWT separately pins the // algorithm-confusion attacks.
// algorithm, which is what actually prevents the "alg: none"/algorithm
// confusion attack.
func (auth *Auth) keyFunc(_ *jwt.Token) (any, error) { func (auth *Auth) keyFunc(_ *jwt.Token) (any, error) {
return auth.Config.Secret, nil return auth.Config.Secret, nil
} }
// VerifyJWT parses and validates a signed token, returning its claims. // VerifyJWT returns the claims. Numbers decode as float64.
// Expiry is checked by the jwt library. Note the *jwt.MapClaims return: a
// pointer to a map is unusual, but every caller in this codebase expects it,
// so the type is part of the internal contract. Numeric claims come back as
// float64 because that is what encoding/json produces, hence the
// `(*claims)["id"].(float64)` conversions at the call sites.
func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) { func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()})) token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil { if err != nil {
@@ -119,31 +92,16 @@ func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
return &claims, nil return &claims, nil
} }
// Typed errors returned by AuthenticateToken so each call site can keep its // Distinct so REST and GraphQL can each map them to their own status codes.
// own response for each case — the REST and GraphQL entry points deliberately
// answer differently (401 vs 500 vs 404-plus-cookie-clear).
var ( var (
// ErrInvalidToken means the token is missing, malformed, expired or not ErrInvalidToken = errors.New("invalid token")
// correctly signed.
ErrInvalidToken = errors.New("invalid token")
// ErrInvalidClaims means the token verified but its "id" claim is absent
// or not a number — a server-side inconsistency, not a client error.
ErrInvalidClaims = errors.New("invalid token claims") ErrInvalidClaims = errors.New("invalid token claims")
// ErrUserNotFound means the token named a user that no longer exists (or ErrUserNotFound = errors.New("user not found")
// has been soft deleted). ErrTokenRevoked = errors.New("token revoked")
ErrUserNotFound = errors.New("user not found")
// ErrTokenRevoked means the token is otherwise valid but was minted
// before the user's TokenVersion was bumped, i.e. logout or a password
// change has invalidated it.
ErrTokenRevoked = errors.New("token revoked")
) )
// tokenVersionOf normalises a stored or claimed token version. // tokenVersionOf treats 0 (old rows, tokens without "tv") as 1, the column
// // default, so introducing versioning logged nobody out.
// Zero means "unset": either a row that predates the token_version column, or
// a token minted before the "tv" claim existed. Both are normalised to 1, the
// column's default, so introducing versioning logs nobody out. The first
// BumpTokenVersion moves a user to 2 and invalidates every older token.
func tokenVersionOf(v uint) uint { func tokenVersionOf(v uint) uint {
if v == 0 { if v == 0 {
return 1 return 1
@@ -151,66 +109,46 @@ func tokenVersionOf(v uint) uint {
return v return v
} }
// AuthenticateToken is the one place a token string is turned into a user: it // AuthenticateToken turns a token into a user, checking signature, expiry,
// verifies the signature and expiry, reads the id claim, loads the row, and // the user row and the token version. Errors are always the sentinels above.
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
// call sites can map each case onto whatever status code they already used.
func (auth *Auth) AuthenticateToken(db *gorm.DB, tokenStr string) (*models.User, error) { func (auth *Auth) AuthenticateToken(db *gorm.DB, tokenStr string) (*models.User, error) {
user, _, err := auth.AuthenticateTokenWithClaims(db, tokenStr) user, _, err := auth.AuthenticateTokenWithClaims(db, tokenStr)
return user, err return user, err
} }
// AuthenticateTokenWithClaims is AuthenticateToken plus the raw claims, for // AuthenticateTokenWithClaims also returns the claims, for "admin". It costs
// the middlewares that go on to read claims the User struct does not carry // one SELECT per request, which is the price of revocation.
// (notably "admin", which is authoritative from the token rather than the
// row — see handlers.AdminMiddleware).
//
// Note this costs one primary-key SELECT per authenticated request. That is
// the price of revocation: without loading the row there is no version to
// compare against, and logout could not kill a live access token.
func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*models.User, *jwt.MapClaims, error) { func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*models.User, *jwt.MapClaims, error) {
claims, err := auth.VerifyJWT(tokenStr) claims, err := auth.VerifyJWT(tokenStr)
if err != nil { if err != nil {
return nil, nil, ErrInvalidToken return nil, nil, ErrInvalidToken
} }
// Claims are decoded by encoding/json, so every number arrives as a
// float64 regardless of the Go type it was signed from.
userIDF, ok := (*claims)["id"].(float64) userIDF, ok := (*claims)["id"].(float64)
if !ok { if !ok {
return nil, nil, ErrInvalidClaims return nil, nil, ErrInvalidClaims
} }
// Pre-setting the primary key and calling First with no explicit // Soft-deleted users are excluded, so a deleted account fails here.
// condition makes GORM look the row up by that key. Soft-deleted users
// are excluded automatically, so a deleted account fails here.
user := models.User{ID: uint(userIDF)} user := models.User{ID: uint(userIDF)}
if err := db.First(&user).Error; err != nil { if err := db.First(&user).Error; err != nil {
return nil, nil, ErrUserNotFound return nil, nil, ErrUserNotFound
} }
// A token with no "tv" claim reads as 0 and is normalised to 1, matching
// an un-bumped user — see tokenVersionOf.
claimedVersion, _ := (*claims)["tv"].(float64) claimedVersion, _ := (*claims)["tv"].(float64)
if tokenVersionOf(uint(claimedVersion)) != tokenVersionOf(user.TokenVersion) { if tokenVersionOf(uint(claimedVersion)) != tokenVersionOf(user.TokenVersion) {
return nil, nil, ErrTokenRevoked return nil, nil, ErrTokenRevoked
} }
// The row is already loaded, so it decides admin: a demotion applies on
// the next request rather than when the token expires.
(*claims)["admin"] = user.Admin
return &user, claims, nil return &user, claims, nil
} }
// BumpTokenVersion invalidates every token previously issued to userID by // BumpTokenVersion revokes all of userID's tokens. COALESCE treats a NULL
// incrementing the user's version counter. Callers treat a failure as // version as 1.
// non-fatal (logout still clears the cookies), but it must be logged: a
// silent failure here means a logout that did not actually revoke anything.
//
// COALESCE covers a pre-migration row sitting at 0 or NULL: it is treated as
// 1, so the bump lands on 2 and invalidates tokens claiming either.
func BumpTokenVersion(db *gorm.DB, userID uint) error { func BumpTokenVersion(db *gorm.DB, userID uint) error {
return db.Model(&models.User{}). return db.Model(&models.User{}).
Where("id = ?", userID). Where("id = ?", userID).
@@ -218,43 +156,23 @@ func BumpTokenVersion(db *gorm.DB, userID uint) error {
Error Error
} }
// SetAuthCookies writes the access/refresh cookie pair. const (
// secure = true
// It lives in services because both handlers and graph need it and handlers httpOnly = true
// cannot import graph (that would be an import cycle); keeping one copy is )
// what stops REST login and GraphQL login drifting apart.
// // SetAuthCookies lives in services so REST and GraphQL share one copy.
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both // SameSite=Lax survives the redirect back from an OAuth provider.
// true here: the cookies never travel over plain HTTP and are invisible to
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
// provider while still blocking cross-site POSTs. Each cookie's max-age
// mirrors the lifetime baked into the token itself, so the browser drops it at
// roughly the moment it stops being accepted.
func SetAuthCookies(gc *gin.Context, config *AuthConfig, tokens *Tokens) { func SetAuthCookies(gc *gin.Context, config *AuthConfig, tokens *Tokens) {
gc.SetSameSite(http.SameSiteLaxMode) gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie( gc.SetCookie("access_token", tokens.AccessToken, int(config.AccessTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly)
"access_token", gc.SetCookie("refresh_token", tokens.RefreshToken, int(config.RefreshTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly)
tokens.AccessToken,
int(config.AccessTokenLifetime.Seconds()),
"/",
config.Domain,
true, true,
)
gc.SetCookie(
"refresh_token",
tokens.RefreshToken,
int(config.RefreshTokenLifetime.Seconds()),
"/",
config.Domain,
true, true,
)
} }
// ClearAuthCookies expires both auth cookies. The max-age of -1 is what tells // ClearAuthCookies must match SetAuthCookies' attributes, or the browser
// the browser to delete them; path, domain and the Secure/HttpOnly flags must // keeps the originals.
// match those used when setting them or the browser keeps the originals.
func ClearAuthCookies(gc *gin.Context, config *AuthConfig) { func ClearAuthCookies(gc *gin.Context, config *AuthConfig) {
gc.SetSameSite(http.SameSiteLaxMode) gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie("access_token", "", -1, "/", config.Domain, true, true) gc.SetCookie("access_token", "", -1, "/", config.Domain, secure, httpOnly)
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, true, true) gc.SetCookie("refresh_token", "", -1, "/", config.Domain, secure, httpOnly)
} }
+4 -20
View File
@@ -10,20 +10,8 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Companion to auth_test.go, covering the two pure things it leaves out: the // Token expiry and cookie attributes. Cookies are checked through a real gin
// expiry the minting code bakes into each token, and the cookie attributes // context, since gin builds the header.
// SetAuthCookies/ClearAuthCookies emit.
//
// DELIBERATELY NOT COVERED HERE:
// - AuthenticateToken past the id claim, and BumpTokenVersion: both need a
// live *gorm.DB and the only driver in go.mod is postgres.
// - Everything auth_test.go already covers (tokenVersionOf, the claim split,
// the VerifyJWT rejection table) — not duplicated.
// - Password hashing: there is none in this package; handlers own it.
//
// Cookie assertions go through a real gin context because gin, not this
// package, is what turns the SetCookie arguments into a header — asserting on
// the arguments alone would test nothing.
// cookiesFrom runs fn against a throwaway gin context and returns what it set, // cookiesFrom runs fn against a throwaway gin context and returns what it set,
// keyed by cookie name. // keyed by cookie name.
@@ -40,9 +28,7 @@ func cookiesFrom(fn func(*gin.Context)) map[string]*http.Cookie {
return out return out
} }
// exp must track the configured lifetime, because the cookie max-age is derived // Cookie max-age is derived from the same lifetime.
// from the same number: if they disagreed the browser would hold a dead cookie
// or drop a live one.
func TestGenerateJWTExpiryMatchesConfiguredLifetime(t *testing.T) { func TestGenerateJWTExpiryMatchesConfiguredLifetime(t *testing.T) {
auth := testAuth() auth := testAuth()
issued := time.Now() issued := time.Now()
@@ -124,9 +110,7 @@ func TestSetAuthCookies(t *testing.T) {
} }
} }
// A browser only replaces a cookie when path, domain and flags match the // A deletion that differs in path, domain or flags silently fails.
// original, so a deletion that differs in any of them silently leaves the user
// logged in. Hence asserting the attributes, not just the negative max-age.
func TestClearAuthCookiesMatchesTheCookiesItDeletes(t *testing.T) { func TestClearAuthCookiesMatchesTheCookiesItDeletes(t *testing.T) {
config := testAuth().Config config := testAuth().Config
set := cookiesFrom(func(gc *gin.Context) { set := cookiesFrom(func(gc *gin.Context) {
+3 -15
View File
@@ -9,12 +9,8 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
// The tests below deliberately stop short of AuthenticateToken's happy path: // Stops short of the row lookup (no DB in CI); revocation is covered via
// that branch needs a live *gorm.DB and the only driver in go.mod is postgres, // tokenVersionOf.
// so exercising it would mean a database in CI. Everything that runs before the
// row lookup (parsing, signature, claim extraction) is covered here, and the
// revocation rule itself is covered through tokenVersionOf, which is the whole
// of the comparison AuthenticateTokenWithClaims performs.
func testAuth() *Auth { func testAuth() *Auth {
return InitAuth(&AuthConfig{ return InitAuth(&AuthConfig{
@@ -47,9 +43,6 @@ func TestTokenVersionOf(t *testing.T) {
} }
} }
// The comparison AuthenticateTokenWithClaims makes is tokenVersionOf(claim) vs
// tokenVersionOf(row). The table therefore encodes the revocation contract: an
// absent claim (0) must still match an un-bumped user, and any bump must not.
func TestTokenVersionMatch(t *testing.T) { func TestTokenVersionMatch(t *testing.T) {
cases := []struct { cases := []struct {
name string name string
@@ -104,9 +97,6 @@ func TestGenerateJWTTokenVersionClaim(t *testing.T) {
} }
} }
// The split of claims is load-bearing: admin lives in the access token so most
// requests need no row, and is absent from the refresh token so that revoking
// admin takes effect on the next refresh.
func TestGenerateJWTClaimSplit(t *testing.T) { func TestGenerateJWTClaimSplit(t *testing.T) {
auth := testAuth() auth := testAuth()
tokens, err := auth.GenerateJWT(&models.User{ID: 7, Username: "adam", Admin: true, TokenVersion: 1}) tokens, err := auth.GenerateJWT(&models.User{ID: 7, Username: "adam", Admin: true, TokenVersion: 1})
@@ -191,9 +181,7 @@ func TestVerifyJWTRejections(t *testing.T) {
} }
} }
// A verified token with no usable id is a server-side inconsistency, not a // Both return before the row lookup, so a nil DB is safe.
// client error, so it gets its own sentinel. Both cases below return before the
// row lookup, which is why a nil *gorm.DB is safe here.
func TestAuthenticateTokenInvalidClaims(t *testing.T) { func TestAuthenticateTokenInvalidClaims(t *testing.T) {
auth := testAuth() auth := testAuth()
cases := []struct { cases := []struct {
+4 -14
View File
@@ -18,9 +18,7 @@ type SQLConfig struct {
Port string Port string
} }
// connectToPostgreSQL opens the GORM connection. sslmode=disable is safe // sslmode=disable: Postgres is only on the Docker network.
// only because Postgres is reachable exclusively on the private Docker
// network, never over the internet.
func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) { func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
dsn := fmt.Sprintf( dsn := fmt.Sprintf(
"user=%s password=%s dbname=%s host=%s port=%s sslmode=disable", "user=%s password=%s dbname=%s host=%s port=%s sslmode=disable",
@@ -35,12 +33,8 @@ func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
return db, nil return db, nil
} }
// migrateDatabase brings the schema up to date. This project has no // AutoMigrate never drops or renames, so removed fields leave columns and
// migration files: GORM's AutoMigrate is the only schema source, so it will // renamed ones start empty. New models must be listed here.
// add tables, columns and indexes but never drop or rename anything. Removing
// a field from a model therefore leaves the column behind, and a renamed
// field appears as a brand-new column with no data. Any model added to
// models.go must also be listed here or its table will never be created.
func migrateDatabase(db *gorm.DB) error { func migrateDatabase(db *gorm.DB) error {
err := db.AutoMigrate( err := db.AutoMigrate(
&models.User{}, &models.User{},
@@ -66,11 +60,7 @@ func migrateDatabase(db *gorm.DB) error {
return ensureStpPage(db) return ensureStpPage(db)
} }
// ensureStpPage turns the home page (/stp) into an ordinary canvas Page once. // ensureStpPage creates the /stp Page row once. Unscoped, so deleting it sticks.
// It used to be a built-in canvas with its own route; its boxes and
// background were already keyed "stp", so a Page row with that slug is all
// it takes. Unscoped, so that deleting the page on purpose sticks rather than
// bringing it back on the next start.
func ensureStpPage(db *gorm.DB) error { func ensureStpPage(db *gorm.DB) error {
var count int64 var count int64
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil { if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
+7 -23
View File
@@ -8,35 +8,27 @@ import (
"time" "time"
) )
// This file talks to the self-hosted Gitea instance over the private Docker // The latest Gitea push, for the home page.
// network to surface "what did Adam push most recently" on the home page.
// The response is cached by the caller (handlers.Store, 1 minute TTL).
// GiteaFeedCommit is one commit inside a push event's Content payload. // Gitea's own capitalised keys.
// The capitalised JSON keys are Gitea's, not a typo.
type GiteaFeedCommit struct { type GiteaFeedCommit struct {
Message string `json:"Message"` Message string `json:"Message"`
} }
// GiteaFeedContent is the shape of the JSON *string* stored in // Push events' Content is this, as a JSON string; see ParseCommitMessage.
// GiteaFeedResponse.Content for push events; see ParseCommitMessage.
type GiteaFeedContent struct { type GiteaFeedContent struct {
Commits []GiteaFeedCommit `json:"Commits"` Commits []GiteaFeedCommit `json:"Commits"`
} }
// GiteaFeedUser is the acting user on a feed entry.
type GiteaFeedUser struct { type GiteaFeedUser struct {
AvatarURL string `json:"avatar_url"` AvatarURL string `json:"avatar_url"`
} }
// GiteaFeedRepo is the repository a feed entry belongs to.
type GiteaFeedRepo struct { type GiteaFeedRepo struct {
FullName string `json:"full_name"` FullName string `json:"full_name"`
HTMLURL string `json:"html_url"` HTMLURL string `json:"html_url"`
} }
// GiteaFeedResponse is a single Gitea activity feed entry. Only the fields
// the front end renders are declared; the rest of the payload is discarded.
type GiteaFeedResponse struct { type GiteaFeedResponse struct {
ActUser GiteaFeedUser `json:"act_user"` ActUser GiteaFeedUser `json:"act_user"`
Repo GiteaFeedRepo `json:"repo"` Repo GiteaFeedRepo `json:"repo"`
@@ -45,13 +37,8 @@ type GiteaFeedResponse struct {
Created time.Time `json:"created"` Created time.Time `json:"created"`
} }
// FetchLatestFeed returns the single most recent public activity entry for // FetchLatestFeed returns (nil, nil) for an empty feed. Unauthenticated: the
// user "adamf", or (nil, nil) when the feed is empty — callers must handle // public feed needs no token.
// that nil-without-error case.
//
// The username is hard-coded and the call is plain HTTP with no token: this
// only ever reaches the Gitea container over the internal Docker network,
// where the public feed needs no authentication.
func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) { func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
url := fmt.Sprintf("http://%s:%s/api/v1/users/adamf/activities/feeds?limit=1", host, port) url := fmt.Sprintf("http://%s:%s/api/v1/users/adamf/activities/feeds?limit=1", host, port)
@@ -79,11 +66,8 @@ func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
return &items[0], nil return &items[0], nil
} }
// ParseCommitMessage pulls the first commit message out of a feed entry's // ParseCommitMessage decodes JSON-in-a-string. Non-push events don't parse,
// Content field, which Gitea delivers as JSON encoded inside a JSON string // which yields "".
// (so it needs a second Unmarshal). Non-push events have Content in a
// different shape entirely, so any parse failure is intentionally swallowed
// and reported as "no commit message".
func ParseCommitMessage(content string) string { func ParseCommitMessage(content string) string {
var c GiteaFeedContent var c GiteaFeedContent
if err := json.Unmarshal([]byte(content), &c); err != nil { if err := json.Unmarshal([]byte(content), &c); err != nil {
+2 -7
View File
@@ -26,13 +26,8 @@ func InitNotes(config *NotesConfig) *Notes {
} }
} }
// ParsePath resolves a user-supplied request path to an absolute path inside // ParsePath appends the separator before the prefix check, so a sibling such
// the notes directory, or returns an error if it would escape. // as /backend/notes-private can't pass.
//
// The traversal guard is the prefix check at the end. filepath.Join already
// cleans "..", but the separator is appended to baseDir before comparing so
// that a sibling directory whose name merely starts with the same characters
// (e.g. /backend/notes-private next to /backend/notes) cannot pass the check.
func (notes *Notes) ParsePath(path string) (string, error) { func (notes *Notes) ParsePath(path string) (string, error) {
// The route is /notes/*path, so a bare /notes/ arrives as "" or "/"; // The route is /notes/*path, so a bare /notes/ arrives as "" or "/";
// treat both as a request for the wiki index. // treat both as a request for the wiki index.
+44
View File
@@ -0,0 +1,44 @@
package services
import (
"net/http"
"net/url"
"github.com/gin-gonic/gin"
)
// IsSiteOrigin reports whether an Origin header names the site itself (the
// apex or www). In dev DOMAIN is localhost, which covers Vite on any port.
func IsSiteOrigin(origin, domain string) bool {
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return domain != "" && (host == domain || host == "www."+domain)
}
// RequireSameOrigin refuses state-changing requests a browser sent from
// elsewhere. SameSite=Lax does not cover this: radar. and git. are the same
// site, so their pages get the auth cookies. A request with neither header is
// not from a browser and passes.
func RequireSameOrigin(domain string) gin.HandlerFunc {
return func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
c.Next()
return
}
allowed := true
if origin := c.GetHeader("Origin"); origin != "" {
allowed = IsSiteOrigin(origin, domain)
} else if site := c.GetHeader("Sec-Fetch-Site"); site != "" {
allowed = site == "same-origin" || site == "none"
}
if !allowed {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin request refused"})
return
}
c.Next()
}
}
+67
View File
@@ -0,0 +1,67 @@
package services
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestIsSiteOrigin(t *testing.T) {
cases := []struct {
origin, domain string
want bool
}{
{"https://www.example.com", "example.com", true},
{"https://example.com", "example.com", true},
{"https://radar.example.com", "example.com", false},
{"https://git.example.com", "example.com", false},
{"https://www.example.com.evil.test", "example.com", false},
{"https://evilexample.com", "example.com", false},
{"null", "example.com", false},
{"http://localhost:5173", "localhost", true},
{"http://localhost:5173", "example.com", false},
{"https://anything", "", false},
}
for _, c := range cases {
if got := IsSiteOrigin(c.origin, c.domain); got != c.want {
t.Errorf("IsSiteOrigin(%q, %q) = %v, want %v", c.origin, c.domain, got, c.want)
}
}
}
func TestRequireSameOrigin(t *testing.T) {
gin.SetMode(gin.TestMode)
cases := []struct {
name string
method string
headers map[string]string
want int
}{
{"GET is never checked", "GET", map[string]string{"Origin": "https://evil.test"}, 200},
{"POST from www", "POST", map[string]string{"Origin": "https://www.example.com"}, 200},
{"POST from a sibling subdomain", "POST", map[string]string{"Origin": "https://radar.example.com"}, 403},
{"POST from another site", "POST", map[string]string{"Origin": "https://evil.test"}, 403},
{"POST with an opaque origin", "POST", map[string]string{"Origin": "null"}, 403},
{"DELETE from another site", "DELETE", map[string]string{"Origin": "https://evil.test"}, 403},
{"no Origin, same-site fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-site"}, 403},
{"no Origin, same-origin fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-origin"}, 200},
{"no browser headers (curl, server to server)", "POST", nil, 200},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := gin.New()
r.Use(RequireSameOrigin("example.com"))
r.Handle(c.method, "/x", func(ctx *gin.Context) { ctx.Status(200) })
req := httptest.NewRequest(c.method, "/x", nil)
for k, v := range c.headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != c.want {
t.Fatalf("status %d, want %d", rec.Code, c.want)
}
})
}
}
+5 -21
View File
@@ -6,44 +6,28 @@ import (
"adam-french.co.uk/backend/models" "adam-french.co.uk/backend/models"
) )
// Per-service permissions: how a non-admin account is let into one gated // Grantable per-service permissions for non-admins; admins pass every check.
// service (the receipt printer, say) without being made an admin. // To add one: an entry below, then `import permission_gate <key>` on its
// // route in caddy/routes.caddy.
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// Caddy gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping its route in
// caddy/routes.caddy from `import admin_gate` to `import permission_gate
// <key>` (the snippet is in caddy/Caddyfile).
// PermissionType describes one grantable service. Key is what is stored and
// what Caddy names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct { type PermissionType struct {
Key string Key string
Label string Label string
Path string Path string
} }
// PermissionTypes is the full set of grantable permissions, in display order. // Removed keys are inert: the validate endpoint 404s them.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
var PermissionTypes = []PermissionType{ var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"}, {Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
} }
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool { func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool { return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key return p.Key == key
}) })
} }
// HasPermission reports whether user may use the service gated on key. It // HasPermission reads the row, not the token.
// reads the row, not a token, so Admin here is the current database value.
func HasPermission(user *models.User, key string) bool { func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key) return user.Admin || slices.Contains(user.Permissions, key)
} }
+11 -40
View File
@@ -10,49 +10,25 @@ import (
"time" "time"
) )
// Every Claude call the site makes lives in the Python service, behind an // CallPython is how the backend reaches the Python service's /internal/
// /internal/ route. This file is the one way the Go backend reaches those // routes, container to container (Caddy refuses them, and they refuse
// routes. The only caller now is the rowing photo reader // proxied requests).
// (handlers/handle_rowing.go); the job posting reader, email classifier and
// lead scorer went with the job tracker to its own repo.
//
// The routes are internal in a specific sense: Caddy answers 404 for
// /py/internal/, and each route itself refuses a request carrying a proxy
// header, so the only way in is this direct container-to-container call. That
// is why the request below sets nothing but Content-Type.
// pythonClient bounds the wait on the Python service. Two minutes sits above // Above Python's own worst case (30s Claude timeout, two retries), so a slow
// that side's own worst case (a 30s Claude timeout, retried twice with // Claude surfaces as Python's error.
// backoff), so a slow Claude surfaces as Python's error rather than as a
// timeout here. One client for every route, so they share a connection pool.
var pythonClient = &http.Client{Timeout: 2 * time.Minute} var pythonClient = &http.Client{Timeout: 2 * time.Minute}
// PythonError is a failure the Python service reported in words that are safe // PythonError is the `detail` of a 502: one of the route's fixed messages,
// and useful to show a person: the string `detail` of a 502, which is always // safe to show a user. Every other failure is a plain error, for the log only.
// one of that route's own fixed messages ("failed to parse image data", ...).
//
// Everything else — a refused connection, a 422, a 503 for a missing API key,
// a reply that will not decode — comes back as an ordinary error instead. The
// distinction is the point: a caller relays a PythonError and only logs the
// rest, because the rest describe plumbing the user can do nothing about and
// may quote internals.
type PythonError struct{ Detail string } type PythonError struct{ Detail string }
func (e *PythonError) Error() string { return e.Detail } func (e *PythonError) Error() string { return e.Detail }
// CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into // CallPython POSTs body as JSON and decodes a 200 into T; anything else is an
// T. baseURL is the service's address on the Docker network with no trailing // error. baseURL has no trailing slash.
// slash (handlers.Store.PythonURL); path is the route, starting with a slash.
//
// Any non-200 is an error. See PythonError for which ones are relayable. A
// cancelled ctx is wrapped, not replaced, so errors.Is(err, context.Canceled)
// still holds.
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) { func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
var out T var out T
// Note for callers sending bytes: encoding/json writes a []byte as
// standard base64, which is the form the Anthropic API wants and so what
// the Python side passes straight through.
payload, err := json.Marshal(body) payload, err := json.Marshal(body)
if err != nil { if err != nil {
return out, fmt.Errorf("encoding request for %s: %w", path, err) return out, fmt.Errorf("encoding request for %s: %w", path, err)
@@ -71,12 +47,8 @@ func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T,
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the // Only a 502's detail is user-facing: a 422's is a list (fails to
// route's own fixed messages; a 422's detail is a list, which fails // decode) and a 503's names an env var.
// to decode into the string and falls through to the generic error,
// and a 503's detail names an environment variable, which is for the
// log rather than the page. The body is capped because it is only
// ever quoted in a log line.
var failure struct { var failure struct {
Detail string `json:"detail"` Detail string `json:"detail"`
} }
@@ -88,7 +60,6 @@ func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T,
} }
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
// A fresh zero value, so a half-decoded T never escapes with an error.
var zero T var zero T
return zero, fmt.Errorf("decoding %s response: %w", path, err) return zero, fmt.Errorf("decoding %s response: %w", path, err)
} }
+25 -27
View File
@@ -1,7 +1,5 @@
// Package services holds the backend's stateful collaborators: the database // Package services holds the backend's stateful collaborators, reached
// handle, JWT signing, the chat WebSocket hub, third-party API clients // through handlers.Store.
// (Spotify, Steam, Gitea, Claude) and the email-sync pipeline. Handlers and
// GraphQL resolvers reach them through handlers.Store.
package services package services
import ( import (
@@ -9,24 +7,15 @@ import (
"time" "time"
) )
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary // RateLimiter is an in-memory sliding window per key, behind Caddy's limits.
// string (in practice the client IP). It is process-local: restarting the
// backend clears every window, and a multi-replica deployment would limit
// per replica rather than globally. Caddy applies its own rate limits in
// front of this, so this layer is a second line of defence, not the only one.
type RateLimiter struct { type RateLimiter struct {
mu sync.Mutex mu sync.Mutex
// attempts holds the timestamps of recent allowed attempts per key. attempts map[string][]time.Time
// Keys are never evicted, so memory grows with the number of distinct max int
// client IPs seen since start-up; acceptable for a personal site, but window time.Duration
// worth knowing before reusing this elsewhere. lastSweep time.Time
attempts map[string][]time.Time
max int
window time.Duration
} }
// NewRateLimiter returns a limiter allowing at most max calls to Allow per
// key within any window-length period.
func NewRateLimiter(max int, window time.Duration) *RateLimiter { func NewRateLimiter(max int, window time.Duration) *RateLimiter {
return &RateLimiter{ return &RateLimiter{
attempts: make(map[string][]time.Time), attempts: make(map[string][]time.Time),
@@ -35,21 +24,16 @@ func NewRateLimiter(max int, window time.Duration) *RateLimiter {
} }
} }
// Allow records an attempt for key and reports whether it is within the // Allow doesn't record rejected attempts, so hammering doesn't extend a lockout.
// limit. A rejected attempt is deliberately NOT recorded, so a caller that
// keeps hammering does not extend its own lockout indefinitely.
func (rl *RateLimiter) Allow(key string) bool { func (rl *RateLimiter) Allow(key string) bool {
rl.mu.Lock() rl.mu.Lock()
defer rl.mu.Unlock() defer rl.mu.Unlock()
now := time.Now() now := time.Now()
cutoff := now.Add(-rl.window) cutoff := now.Add(-rl.window)
rl.sweep(now, cutoff)
// Filter in place: slicing to [:0] reuses the existing backing array, so // Filtered in place, reusing the backing array.
// the append below overwrites the old timestamps instead of allocating a
// new slice on every request. Safe here because we only ever write an
// element at an index we have already read past. A missing key yields a
// nil slice, and nil[:0] is legal and yields nil.
valid := rl.attempts[key][:0] valid := rl.attempts[key][:0]
for _, t := range rl.attempts[key] { for _, t := range rl.attempts[key] {
if t.After(cutoff) { if t.After(cutoff) {
@@ -65,3 +49,17 @@ func (rl *RateLimiter) Allow(key string) bool {
rl.attempts[key] = append(valid, now) rl.attempts[key] = append(valid, now)
return true return true
} }
// sweep drops keys with no attempt inside the window, at most once a window,
// so keys that are never seen again don't accumulate.
func (rl *RateLimiter) sweep(now, cutoff time.Time) {
if now.Sub(rl.lastSweep) < rl.window {
return
}
rl.lastSweep = now
for key, times := range rl.attempts {
if len(times) == 0 || !times[len(times)-1].After(cutoff) {
delete(rl.attempts, key)
}
}
}
+1 -4
View File
@@ -9,10 +9,7 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// SeedDatabase populates an empty database with demo content for local // SeedDatabase is dev only: it creates an admin with password "password".
// development. It is called from main only when SEED_DB=true, which
// docker-compose.dev.yml sets; it must never run in production because it
// creates an admin account with the password "password".
func SeedDatabase(db *gorm.DB) { func SeedDatabase(db *gorm.DB) {
// "Any user exists" is the whole idempotency check — if the users table // "Any user exists" is the whole idempotency check — if the users table
// has a row, nothing is seeded, even if the other tables were emptied. // has a row, nothing is seeded, even if the other tables were emptied.
+14 -15
View File
@@ -8,18 +8,7 @@ import (
"time" "time"
) )
// Covered here: the pure logic in ratelimit.go, notes.go and gitea.go — // Expiry uses the real clock, hence the tiny window.
// sliding-window arithmetic, the path-traversal guard, and the two-stage JSON
// decoding of a Gitea feed entry (from a hand-written fixture).
//
// Deliberately not covered:
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
// logic beyond the request is the empty-feed nil,nil case, and testing it
// would mean either a network or an injected client that does not exist.
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
// directly and there is no injectable clock), so the expiry case below
// uses a deliberately tiny window rather than a long sleep.
func TestRateLimiterAllow(t *testing.T) { func TestRateLimiterAllow(t *testing.T) {
t.Run("calls up to max are allowed", func(t *testing.T) { t.Run("calls up to max are allowed", func(t *testing.T) {
@@ -69,6 +58,16 @@ func TestRateLimiterAllow(t *testing.T) {
} }
}) })
t.Run("keys idle past the window are evicted", func(t *testing.T) {
rl := NewRateLimiter(1, 5*time.Millisecond)
rl.Allow("gone")
time.Sleep(10 * time.Millisecond)
rl.Allow("other")
if _, ok := rl.attempts["gone"]; ok {
t.Fatal("idle key still stored, want evicted")
}
})
t.Run("max of zero denies everything", func(t *testing.T) { t.Run("max of zero denies everything", func(t *testing.T) {
rl := NewRateLimiter(0, time.Minute) rl := NewRateLimiter(0, time.Minute)
if rl.Allow("ip") { if rl.Allow("ip") {
@@ -163,7 +162,7 @@ func TestParseCommitMessage(t *testing.T) {
func TestGiteaFeedResponseDecoding(t *testing.T) { func TestGiteaFeedResponseDecoding(t *testing.T) {
const fixture = `[{ const fixture = `[{
"act_user": {"avatar_url": "http://gitea:3000/avatars/1", "login": "adamf"}, "act_user": {"avatar_url": "http://gitea:3000/avatars/1", "login": "adamf"},
"repo": {"full_name": "adamf/web_server", "html_url": "http://gitea:3000/adamf/web_server"}, "repo": {"full_name": "adamf/stpweb", "html_url": "http://gitea:3000/adamf/stpweb"},
"op_type": "commit_repo", "op_type": "commit_repo",
"content": "{\"Commits\":[{\"Message\":\"add tests\"}]}", "content": "{\"Commits\":[{\"Message\":\"add tests\"}]}",
"created": "2026-09-22T10:30:00Z", "created": "2026-09-22T10:30:00Z",
@@ -182,10 +181,10 @@ func TestGiteaFeedResponseDecoding(t *testing.T) {
if got.ActUser.AvatarURL != "http://gitea:3000/avatars/1" { if got.ActUser.AvatarURL != "http://gitea:3000/avatars/1" {
t.Errorf("AvatarURL = %q", got.ActUser.AvatarURL) t.Errorf("AvatarURL = %q", got.ActUser.AvatarURL)
} }
if got.Repo.FullName != "adamf/web_server" { if got.Repo.FullName != "adamf/stpweb" {
t.Errorf("FullName = %q", got.Repo.FullName) t.Errorf("FullName = %q", got.Repo.FullName)
} }
if got.Repo.HTMLURL != "http://gitea:3000/adamf/web_server" { if got.Repo.HTMLURL != "http://gitea:3000/adamf/stpweb" {
t.Errorf("HTMLURL = %q", got.Repo.HTMLURL) t.Errorf("HTMLURL = %q", got.Repo.HTMLURL)
} }
if got.OpType != "commit_repo" { if got.OpType != "commit_repo" {
+8 -39
View File
@@ -13,26 +13,17 @@ import (
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
// SpotifyConfig holds the OAuth app credentials.
//
// There is no state value here any more: the `state` parameter is a one-shot
// CSRF nonce minted per authorisation request by handlers.Store, so a fixed
// configured value would defeat the point.
type SpotifyConfig struct { type SpotifyConfig struct {
RedirectURL string RedirectURL string
ClientID string ClientID string
ClientSecret string ClientSecret string
} }
// SPOTIFY_TOKEN_JSON_PATH is inside a Docker volume, so the refresh token // On a mounted volume, so the OAuth dance survives rebuilds.
// survives container restarts and the OAuth dance only has to be done once.
const SPOTIFY_TOKEN_JSON_PATH = "/backend/token/spotify_token.json" const SPOTIFY_TOKEN_JSON_PATH = "/backend/token/spotify_token.json"
// SaveSpotifyToken persists an OAuth token to disk. // SaveSpotifyToken writes its own struct so the file format doesn't follow
// // oauth2.Token's.
// It copies the fields into a local anonymous struct rather than marshalling
// oauth2.Token directly, so the on-disk format stays stable regardless of what
// the oauth2 package adds to its own struct or its JSON tags.
func SaveSpotifyToken(path string, tok *oauth2.Token) error { func SaveSpotifyToken(path string, tok *oauth2.Token) error {
data := struct { data := struct {
AccessToken string `json:"access_token"` AccessToken string `json:"access_token"`
@@ -55,13 +46,9 @@ func SaveSpotifyToken(path string, tok *oauth2.Token) error {
return err return err
} }
// 0600 ensures only your user can read/write the file
return os.WriteFile(path, jsonBytes, 0600) return os.WriteFile(path, jsonBytes, 0600)
} }
// LoadSpotifyToken reads a token previously written by SaveSpotifyToken.
// A missing file returns an error, which callers treat as "not yet
// authenticated" rather than a fault.
func LoadSpotifyToken(path string) (*oauth2.Token, error) { func LoadSpotifyToken(path string) (*oauth2.Token, error) {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
@@ -89,16 +76,8 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
return tok, nil return tok, nil
} }
// InitSpotifyAuth builds the OAuth authenticator and, if a saved token // InitSpotifyAuth never fails startup: with no usable token it returns a nil
// exists, an authenticated client. // client, so every caller must nil-check Store.SpotifyClient.
//
// Start-up never fails on Spotify problems: when there is no token or the
// refresh is rejected it logs how to authenticate and returns a nil client.
// Every Spotify handler and resolver therefore has to nil-check
// Store.SpotifyClient. The authorisation URL can no longer be printed here
// because its state nonce is per-request (see handlers.Store.StartSpotifyAuth);
// following it sends the browser to /spotify/callback, which fills the client
// in at runtime.
func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) { func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) {
auth := spotifyauth.New( auth := spotifyauth.New(
spotifyauth.WithRedirectURL(config.RedirectURL), spotifyauth.WithRedirectURL(config.RedirectURL),
@@ -111,14 +90,12 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
), ),
) )
// check if token exists locally
token, err := LoadSpotifyToken(SPOTIFY_TOKEN_JSON_PATH) token, err := LoadSpotifyToken(SPOTIFY_TOKEN_JSON_PATH)
if err != nil || token == nil { if err != nil || token == nil {
fmt.Println("No Spotify token saved. Authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.") fmt.Println("No Spotify token saved. Authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
return auth, nil return auth, nil
} }
// refresh token and client
client, err := RefreshClient(auth, token) client, err := RefreshClient(auth, token)
if err != nil { if err != nil {
fmt.Println("Failed to refresh Spotify token. Re-authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.") fmt.Println("Failed to refresh Spotify token. Re-authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
@@ -128,18 +105,10 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
return auth, client return auth, client
} }
// RefreshClient exchanges a stored token for a fresh one and returns a client // RefreshClient saves the new token, ignoring write errors. The client's
// using it. // later automatic refreshes are not persisted.
//
// Spotify may issue a new refresh token during this exchange, so the result is
// written straight back to disk; the write error is ignored because a failed
// save only costs a re-authentication later, and failing the whole start-up
// over it would be worse. The returned client also holds the token source
// internally and keeps refreshing on its own — but those later refreshes are
// NOT persisted, so after a long uptime the file on disk can be stale.
func RefreshClient(auth *spotifyauth.Authenticator, token *oauth2.Token) (*spotify.Client, error) { func RefreshClient(auth *spotifyauth.Authenticator, token *oauth2.Token) (*spotify.Client, error) {
// context.Background rather than a request context: the resulting client // The client outlives the request that created it.
// is long-lived and must outlive whichever request triggered this.
ctx := context.Background() ctx := context.Background()
token, err := auth.RefreshToken(ctx, token) token, err := auth.RefreshToken(ctx, token)
+3 -13
View File
@@ -8,10 +8,6 @@ import (
"time" "time"
) )
// This file wraps the two public Steam Web API endpoints used by the home
// page. Results are cached by the caller (handlers.Store, 5 minute TTL) to
// stay well inside Steam's rate limits.
// SteamRecentGame is one game from GetRecentlyPlayedGames. Playtimes are in // SteamRecentGame is one game from GetRecentlyPlayedGames. Playtimes are in
// minutes. // minutes.
type SteamRecentGame struct { type SteamRecentGame struct {
@@ -30,10 +26,7 @@ type SteamRecentGamesResponse struct {
} `json:"response"` } `json:"response"`
} }
// SteamPlayerSummary is the subset of GetPlayerSummaries we care about. // PersonaState > 0 is some kind of online.
// PersonaState is Steam's online status enum: 0 = offline, anything higher
// is some flavour of online (online, busy, away, snooze, looking to trade or
// play), which is why the caller treats "> 0" as online.
type SteamPlayerSummary struct { type SteamPlayerSummary struct {
PersonaState int `json:"personastate"` PersonaState int `json:"personastate"`
} }
@@ -45,11 +38,8 @@ type SteamPlayerSummariesResponse struct {
} `json:"response"` } `json:"response"`
} }
// FetchRecentlyPlayedGames returns the three most recently played games. // Steam answers 200 with nothing for a private profile or bad key, so empty
// // is not an error.
// Steam answers with HTTP 200 and an empty envelope for a private profile or
// a bad key, so an empty slice and no error is the normal "nothing to show"
// result rather than a failure.
func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error) { func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error) {
url := fmt.Sprintf("https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=%s&steamid=%s&count=3", apiKey, steamID) url := fmt.Sprintf("https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=%s&steamid=%s&count=3", apiKey, steamID)
+5 -36
View File
@@ -7,42 +7,21 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// This file replaces gin.Logger with a formatter tuned for one reader: the // TrafficLogFormatter replaces gin.Logger: heartbeat and forward_auth traffic
// site owner scanning the log for "who is using my site". Two goals: // is dropped or terse, while external IPs, errors and slow requests stand out.
//
// 1. Quietness. The log is flooded by traffic that is not a human visit:
// Caddy forward_auth subrequests (/auth/validate-admin, re-run for every
// admin page hit), the front end's own polling (`/auth/refresh_token`,
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
// a single terse line, or dropped entirely when repeated in a short
// window — a 200 on a poll says nothing worth a line each time.
//
// 2. Salience. A request that matters (an external IP, an error status, a
// slow response) gets a line that stands out and carries the pieces that
// answer "who": client IP, path, status, latency.
// logQuietDrop lists paths whose 2xx responses are dropped outright. These
// are all heartbeat-style endpoints: identical every few seconds, no signal.
var logQuietDrop = map[string]bool{ var logQuietDrop = map[string]bool{
"/auth/validate-admin": true, // Caddy forward_auth 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
} }
// logQuietDropPrefix is the permission gate's auth_request subrequest // The permission gate's subrequests, as for /auth/validate-admin.
// (/auth/validate/<key>), dropped on 2xx for the same reason as
// /auth/validate-admin above: it repeats on every request to a gated page.
const logQuietDropPrefix = "/auth/validate/" const logQuietDropPrefix = "/auth/validate/"
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
// signature so it plugs into gin.LoggerWithFormatter.
func TrafficLogFormatter(params gin.LogFormatterParams) string { func TrafficLogFormatter(params gin.LogFormatterParams) string {
// gin hands the full URL (path + query) in Path; Query is split off
// params.ErrorMessage... not needed — just use Path which carries both.
path := params.Path path := params.Path
// Latency is human-scaled rather than raw nanoseconds: "1.2ms" scans
// faster than "1230689ns" when you are skimming.
latency := params.Latency latency := params.Latency
unit := "ns" unit := "ns"
switch { switch {
@@ -56,8 +35,6 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
unit, latency = "µs", latency/time.Microsecond unit, latency = "µs", latency/time.Microsecond
} }
// Errors (>=500) are marked so they survive even a fast scroll; the
// literal marker also makes them greppable in a rotated log.
marker := "" marker := ""
if params.StatusCode >= 500 { if params.StatusCode >= 500 {
marker = " !!! SERVER ERROR" marker = " !!! SERVER ERROR"
@@ -65,9 +42,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
marker = " !!" marker = " !!"
} }
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them // Failures on these are still worth seeing.
// is still interesting (an expired session raging against refresh, a
// broken admin gate) and is kept.
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 { if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
return "" return ""
} }
@@ -75,9 +50,6 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
line := fmt.Sprintf("%s %s %d %s%s", params.Method, path, params.StatusCode, line := fmt.Sprintf("%s %s %d %s%s", params.Method, path, params.StatusCode,
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
// traffic (the edge's own feet on the internal subnet) already has its IP
// implied and is left lean.
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) { if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
line += " " + params.ClientIP line += " " + params.ClientIP
} }
@@ -85,11 +57,8 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
return line + "\n" return line + "\n"
} }
// logIsInterestingClient reports whether a client IP is likely an actual
// visitor rather than infrastructure. Caddy proxies everything, so the IPs
// that appear are either forwarded-from-humans or the ingress itself.
func logIsInterestingClient(ip string) bool { func logIsInterestingClient(ip string) bool {
// Docker's bridge network: the edge's own feet. Not a visitor. // The Docker bridge: infrastructure, not a visitor.
return !startsWith(ip, "172.28.") return !startsWith(ip, "172.28.")
} }
+28 -100
View File
@@ -22,51 +22,25 @@ import (
"github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3"
) )
// Uploaded files: everything the site stores from a user and serves back at // Every stored file goes through Uploads.Save. An *UploadError is the
// /uploads/. One entry point for any handler that takes a file: // uploader's fault and safe to show; any other error is ours.
// // Public files go to Garage, falling back to the volume; private files
// url, err := store.Uploads.Save(ctx, fileHeader, private) // always go to the volume, because Caddy can gate a path but can't sign S3.
//
// Save validates the file against UploadTypes and MaxUploadSize, gives it a
// random name, stores it, and returns the URL to put in the page. An
// *UploadError is the uploader's fault and its message is safe to show them;
// any other error is ours (log it, answer 500).
//
// WHERE FILES GO
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
// the `uploads` volume as a fallback for when Garage refuses a write. Caddy
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (caddy/routes.caddy), so the URL is the same wherever the
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
// the only store.
// Private files (admin-only chat attachments) always go to the volume, under
// /uploads/private/, which Caddy gates behind an admin check. Caddy can't
// sign S3 requests, so it has no way to gate a bucket.
//
// Everything public is reachable by anyone who has the URL, with no login.
// That is why the type checks below are strict, and why names are random.
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
// disk or the bucket; 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 // Served back as-is, and Caddy sends nosniff, so it must be right.
// returns exactly this, and the browser renders by it: Caddy adds
// `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 // What http.DetectContentType must report. Empty skips the check, which
// first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty // is unreliable for audio and gif.
// means "not checked": DetectContentType is too unreliable for audio and
// gif files, and checking would reject legitimate ones.
SniffPrefix string SniffPrefix string
} }
// UploadTypes is the allow-list, keyed by lower-cased extension with its dot. // UploadTypes is the allow-list. Never add anything a browser would execute
// Nothing a browser would execute or render as markup (.html, .svg, .js, ...) // or render as markup: these are served from our origin. Mirrored by
// may ever be added: these files are served from our own origin. The // vue/src/uploads.js's ACCEPT.
// frontend's file pickers (vue/src/uploads.js, ACCEPT) list the same types.
var UploadTypes = map[string]UploadType{ var UploadTypes = map[string]UploadType{
".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"}, ".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"}, ".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
@@ -81,8 +55,6 @@ var UploadTypes = map[string]UploadType{
".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"}, ".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"},
} }
// UploadError is a rejected upload: the uploader's mistake, with a message
// meant for them. The handler answers 400 with it.
type UploadError struct{ Message string } type UploadError struct{ Message string }
func (e *UploadError) Error() string { return e.Message } func (e *UploadError) Error() string { return e.Message }
@@ -94,26 +66,17 @@ var (
ErrUploadUnreadable = &UploadError{"failed to read file content"} ErrUploadUnreadable = &UploadError{"failed to read file content"}
) )
// Uploads stores files. Build it with NewUploads.
type Uploads struct { type Uploads struct {
public FileStore public FileStore
private FileStore private FileStore
} }
// URL prefixes the files are served under; Caddy owns both paths.
const ( const (
publicURLPrefix = "/uploads/" publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/" privateURLPrefix = "/uploads/private/"
) )
// NewUploads picks the stores. publicDir and privateDir are directories on the // NewUploads falls back to the volume alone when S3 is unset or misconfigured.
// shared `uploads` volume (/backend/uploads/ and its private/ subdirectory in
// the container).
//
// With no S3 endpoint the public store is the volume alone, the behaviour
// before Garage. An endpoint with missing credentials is a configuration
// mistake: it is logged and the volume is used rather than failing every
// upload.
func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads { func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
disk := DiskFileStore{Dir: publicDir} disk := DiskFileStore{Dir: publicDir}
u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}} u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}}
@@ -130,9 +93,7 @@ func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
return u return u
} }
// Save validates and stores one uploaded file and returns its URL // Save stores one file and returns its URL. Only admins may save private files.
// (/uploads/<name>, or /uploads/private/<name>). Authorisation is the
// caller's job: only an admin may save a private file.
func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) { func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) {
if fh.Size > MaxUploadSize { if fh.Size > MaxUploadSize {
return "", ErrUploadTooLarge return "", ErrUploadTooLarge
@@ -150,8 +111,7 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
defer f.Close() defer f.Close()
if kind.SniffPrefix != "" { if kind.SniffPrefix != "" {
// 512 bytes is all http.DetectContentType looks at. A short read is // A short read is fine; only an empty file fails.
// fine; sniffing works on a prefix, so only an empty file is an error.
buf := make([]byte, 512) buf := make([]byte, 512)
n, err := io.ReadFull(f, buf) n, err := io.ReadFull(f, buf)
if n == 0 { if n == 0 {
@@ -168,9 +128,8 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
} }
} }
// The uploaded name is thrown away for 16 random bytes. That rules out // A random name rules out traversal and collisions, and makes the URL
// path traversal and collisions in one go, and makes the URL unguessable. // unguessable.
// Only the extension survives, and it is on the allow-list.
b := make([]byte, 16) b := make([]byte, 16)
if _, err := rand.Read(b); err != nil { if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generating filename: %w", err) return "", fmt.Errorf("generating filename: %w", err)
@@ -187,7 +146,6 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
return prefix + name, nil return prefix + name, nil
} }
// StoredFile is one public upload, as listed for the admin's upload picker.
type StoredFile struct { type StoredFile struct {
Name string `json:"name"` Name string `json:"name"`
URL string `json:"url"` URL string `json:"url"`
@@ -195,16 +153,8 @@ type StoredFile struct {
Modified time.Time `json:"modified"` Modified time.Time `json:"modified"`
} }
// List returns every public upload, newest first. Private files are never // List returns public uploads, newest first. Admin only: unguessable URLs are
// listed: they live in their own store, which this doesn't touch. // the only protection for unlinked files. Off-list extensions are dropped.
//
// The caller must be an admin. An upload's URL is public but unguessable, and
// that is the only thing keeping a file nobody linked to from being found; a
// listing anyone could read would hand every one of them out.
//
// Only names with an extension on the allow-list are returned, so anything
// else that ends up in the bucket or the directory (by hand, through
// garage-webui) never reaches a page through the picker.
func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) { func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
files, err := u.public.List(ctx) files, err := u.public.List(ctx)
if err != nil { if err != nil {
@@ -223,22 +173,17 @@ func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
// ---- Stores ---------------------------------------------------------------- // ---- Stores ----------------------------------------------------------------
// FileStore stores one file under key, and lists what it holds. r is a // FileStore takes a ReadSeeker because S3 hashes the body before sending and
// ReadSeeker because the S3 client must hash the body before sending it over // FallbackFileStore rewinds it to retry. List returns top-level files only.
// plain HTTP, and because FallbackFileStore rewinds it to retry; a
// multipart.File satisfies it.
//
// List returns top-level files only, with URL unset (Uploads.List fills it).
type FileStore interface { type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
List(ctx context.Context) ([]StoredFile, error) List(ctx context.Context) ([]StoredFile, error)
} }
// DiskFileStore writes files into Dir, creating it if needed.
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 the edge, in another container, can reach and read the files. // World-readable so Caddy, in another container, can serve them.
if err := os.MkdirAll(d.Dir, 0755); err != nil { if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err return err
} }
@@ -253,9 +198,7 @@ func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _
return out.Close() return out.Close()
} }
// List skips subdirectories, which is what keeps the private/ directory // List skips directories, which keeps private/ out of the listing.
// (inside the public one on the volume) out of the listing. A directory that
// doesn't exist yet just holds nothing.
func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) { func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
entries, err := os.ReadDir(d.Dir) entries, err := os.ReadDir(d.Dir)
if errors.Is(err, fs.ErrNotExist) { if errors.Is(err, fs.ErrNotExist) {
@@ -278,13 +221,11 @@ func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
return files, nil return files, nil
} }
// S3FileStore writes files into one bucket of an S3-compatible server.
type S3FileStore struct { type S3FileStore struct {
client *s3.Client client *s3.Client
bucket string bucket string
} }
// S3Config is the S3_* block of .env.
type S3Config struct { type S3Config struct {
Endpoint string // e.g. http://garage:3900 Endpoint string // e.g. http://garage:3900
Region string // must match garage.toml's s3_region Region string // must match garage.toml's s3_region
@@ -293,9 +234,7 @@ type S3Config struct {
SecretAccessKey string SecretAccessKey string
} }
// s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on // Garage is on the same network, so anything near this is a hang.
// the same Docker network, so anything near this is a hang, and the fallback
// to disk is better than holding the request open.
const s3Timeout = 30 * time.Second const s3Timeout = 30 * time.Second
func NewS3FileStore(cfg S3Config) *S3FileStore { func NewS3FileStore(cfg S3Config) *S3FileStore {
@@ -303,12 +242,9 @@ func NewS3FileStore(cfg S3Config) *S3FileStore {
BaseEndpoint: aws.String(cfg.Endpoint), BaseEndpoint: aws.String(cfg.Endpoint),
Region: cfg.Region, Region: cfg.Region,
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""), Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
// Garage addresses buckets by path (/bucket/key); virtual-host style // Garage needs path-style addressing.
// would need a DNS name per bucket.
UsePathStyle: true, UsePathStyle: true,
// Recent SDKs add CRC32 checksums to every PUT by default. Only send // Default CRC32 checksums aren't reliably supported by non-AWS servers.
// them where S3 requires them, which is what third-party servers
// handle reliably.
RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
}) })
@@ -332,9 +268,7 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
return nil return nil
} }
// List pages through the whole bucket. Keys containing "/" are skipped: they // List skips keys under a prefix: those were put there by hand.
// are not uploads (Save never makes one) but something put under a prefix by
// 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()
@@ -357,10 +291,8 @@ func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
return files, nil return files, nil
} }
// FallbackFileStore tries Primary and, if that fails, logs it and writes to // FallbackFileStore writes to Fallback when Primary fails. Caddy serves from
// Fallback instead. The upload still succeeds and its URL still works (Caddy // both, so the URL still works.
// looks in both places), so a Garage outage costs a log line rather than
// broken uploads.
type FallbackFileStore struct { type FallbackFileStore struct {
Primary FileStore Primary FileStore
Fallback FileStore Fallback FileStore
@@ -378,11 +310,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 Caddy serves from both: the // List merges both stores, primary first, since Caddy serves from both.
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the
// fallback's files are returned alone, as for Put.
func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) { func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) {
primary, err := f.Primary.List(ctx) primary, err := f.Primary.List(ctx)
if err != nil { if err != nil {
+1 -7
View File
@@ -17,13 +17,7 @@ import (
"time" "time"
) )
// Covered here: the type table (the upload trust boundary's data), Save's // A successful Garage write is checked by hand (DEPLOYMENT.md, "Garage").
// validation, naming and routing, which store NewUploads picks, and the
// fallback — including against a real S3 client talking to a server that
// refuses the write, since "Garage said no" is the case it exists for.
//
// Not covered: a successful PutObject or ListObjectsV2 against Garage. That needs the garage
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
// fileHeader builds the *multipart.FileHeader a handler would get from // fileHeader builds the *multipart.FileHeader a handler would get from
// ctx.FormFile, by round-tripping a real multipart body. // ctx.FormFile, by round-tripping a real multipart body.
+56 -75
View File
@@ -1,8 +1,8 @@
package services package services
import ( import (
"log"
"net/http" "net/http"
"net/url"
"sync" "sync"
"time" "time"
@@ -12,68 +12,58 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
// This file is the chat hub behind GET /ws. It is deliberately a package-level // The chat hub behind GET /ws: one process, one room, so package-level state.
// singleton (one process, one chat room) rather than an injectable type, so the
// connection set, the database handle and the allowed origin all live in
// package vars initialised once by InitWebSocket.
// maxMessages is both the size of the history replayed to a new client and the // History replayed on connect, and rows kept in the database.
// number of rows kept in the database: every insert trims older messages.
const maxMessages = 50 const maxMessages = 50
// allowedDomain is the site's domain, set by InitWebSocket and read by
// Upgrader.CheckOrigin. It is a package var because the Upgrader is one too.
var allowedDomain string var allowedDomain string
// Upgrader turns the HTTP request into a WebSocket. // CheckOrigin is the only cross-origin defence: browsers send cookies on a
// // WebSocket handshake with no preflight. Gorilla's same-host default would
// CheckOrigin is the only cross-origin defence on this endpoint: the browser // reject the apex/www split and the Vite dev server.
// sends cookies with a WebSocket handshake regardless of origin and there is
// no preflight, so without this check any site could open a socket as a
// logged-in visitor. Default gorilla behaviour (same-host only) is too strict
// here because the site is reached as both example.com and www.example.com,
// and "localhost" is allowed for the Vite dev server.
var Upgrader = websocket.Upgrader{ var Upgrader = websocket.Upgrader{
ReadBufferSize: 1024, ReadBufferSize: 1024,
WriteBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin") origin := r.Header.Get("Origin")
if origin == "" { return origin != "" && IsSiteOrigin(origin, allowedDomain)
return false
}
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
}, },
} }
var ( var (
// clients maps each open connection to whether it belongs to an admin.
clients = make(map[*websocket.Conn]bool) clients = make(map[*websocket.Conn]bool)
// mu guards clients AND serialises the write-then-broadcast sequence, so // Also serialises write-then-broadcast so all clients see one order.
// that two concurrent senders cannot interleave and deliver messages to
// different clients in different orders.
mu sync.Mutex mu sync.Mutex
wsDB *gorm.DB wsDB *gorm.DB
// nextAuthorID is a per-process counter handed out on connect. It is NOT // Per-process connection number, not a user id; chat is pseudonymous.
// a user id and has no meaning across restarts: the chat is pseudonymous,
// and the front end only uses it to colour/group consecutive messages
// from the same connection.
nextAuthorID uint nextAuthorID uint
) )
// Per-connection flood limit, separate from services.RateLimiter because it // Per-socket flood limit (frames, not requests per IP).
// counts frames on one socket rather than requests from one IP.
const ( const (
rateLimitWindow = time.Second rateLimitWindow = time.Second
rateLimitMaxMsgs = 10 rateLimitMaxMsgs = 10
) )
// wsIncoming is the envelope clients send over the socket. A plain chat // The route is public, so frame and field sizes are capped. Writes happen
// message carries text/fileUrl/private; an admin delete carries action+id. // under mu, so a stalled client may hold it for at most writeWait.
// ChatPanel's maxlength of 1000 UTF-16 units is at most 3000 bytes, under
// maxContentBytes; over-limit messages are dropped silently.
const (
maxFrameBytes = 16 << 10
maxContentBytes = 4000
maxFileURLBytes = 512
writeWait = 5 * time.Second
)
func writeJSON(conn *websocket.Conn, v any) error {
if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
return err
}
return conn.WriteJSON(v)
}
type wsIncoming struct { type wsIncoming struct {
Action string `json:"action,omitempty"` Action string `json:"action,omitempty"`
ID uint `json:"id,omitempty"` ID uint `json:"id,omitempty"`
@@ -82,37 +72,29 @@ type wsIncoming struct {
Private bool `json:"private,omitempty"` Private bool `json:"private,omitempty"`
} }
// wsDeleteEvent is broadcast to every client when a message is removed.
type wsDeleteEvent struct { type wsDeleteEvent struct {
Action string `json:"action"` Action string `json:"action"`
ID uint `json:"id"` ID uint `json:"id"`
} }
// wsHistoryEvent is sent once on connect with the recent messages the client // Sent as one batch so a reconnect replaces the list without blanking it.
// may see. Sending it as a single batch lets the client replace its list
// atomically, so a reconnect does not blank the chat and reload every image.
type wsHistoryEvent struct { type wsHistoryEvent struct {
Action string `json:"action"` Action string `json:"action"`
Messages []models.Message `json:"messages"` Messages []models.Message `json:"messages"`
} }
// InitWebSocket wires the package-level hub to the database and the origin
// allow-list. Call it once, before serving.
func InitWebSocket(database *gorm.DB, domain string) { func InitWebSocket(database *gorm.DB, domain string) {
wsDB = database wsDB = database
allowedDomain = domain allowedDomain = domain
} }
// HandleWebSocket serves one chat connection. isAdmin controls whether the // isAdmin allows seeing, sending and deleting private messages.
// connection may see private messages, send them, and delete messages.
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) { func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
defer conn.Close() defer conn.Close()
conn.SetReadLimit(maxFrameBytes)
// Registration, history read and history send all happen under one lock. // Register and snapshot under one lock, so a concurrent broadcast is
// That is the point: it guarantees the client is already in `clients` // either in the history or delivered after it, never lost or reordered.
// before its snapshot is taken, so a message broadcast concurrently is
// either in the history or delivered afterwards — never dropped in the
// gap, and never delivered before the history that would overwrite it.
mu.Lock() mu.Lock()
clients[conn] = isAdmin clients[conn] = isAdmin
nextAuthorID++ nextAuthorID++
@@ -123,24 +105,23 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
if !isAdmin { if !isAdmin {
historyQuery = historyQuery.Where("private = ?", false) historyQuery = historyQuery.Where("private = ?", false)
} }
historyQuery.Find(&history) if err := historyQuery.Find(&history).Error; err != nil {
log.Printf("[ws] loading history: %v", err)
}
if err := conn.WriteJSON(wsHistoryEvent{Action: "history", Messages: history}); err != nil { if err := writeJSON(conn, wsHistoryEvent{Action: "history", Messages: history}); err != nil {
delete(clients, conn) delete(clients, conn)
mu.Unlock() mu.Unlock()
return return
} }
mu.Unlock() mu.Unlock()
// Fixed-window flood limit. Over-limit frames are dropped silently with // Over-limit frames are dropped silently.
// no error to the client and without resetting the window.
msgCount := 0 msgCount := 0
windowStart := time.Now() windowStart := time.Now()
for { for {
var incoming wsIncoming var incoming wsIncoming
// Any read error — clean close, network drop or malformed JSON —
// ends the connection; there is no attempt to resynchronise.
if err := conn.ReadJSON(&incoming); err != nil { if err := conn.ReadJSON(&incoming); err != nil {
break break
} }
@@ -162,33 +143,35 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
continue continue
} }
if len(incoming.Text) > maxContentBytes || len(incoming.FileURL) > maxFileURLBytes {
continue
}
msg := models.Message{ msg := models.Message{
Content: incoming.Text, Content: incoming.Text,
FileURL: incoming.FileURL, FileURL: incoming.FileURL,
AuthorID: authorID, AuthorID: authorID,
// Only admins may mark a message private. Private: incoming.Private && isAdmin,
Private: incoming.Private && isAdmin,
} }
mu.Lock() mu.Lock()
wsDB.Create(&msg) if err := wsDB.Create(&msg).Error; err != nil {
// Keep only the newest maxMessages rows. This is a soft delete mu.Unlock()
// (models.Message has gorm.DeletedAt), so the rows stay in the table log.Printf("[ws] saving message: %v", err)
// with deleted_at set and GORM filters them out of later reads; the continue
// table therefore grows forever even though the chat does not. }
// The subquery is itself soft-delete filtered, so already-trimmed // Soft delete, so the table still grows; the chat does not.
// rows are not re-deleted. if err := wsDB.Where("id NOT IN (?)",
wsDB.Where("id NOT IN (?)",
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages), wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
).Delete(&models.Message{}) ).Delete(&models.Message{}).Error; err != nil {
log.Printf("[ws] pruning messages: %v", err)
}
// Deleting from a map while ranging over it is explicitly allowed in
// Go, so pruning dead clients inline here is safe.
for client, clientAdmin := range clients { for client, clientAdmin := range clients {
if msg.Private && !clientAdmin { if msg.Private && !clientAdmin {
continue continue
} }
if err := client.WriteJSON(msg); err != nil { if err := writeJSON(client, msg); err != nil {
client.Close() client.Close()
delete(clients, client) delete(clients, client)
} }
@@ -201,9 +184,7 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
mu.Unlock() mu.Unlock()
} }
// deleteMessage soft-deletes a message and tells every client to drop it. // deleteMessage soft-deletes and broadcasts; clients ignore unknown ids.
// Clients that never received the message (non-admins for a private one)
// simply ignore the unknown id.
func deleteMessage(id uint) { func deleteMessage(id uint) {
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
@@ -215,7 +196,7 @@ func deleteMessage(id uint) {
event := wsDeleteEvent{Action: "delete", ID: id} event := wsDeleteEvent{Action: "delete", ID: id}
for client := range clients { for client := range clients {
if err := client.WriteJSON(event); err != nil { if err := writeJSON(client, event); err != nil {
client.Close() client.Close()
delete(clients, client) delete(clients, client)
} }
+40 -215
View File
@@ -1,107 +1,32 @@
# ============================================================================= # Global options and shared snippets. Routes are in routes.caddy; per-mode
# Caddyfile — the public edge: TLS, the SPA, and the reverse proxy in front of # sites in sites/<CADDY_SITE>.caddy. {$X} is substituted at parse time and
# every other service. Replaced nginx and certbot (now .deprecated/) on # saved into /config, so secrets are read as {env.X} instead.
# 2026-11-17.
#
# FILES (all baked into the image by caddy/Dockerfile)
# Caddyfile this file: global options, the snippets every site
# uses, the healthcheck site, and the import that picks
# the dev or production sites.
# routes.caddy the proxy route table, shared by dev and production.
# ADD A NEW PROXIED ROUTE THERE.
# sites/prod.caddy production: http -> https://www, the apex (registry
# and redirect), the www site.
# sites/dev.caddy dev: localhost on http and https, `/` -> Vite.
#
# WHICH SITES ARE LOADED
# CADDY_SITE picks the file (`prod` unless set; docker-compose.dev.yml sets
# `dev`). It is a parse-time {$VAR}, substituted before the Caddyfile is
# read, so it can name the import itself.
#
# TWO KINDS OF VARIABLE
# {$NAME} / {$NAME:default} read from the environment ONCE, when the config
# is parsed. Used for upstream names and the
# domain. They end up in the JSON config Caddy
# autosaves to /config, so never a secret.
# {env.NAME} read per use at runtime, never written into the
# config. Used for the two secrets: the
# Cloudflare DNS token and the receipt token.
# Every variable must be in the caddy service's explicit `environment:`
# list in docker-compose.yml, or it reaches Caddy empty. Note an EMPTY
# variable is not "unset": {$X:default} keeps the empty value. So defaults
# live in that compose list (${X:-default}), which treats both alike, as
# nginx's entrypoint's ${X:-default} did.
#
# WHAT NO LONGER NEEDS DOING (vs nginx)
# - Upstreams are resolved when Caddy dials them, not at startup, so it
# boots with any container missing and 502s until it appears. No
# `resolver` / `set $upstream_*` trick.
# - Certificates are obtained and renewed in-process (sites/prod.caddy), and
# Caddy serves while it does, so there is no bootstrap config, no certbot,
# no reload sentinel.
# - `header` is additive: a route that sets its own headers keeps the site's
# too. No security_headers.conf re-included everywhere.
# - Websocket upgrades, streaming responses and request-body streaming are
# the reverse proxy's defaults.
# =============================================================================
{ {
# No `email`: the ACME account works without one, Let's Encrypt stopped # No `email`: with EMAIL unset that line is a parse error.
# sending expiry notices in 2025, and an `email {$EMAIL}` line with EMAIL
# unset is a parse error that keeps the whole edge from starting.
# rate_limit is a plugin, so it has no place in Caddy's built-in directive # Count requests before forward_auth asks the backend.
# order. Before basic_auth means before forward_auth too: a gated route
# counts the request before asking the backend about the session, as
# nginx's limit_req (preaccess phase) ran before auth_request (access).
order rate_limit before basic_auth order rate_limit before basic_auth
# Dev's `tls internal` would otherwise try to add Caddy's local CA to the # Stops `tls internal` trying to edit the container's trust store.
# container's trust store, which is pointless and logs an error.
skip_install_trust skip_install_trust
servers { servers {
# Real client IP behind the Cloudflare tunnel. For connections from # Trust CF-Connecting-IP only from cloudflared's fixed IP. Trusting the
# the cloudflared container, and only those, the client IP is taken # subnet would let direct visitors (via the bridge gateway) pick their IP.
# from Cloudflare's CF-Connecting-IP header. {client_ip} is then the
# visitor everywhere it is used: the rate-limit keys, the access log,
# and the X-Real-IP / X-Forwarded-For sent upstream (see `proxy`).
#
# Pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the subnet. Direct
# visitors on the published 80/443 can arrive from the bridge gateway,
# 172.28.0.1, so trusting the subnet would let anyone choose their own
# IP, and so their own rate-limit bucket, by sending the header.
trusted_proxies static 172.28.255.250 trusted_proxies static 172.28.255.250
client_ip_headers CF-Connecting-IP client_ip_headers CF-Connecting-IP
# No HTTP/3: 443/udp is not published and cloudflared does not use it, # 443/udp is not published.
# so advertising it (Alt-Svc) would only send browsers on a detour.
protocols h1 h2 protocols h1 h2
} }
# ---- Access logs --------------------------------------------------------- # Keep access logs out of the default logger, or bodies print unfiltered.
# Every site imports `logging`, which names its access logger `payloads`.
# The two loggers below take that stream; the default logger is told to
# leave it alone, or each request would also be printed unfiltered,
# request body included.
log default { log default {
exclude http.log.access.payloads exclude http.log.access.payloads
} }
# The payload log: one JSON line per request, body included (log_append # One JSON line per request, body included. A body mentioning a password,
# in `logging`), for seeing what actually arrives at the edge. # token or secret is redacted whole: there is no JSON parser here.
# logs/caddy/ on the host; the `traffic` container tails it so Dozzle
# shows it as its own stream. Caddy rotates it itself, and
# `tail -F` follows the rotation. 0644 so `jq` on the host can read it
# unprivileged (Caddy's default is 0600).
#
# Redaction: any body mentioning a password, token or secret is replaced
# whole, not field by field, because there is no JSON parser here. That
# catches /auth/login, the GraphQL login and change-password mutations and
# the refresh-token call in one rule. Over-matching (a query that merely
# selects a field named *token*) costs a hidden body, never a leak.
# Cookie and Authorization headers are logged as REDACTED by Caddy itself
# (the `log_credentials` server option is off).
log payloads_file { log payloads_file {
include http.log.access.payloads include http.log.access.payloads
output file /var/log/caddy/payloads.log { output file /var/log/caddy/payloads.log {
@@ -117,9 +42,7 @@
} }
} }
# The container's stdout, which `docker compose logs caddy` and Dozzle # One short line per request for `docker logs` and Dozzle.
# show: the same requests cut down to one short line each, without the
# body or headers, like nginx's `compact` format.
log payloads_stdout { log payloads_stdout {
include http.log.access.payloads include http.log.access.payloads
output stdout output stdout
@@ -136,36 +59,16 @@
} }
# ---- Snippets ---------------------------------------------------------------- # ---- 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 # Overwrite X-Forwarded-For rather than append, so upstreams see only the
# X-Forwarded-Proto/Host. X-Forwarded-For is overwritten rather than left to # visitor, not cloudflared.
# Caddy's default, which APPENDS the trusted peer: behind the tunnel that is
# "<visitor>, 172.28.255.250", and Gitea (REVERSE_PROXY_LIMIT = 1, so the
# rightmost entry) would log cloudflared for every visitor. With exactly one
# entry, the visitor, every upstream sees what nginx gave it: gin's ClientIP()
# (backend/main.go, trusts 172.28/16), Gitea, and python/app/main.py's
# _internal_only guard, which refuses any request carrying either header.
(proxy) { (proxy) {
header_up X-Real-IP {client_ip} header_up X-Real-IP {client_ip}
header_up X-Forwarded-For {client_ip} header_up X-Forwarded-For {client_ip}
} }
# import limit <zone> <events> <window> # 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.
# A sliding window: at most <events> per <window> per client IP, then 429
# (turned into 503 by `errors`). Unlike nginx's leaky bucket there is no
# separate burst, so each zone's <events> is nginx's rate and <window> its
# unit, which keeps the sustained rates exact; the instant allowance comes out
# close to nginx's burst + 1. DEPLOYMENT.md §6 has the table and the reasoning
# behind each zone.
#
# State is shared per ZONE NAME across every route that names it (the plugin
# keeps one pool keyed by name), which is how /api, /py, /jobs, /usaco and
# /tracker share one `api` bucket, as in nginx. So a zone name must always be
# given the same <events> and <window>; a route that wants different numbers
# needs its own zone name (see `receipt`).
(limit) { (limit) {
rate_limit { rate_limit {
zone {args[0]} { zone {args[0]} {
@@ -176,20 +79,8 @@
} }
} }
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/, # forward_auth sends no body. orig_uri because strip_prefix runs first; the
# Gitea's history views, /uploads/private/) ---- # `*` stops redir reading the target as a path matcher.
# forward_auth sends a GET carrying the original request's headers, cookie
# included, to the backend's /auth/validate-admin before the request goes
# anywhere. 2xx lets it through; 401/403 become a redirect to the SPA login.
# This puts the Go backend's session in front of services that have no idea
# it exists. The body is never sent (the method is rewritten to GET), so a
# 2 GB garage-webui upload does not go to the backend twice.
#
# {http.request.orig_uri}, not {uri}: a route's `uri strip_prefix` runs
# BEFORE forward_auth in Caddy's directive order, so {uri} would have lost its
# prefix by the time this redirect is built. The `*` matters too: given only a
# target and a status, `redir` takes a target starting with / as a path
# MATCHER, and the redirect would never fire.
(admin_gate) { (admin_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} { forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate-admin uri /auth/validate-admin
@@ -200,19 +91,8 @@
} }
} }
# ---- Permission gate (/receipt/) ---- # import permission_gate <key>. 403 goes to /no-access, not the login page.
# import permission_gate <key> # copy_headers drops any client-sent X-Remote-User, so upstreams can trust it.
#
# The same mechanism, but asking GET /auth/validate/<key> whether the session
# holds one named permission (backend/services/permissions.go; admins hold
# them all), so a non-admin account granted it in the admin panel gets in.
# 401 (not signed in) goes to the login page; 403 (signed in, not granted)
# goes to a page that says so, since sending a signed-in user to log in again
# only shows them "Already signed in".
#
# On success the backend returns the username in X-Auth-User, copied onto the
# proxied request as X-Remote-User. copy_headers deletes any X-Remote-User the
# client sent before it sets the real one, so the upstream can trust it.
(permission_gate) { (permission_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} { forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate/{args[0]} uri /auth/validate/{args[0]}
@@ -228,13 +108,7 @@
} }
} }
# Production only (sites/prod.caddy); HSTS on localhost would poison the # Production only: HSTS on localhost would affect every local project.
# browser for every other localhost project on the machine.
#
# No site-wide CSP here. Gitea (proxied at /gitea/) relies on inline <script>
# blocks its own templates generate, so a shared script-src would need
# 'unsafe-inline', which voids almost all of CSP's value. If a real CSP
# matters again, give the SPA document its own, separate from Gitea.
(security_headers) { (security_headers) {
header { header {
X-Frame-Options "SAMEORIGIN" X-Frame-Options "SAMEORIGIN"
@@ -244,13 +118,8 @@
} }
} }
# User-uploaded files are attacker-supplied bytes on our own origin. nosniff # Uploads are attacker-supplied bytes on our origin. `>` makes these win over
# stops content-type guessing (so backend/services/uploads.go's stored type is # Garage's headers.
# what the browser goes by), Content-Disposition inline keeps them from being
# treated as downloads, and the locked-down CSP means even an uploaded .html
# can run no script and load no resource. `>` defers each one until the
# response is written, so it also wins over anything Garage sends. (-Server
# and -Via repeat `common`'s, for the error route, which does not run it.)
(upload_headers) { (upload_headers) {
header { header {
>X-Content-Type-Options "nosniff" >X-Content-Type-Options "nosniff"
@@ -261,45 +130,22 @@
} }
} }
# The disk half of /uploads/ (see routes.caddy): hand the request to the # Serves /uploads/ from disk via the :2080 site. A proxy, not file_server,
# uploads disk site at the bottom of this file. Used both when Garage answers # because in an error route file_server replies with the error's status.
# 404/5xx (handle_response) and when it cannot be reached at all (`errors`), # Error routes don't inherit deferred headers, hence the import.
# so it works from the ORIGINAL path, whatever the route had stripped by then.
#
# Why proxy to a second site rather than call file_server here: in an error
# route file_server answers with the ERROR's status, so a file served while
# Garage is down would arrive as a 502 (with the file as its body), and
# forcing 200 instead would also turn its 206 and 304 answers into 200s. A
# proxied response keeps whatever status the disk site gave it.
#
# The headers are imported again because error routes do not inherit the
# deferred ones of the route that failed.
(uploads_disk) { (uploads_disk) {
import upload_headers import upload_headers
rewrite * {http.request.orig_uri.path} rewrite * {http.request.orig_uri.path}
reverse_proxy 127.0.0.1:2080 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) { (errors) {
# rate_limit's 429. Answered as 503, the status nginx's limit_req used, # 503, not 429: hotelsStream.js reads 429 as the Python service's own limit.
# because vue/src/views/hotels/hotelsStream.js tells the two apart: 503 is
# "too many searches from your address", while a 429 is the Python
# service's own "someone else is searching right now".
handle_errors 429 { handle_errors 429 {
respond "Too many requests from your address. Wait a moment and retry." 503 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 # Keyed on vars set by the route, which cannot be spoofed like a path.
# into something better than a bare 502, each keyed on a variable its
# route sets (error routes keep the request's vars, and a variable cannot
# be spoofed the way a path can be dressed up):
# uploads_fallback Garage is down: serve the file from disk instead.
# receipt_upstream set only once the permission gate has passed, so a
# backend outage is not reported as the printer's.
# radar_upstream the Partner Radar stack (radar.DOMAIN) is down.
handle_errors 502 504 { handle_errors 502 504 {
@uploads_fallback vars uploads_fallback yes @uploads_fallback vars uploads_fallback yes
handle @uploads_fallback { handle @uploads_fallback {
@@ -313,32 +159,26 @@
handle @radar_offline { handle @radar_offline {
respond "Partner Radar is offline." 503 respond "Partner Radar is offline." 503
} }
@garage_offline vars garage_upstream yes
handle @garage_offline {
respond "The Garage admin UI (stpcore) is offline." 503
}
} }
} }
# The access log, and the request body on it. {http.request.body} buffers the # Bodies are buffered in memory to log them, so only small non-upload ones.
# body in memory to log it, so it is only taken when the client declared a
# length under 100 KB and the route is not an upload path: big and chunked
# bodies are logged without one. nginx did the equivalent: bodies over its
# 64k buffer went to a temp file and logged empty.
(logging) { (logging) {
log payloads log payloads
@small_body { @small_body {
# Up to five digits, spelt out because a {1,5} would read as a # Spelt out: {1,5} would parse as a placeholder.
# placeholder.
header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$ header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/* not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
} }
# `<` (early: taken before the request is proxied) must be explicit. # `<` must be explicit, or the body is logged a second time, empty.
# Without it 2.11 takes the body early as documented, but then takes it a
# second time after the proxy has read it, logging an empty string.
log_append @small_body <req_body {http.request.body} log_append @small_body <req_body {http.request.body}
} }
# Compression, for the types nginx's gzip_types listed. An explicit list so # Explicit types so streamed responses (ndjson, SSE, audio) are never buffered.
# that streamed responses (application/x-ndjson from /py/hotels/*, Dozzle's
# text/event-stream, icecast's audio) are never held back to fill a
# compression buffer.
(encode) { (encode) {
encode zstd gzip { encode zstd gzip {
minimum_length 256 minimum_length 256
@@ -359,35 +199,20 @@
import logging import logging
import errors import errors
import encode 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 { header {
-Server -Server
-Via -Via
} }
} }
# ---- Container healthcheck --------------------------------------------------- # ---- Container healthcheck (unlogged) ----------------------------------------
# The target of the healthcheck in docker-compose.yml, which the `autoheal`
# container acts on. Answered by Caddy itself, so it measures whether the
# server is serving and nothing upstream. Plain HTTP on :80, addressed by IP
# so it matches no real site; not logged, or it would put a line in the
# payload log every 30 s.
http://127.0.0.1 { http://127.0.0.1 {
respond /caddy-health 204 respond /caddy-health 204
respond 404 respond 404
} }
# ---- Uploads disk site ------------------------------------------------------- # ---- Uploads disk site (loopback only, unlogged) -----------------------------
# The shared `uploads` volume (mounted at /srv/uploads), served to this # private/ is refused here too, in case the gated route is ever reordered.
# container only (bound to the loopback; nothing publishes 2080). Reached by
# `uploads_disk` when Garage has no copy of a file; see that snippet for why
# it is a site of its own. Unlogged: the request was logged as it arrived.
#
# private/ is refused here as well as gated upstream. A request is routed by
# its cleaned, lower-cased path, so anything that could reach private/ goes to
# the gated /uploads/private/ route long before this; the refusal is the
# second lock, should that route ever be reordered.
http://:2080 { http://:2080 {
bind 127.0.0.1 bind 127.0.0.1
@private path /uploads/private /uploads/private/* @private path /uploads/private /uploads/private/*
+7 -41
View File
@@ -1,37 +1,8 @@
# ============================================================================= # Caddy plus the Cloudflare DNS and rate-limit plugins. caddy-ratelimit is
# caddy image — the public edge. Caddy with two plugins, plus this # pinned to a commit (no usable release), so Renovate leaves it; bump by hand.
# directory's config, checked while the image is built. # Builder and runtime tags move together.
# # The last RUN validates the config for both modes, so a bad config fails the
# WHY A CUSTOM BUILD # build before any running container is replaced.
# Stock Caddy has neither of these, and the config needs both:
# caddy-dns/cloudflare DNS-01 certificates through the Cloudflare API
# (sites/prod.caddy), since the router forwards
# nothing to obtain them over HTTP.
# mholt/caddy-ratelimit the `rate_limit` directive (the `limit` snippet
# in the Caddyfile).
# xcaddy compiles them in. The cloudflare plugin is pinned to a release;
# caddy-ratelimit has had one tagged release (v0.1.0, 2024) and is pinned
# to a commit, so Renovate leaves it alone and it is bumped by hand.
#
# BASE: caddy:2.11.9, the builder and the runtime from the same release
# (the builder's xcaddy builds the CADDY_VERSION its image sets). Both
# tags are bumped together. Official images are multi-arch.
#
# THE CONFIG IS VALIDATED AT BUILD TIME
# The last RUN parses and provisions the config with `caddy validate`, for
# the production sites and the dev ones, against placeholder values for
# every variable the config reads. A config that would not load therefore
# fails the image build, and a failed build aborts `docker compose up
# --build` BEFORE any container is replaced, so the running edge keeps
# serving. `make check-caddy` is the same build. The placeholders exist
# only for that RUN; the real values come from the container's
# environment (docker-compose.yml).
#
# NO ENTRYPOINT. The base image's CMD runs
# `caddy run --config /etc/caddy/Caddyfile --adapter caddyfile`, which is all
# that is needed: Caddy reads the environment itself, and obtains and renews
# its own certificates.
# =============================================================================
FROM caddy:2.11.9-builder AS builder FROM caddy:2.11.9-builder AS builder
RUN xcaddy build \ RUN xcaddy build \
--with github.com/caddy-dns/[email protected] \ --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 --from=builder /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile routes.caddy /etc/caddy/ COPY Caddyfile routes.caddy /etc/caddy/
COPY sites/ /etc/caddy/sites/ COPY sites/ /etc/caddy/sites/
# Mount points (docker-compose.yml). Created so Caddy still starts without # A log directory that can't be opened stops the config loading.
# them: the log directory especially, since a log file that cannot be opened
# stops the config loading.
RUN mkdir -p /var/log/caddy /srv/www /srv/uploads 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; \ RUN set -e; \
for site in prod dev; do \ for site in prod dev; do \
echo "caddy validate (CADDY_SITE=$site)"; \ echo "caddy validate (CADDY_SITE=$site)"; \
@@ -56,10 +22,10 @@ RUN set -e; \
BACKEND_HOST=backend BACKEND_PORT=8080 BACKEND_ENDPOINT=/api \ BACKEND_HOST=backend BACKEND_PORT=8080 BACKEND_ENDPOINT=/api \
ICECAST_HOST=icecast2 ICECAST_PORT=8000 \ ICECAST_HOST=icecast2 ICECAST_PORT=8000 \
GITEA_HOST=gitea GITEA_PORT=3000 \ GITEA_HOST=gitea GITEA_PORT=3000 \
SILVERBULLET_HOST=silverbullet SILVERBULLET_PORT=3000 \
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_PORT=3000 \ SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_PORT=3000 \
PYTHON_HOST=python PYTHON_PORT=8000 \ PYTHON_HOST=python PYTHON_PORT=8000 \
RECEIPT_WEB_UPSTREAM=127.0.0.1:9 RECEIPT_WEB_TOKEN=validate \ RECEIPT_WEB_UPSTREAM=127.0.0.1:9 RECEIPT_WEB_TOKEN=validate \
STPPRIV_LAN_IP=192.0.2.1 \
CLOUDFLARE_DNS_API_TOKEN=validate-placeholder-token-0000000000000 \ CLOUDFLARE_DNS_API_TOKEN=validate-placeholder-token-0000000000000 \
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile; \ caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile; \
done; \ done; \
+38 -65
View File
@@ -1,49 +1,12 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# ============================================================================= # Probes the edge. ok/FAIL lines (privacy denials and gates) set the exit
# edge_test.sh — what the public edge does with a fixed set of requests. # status; show/hdr lines depend on data, so diff two runs instead.
# # caddy/edge_test.sh <www-origin> [curl options...]
# WHAT IT DOES # e.g. https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 (on stpvm)
# Sends each request below to the edge and prints one line per request # https://localhost -k (dev)
# (status and Location, or one response header). Two kinds of line: # Optional env: EDGE_APEX, EDGE_HTTP, EDGE_COOKIE (admin session),
# ok / FAIL the privacy boundary and the gates, which have a fixed right # EDGE_UPLOAD (an existing upload's name). Read-only: GETs plus one POST that
# answer: the /notes/ denials, /py/internal/, every gated # the edge refuses.
# prefix. Any FAIL makes the exit status 1.
# show / hdr everything else (redirects, headers, carve-outs, uploads),
# whose answer depends on the upstream's data. Compare two runs
# instead (below).
#
# USAGE
# caddy/edge_test.sh <base-url> [curl options...]
# base-url the www origin, e.g. https://www.example.com
# curl options added to every request: --resolve to reach a given
# container, -k for dev's internal CA.
# Environment, all optional:
# EDGE_APEX the apex origin (production only): adds the apex cases.
# EDGE_HTTP the plain-http apex origin (production only), e.g.
# http://example.com: adds the http -> https case.
# EDGE_COOKIE an admin session's Cookie header value: adds the
# signed-in cases (each gated prefix must then NOT redirect
# to the login).
# EDGE_UPLOAD the name of a file under /uploads/ that exists.
#
# On stpvm, pin the hostname to this machine, or curl goes out over the
# internet and back (and hangs):
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
# Dev stack:
# caddy/edge_test.sh https://localhost -k
#
# COMPARING TWO EDGES
# Run it against each and diff the output. This is how Caddy was checked
# against nginx before the 2026-11-17 cutover (Caddy on 8443 beside nginx),
# and how a big change to caddy/ can be checked against the running edge:
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >before.txt
# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >after.txt
# diff before.txt after.txt
# Every remaining difference should be one that was intended.
#
# NOTHING HERE WRITES. Every request is a GET, apart from one POST to
# /py/internal/, which never gets past the edge.
# =============================================================================
set -u set -u
if [ $# -lt 1 ]; then if [ $# -lt 1 ]; then
@@ -57,11 +20,7 @@ FAILED=0
# The www host, without scheme or port. # The www host, without scheme or port.
BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#') BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')
# "<status> <location>" for one request. Arguments after the URL are extra # "<status> <location>"; a redirect to www is shown as its path alone.
# curl options (method, headers, --path-as-is). A redirect to the www host is
# shown as its path alone: nginx sends an absolute Location built from its
# own port, Caddy a relative one, and either way the browser lands on the
# same page.
probe() { probe() {
local url=$1 out local url=$1 out
shift shift
@@ -146,37 +105,52 @@ must 404 - py-internal /py//internal/rowing/read --path-as-is -X POST
echo "# admin gate, signed out: must redirect to the login, with the original URI" echo "# admin gate, signed out: must redirect to the login, with the original URI"
for p in \ for p in \
/sb/ /sb/index.html /jobs/ /jobs/api/graphql /tracker/ /tracker/dashboard \ /tracker/ /tracker/dashboard \
/dozzle/ /garage/ /radio/admin/stats.xsl /uploads/private/x.png \ /dozzle/ /garage/ /radio/admin/stats.xsl /uploads/private/x.png; do
/gitea/adamf/web_server/commit/0000000 /gitea/adamf/web_server/src/commit/0000000/README.md \
/gitea/adamf/web_server/archive/main.tar.gz /gitea/adamf/web_server/compare/main...x \
/gitea/adamf/web_server/blame/commit/0000000/README.md \
"/jobs/leads?x=1"; do
must 302 "$LOGIN$p" gate "$p" must 302 "$LOGIN$p" gate "$p"
done done
must 302 "${LOGIN}/uploads/x/../private/x.png" gate /uploads/x/../private/x.png --path-as-is must 302 "${LOGIN}/uploads/x/../private/x.png" gate /uploads/x/../private/x.png --path-as-is
show gate "$BASE/SB/" show gate "$BASE/TRACKER/"
must 302 "${LOGIN}/receipt/" permission /receipt/ must 302 "${LOGIN}/receipt/" permission /receipt/
if [ -n "${EDGE_COOKIE:-}" ]; then if [ -n "${EDGE_COOKIE:-}" ]; then
echo "# admin gate, signed in: must be let through" echo "# admin gate, signed in: must be let through"
for p in /sb/ /jobs/ /tracker/ /dozzle/ /garage/ /radio/admin/stats.xsl \ for p in /tracker/ /dozzle/ /garage/ /radio/admin/stats.xsl \
/gitea/adamf/web_server/commit/0000000 /receipt/; do /receipt/; do
not_login gate "$p" -H "Cookie: $EDGE_COOKIE" not_login gate "$p" -H "Cookie: $EDGE_COOKIE"
done done
fi fi
echo "# carve-outs and public routes (status depends on the upstream)" echo "# carve-outs and public routes (status depends on the upstream)"
for p in /jobs/api/capture /jobs/job-capture.user.js /tracker/api/v1/events \ for p in /tracker/api/v1/events \
/tracker/tracker.user.js /tracker/readyz /usaco/ /notes/ /gitea/ \ /tracker/tracker.user.js /tracker/readyz /usaco/ /notes/ /radio/status.xsl \
/gitea/adamf/web_server/src/branch/main/README.md /radio/status.xsl \
/py/ /py/docs /api/ /api/me /; do /py/ /py/docs /api/ /api/me /; do
show public "$BASE$p" show public "$BASE$p"
done done
echo "# Gitea moved to git.<domain>: every /gitea/ URL must 301 there, prefix dropped"
GIT_HOST=${BASE#*://}
GIT="https://git.${GIT_HOST#www.}"
must 301 "$GIT/" gitea /gitea
must 301 "$GIT/" gitea /gitea/
must 301 "$GIT/adamf/stpweb/src/branch/main/README.md" gitea /gitea/adamf/stpweb/src/branch/main/README.md
must 301 "$GIT/adamf/stpweb.git/info/refs?service=git-upload-pack" gitea "/gitea/adamf/stpweb.git/info/refs?service=git-upload-pack"
must 301 "$GIT/adamf/stpweb/commit/0000000" gitea /gitea/adamf/stpweb/commit/0000000
echo "# the editor and job tracker are on stppriv: must 301 there, path kept"
PRIV="https://priv.${GIT_HOST#www.}"
for p in /sb/ /sb/index.html /SB/ /jobs/ /jobs/api/graphql "/jobs/leads?x=1" \
/jobs/api/capture /jobs/job-capture.user.js; do
must 301 "$PRIV$p" priv "$p"
done
must 301 "$PRIV/sb/" priv /sb
must 301 "$PRIV/jobs/" priv /jobs
must 301 "$PRIV/jobs/" priv /cv/jobs
must 301 "$PRIV/jobs/job-capture.user.js" priv /job-capture.user.js
echo "# bare prefixes and moved URLs" echo "# bare prefixes and moved URLs"
for p in /api /radio /dozzle /garage /gitea /notes /sb /py /jobs /usaco \ for p in /api /radio /dozzle /garage /notes /py /usaco \
/tracker /receipt /cv/jobs /cv/leads /job-capture.user.js "/gitea?x=1"; do /tracker /receipt /cv/leads "/gitea?x=1"; do
show redirect "$BASE$p" show redirect "$BASE$p"
done done
@@ -187,7 +161,6 @@ done
hdr "$BASE/" Content-Type Strict-Transport-Security X-Frame-Options \ hdr "$BASE/" Content-Type Strict-Transport-Security X-Frame-Options \
X-Content-Type-Options Referrer-Policy Content-Security-Policy Server X-Content-Type-Options Referrer-Policy Content-Security-Policy Server
hdr "$BASE/api/" Strict-Transport-Security X-Frame-Options Server hdr "$BASE/api/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/gitea/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/assets/does-not-exist.js" Cache-Control hdr "$BASE/assets/does-not-exist.js" Cache-Control
hdr "$BASE/img/stamps/mine.gif" Access-Control-Allow-Origin Cache-Control hdr "$BASE/img/stamps/mine.gif" Access-Control-Allow-Origin Cache-Control
+79 -233
View File
@@ -1,55 +1,10 @@
# ============================================================================= # The route table for both modes, imported inside a `route` block: the first
# routes.caddy — the PROXY ROUTE TABLE shared by production and dev. Add a new # matching handle wins, so denials go first and each carve-out precedes the
# proxied route HERE, once. # 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.
# WHO IMPORTS IT # A gated route that loses its gate import is open to the internet.
# sites/prod.caddy (the www site) and sites/dev.caddy, each inside a
# `route { ... }` block, followed by that site's own `/` handler (the built
# SPA in production, the Vite dev server in dev). Everything else that
# differs between the two (TLS, security headers, static-asset caching, the
# apex) is in the site files.
#
# ORDER IS LITERAL: THE FIRST MATCHING handle WINS
# Inside `route`, Caddy keeps directives in the order written, and `handle`
# blocks are mutually exclusive. So this file is read top to bottom like a
# firewall list: denials first, then the specific routes, each carve-out
# ahead of the gated prefix it is carved out of, then the catch-alls.
# (nginx's longest-prefix / regex-in-file-order / ^~ rules are gone.)
#
# HOW PATHS ARE MATCHED
# `path` matchers are case-insensitive and see the decoded, cleaned path
# (`..` resolved, `//` merged), so /SB/, /notes/a/../private/x or
# /uploads/%70rivate/x cannot slip past a rule. `path_regexp` sees the
# decoded, cleaned path too but is case-sensitive, hence `(?i)` where case
# matters. caddy/edge_test.sh checks these against the live edge.
#
# PATTERNS THAT REPEAT BELOW
# - `uri strip_prefix /x`: the public URL carries a prefix (/api, /radio,
# /gitea, /py, /tracker, /receipt) but the upstream serves from /. Apps
# told their own base path (SilverBullet, the job tracker, usaco, Dozzle,
# garage-webui) keep it.
# - `import proxy` in every reverse_proxy: the forwarding headers (see the
# snippet in Caddyfile).
# - `import limit <zone> ...`: see the snippet; DEPLOYMENT.md §6 for the
# numbers.
# - `import admin_gate` / `import permission_gate <key>`: the session check
# against the backend. Some of these services have no auth of their own,
# so a gated route that loses its import is open to the internet.
# - Upstream read timeouts are not set anywhere: Caddy has none by default,
# so a long hotel search, an email sync or a log tail is never cut off by
# the proxy. (Cloudflare still gives up on an origin that sends nothing
# for 100 s; see DEPLOYMENT.md.)
#
# Upstream names come from the environment ({$BACKEND_HOST} etc.; see the
# caddy service in docker-compose.yml). The job tracker, activity tracker,
# usaco, Dozzle and Garage containers have fixed names there, so they are
# written literally.
# =============================================================================
# Request bodies: 50 MB everywhere except garage-webui, which takes video # An inner limit cannot raise an outer one, so garage-webui's 2 GB is carved out here.
# uploads and sets its own 2 GB below. (An outer limit cannot be raised by an
# inner one, so the exception has to be carved out here.) The backend caps
# uploads at 10 MB itself; this is the ceiling for everything else.
@body_default not path /garage/* @body_default not path /garage/*
request_body @body_default { request_body @body_default {
max_size 50MB max_size 50MB
@@ -57,38 +12,16 @@ request_body @body_default {
# ---- Denials ----------------------------------------------------------------- # ---- Denials -----------------------------------------------------------------
# /py/internal/: routes the Go backend calls directly over app-network (the # Called by the backend over app-network only; spends paid Claude calls.
# rowing photo reader, which spends a paid Claude call and has no auth of its
# own). Never proxied. The Python side also refuses anything carrying the
# X-Real-IP / X-Forwarded-For headers `proxy` sets, as a second layer.
handle /py/internal/* { handle /py/internal/* {
respond 404 respond 404
} }
# PUBLIC notes viewer privacy boundary. /notes/ is a second, read-only # SB_SPACE_IGNORE only hides paths from listings, so these block direct
# SilverBullet over the vault /sb/ edits, and SB_SPACE_IGNORE only hides # fetches: private/ or templates/ at any depth, any dot-segment below the
# paths from its file LIST. Everything else serves them (all verified against # first (SilverBullet's own endpoints live at the first), and revisions.
# 2.11.0 with curl): # Keep the folder list in step with silverbullet-public's SB_SPACE_IGNORE.
# /notes/.fs/private/x.md raw file, straight off disk # 404, not 403, so a private path's existence isn't confirmed.
# /notes/private/x the page URL: the server pre-renders the
# note's content into the HTML shell
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
# version of every private note ever
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a private/
# folder at ANY depth, so the block must too.
#
# 1. private/ or templates/ as any path segment, page URL or /.fs/. (?i) so
# Private/ is caught; (/|$) so the folder itself matches.
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The first
# segment is exempt because that is where SilverBullet's own endpoints
# live (/.fs, /.config, /.client, /.events ...). Nothing the client
# legitimately loads has a dot-segment deeper than that.
# 3. Revisions are read from the vault's own .git, i.e. the full history of
# every file INCLUDING private/ and anything ever deleted.
# SB_REVISIONS=disabled already turns this off upstream; this is the
# second lock in case that env var is ever dropped.
# Keep the folder list in step with SB_SPACE_IGNORE on silverbullet-public.
# 404 rather than 403 so the response does not confirm a private path exists.
@notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$) @notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$)
handle @notes_private { handle @notes_private {
respond 404 respond 404
@@ -104,35 +37,28 @@ handle /notes/.revisions* {
} }
# ---- Bare prefixes and moved URLs ---------------------------------------------- # ---- Bare prefixes and moved URLs ----------------------------------------------
# So a user typing /gitea without the slash lands correctly. Exact paths: unlike # Exact paths, so /gitea-something is left to the SPA.
# nginx's prefix locations, /gitea-something is not caught and is left to the
# SPA (where an admin-created canvas page with that slug now works).
redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301 redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301
redir /radio /radio/ 301 redir /radio /radio/ 301
redir /dozzle /dozzle/ 301 redir /dozzle /dozzle/ 301
redir /garage /garage/ 301 redir /garage /garage/ 301
redir /gitea /gitea/ 301 redir /gitea https://git.{$DOMAIN}/ 301
redir /notes /notes/ 301 redir /notes /notes/ 301
redir /sb /sb/ 301 redir /sb https://priv.{$DOMAIN}/sb/ 301
redir /py /py/ 301 redir /py /py/ 301
redir /jobs /jobs/ 301 redir /jobs https://priv.{$DOMAIN}/jobs/ 301
redir /usaco /usaco/ 301 redir /usaco /usaco/ 301
redir /tracker /tracker/ 301 redir /tracker /tracker/ 301
redir /receipt /receipt/ 301 redir /receipt /receipt/ 301
# Where the job tracker used to be. The SPA routes were client-side, so these # Old job tracker URLs; the userscript's old @updateURL finds its update here.
# only catch bookmarks and typed URLs. The userscript's old @updateURL lands redir /cv/jobs https://priv.{$DOMAIN}/jobs/ 301
# on the third, which is how installed copies find version 2.0.0 and its new redir /cv/leads https://priv.{$DOMAIN}/jobs/leads 301
# API base. redir /job-capture.user.js https://priv.{$DOMAIN}/jobs/job-capture.user.js 301
redir /cv/jobs /jobs/ 301
redir /cv/leads /jobs/leads 301
redir /job-capture.user.js /jobs/job-capture.user.js 301
# ---- Backend API --------------------------------------------------------------- # ---- Backend API ---------------------------------------------------------------
# Live chat / activity feed websocket. Deliberately NOT rate limited: a # Not rate limited: a limit would only drop reconnect storms.
# websocket is one long-lived request, and a limit here would drop reconnect
# storms, not abuse.
handle {$BACKEND_ENDPOINT}/ws* { handle {$BACKEND_ENDPOINT}/ws* {
uri strip_prefix {$BACKEND_ENDPOINT} uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} { reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
@@ -140,7 +66,21 @@ handle {$BACKEND_ENDPOINT}/ws* {
} }
} }
# Brute-force defence on password auth, on top of the backend's own 5/min. # stppriv's admin_gate checks every one of its requests here from one LAN IP,
# so it would exhaust the per-IP api limit. Public traffic always arrives from
# cloudflared, so it can never match.
@stppriv_gate {
path {$BACKEND_ENDPOINT}/auth/validate-admin
remote_ip {$STPPRIV_LAN_IP}
}
handle @stppriv_gate {
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# On top of the backend's own 5/min.
handle {$BACKEND_ENDPOINT}/auth/login* { handle {$BACKEND_ENDPOINT}/auth/login* {
import limit login 5 1m import limit login 5 1m
uri strip_prefix {$BACKEND_ENDPOINT} uri strip_prefix {$BACKEND_ENDPOINT}
@@ -157,8 +97,7 @@ handle {$BACKEND_ENDPOINT}/uploads* {
} }
} }
# Tighter than the REST catch-all, because one GraphQL query can be # One GraphQL query can be arbitrarily expensive.
# arbitrarily expensive to resolve.
handle {$BACKEND_ENDPOINT}/graphql* { handle {$BACKEND_ENDPOINT}/graphql* {
import limit graphql 10 1s import limit graphql 10 1s
uri strip_prefix {$BACKEND_ENDPOINT} uri strip_prefix {$BACKEND_ENDPOINT}
@@ -177,11 +116,7 @@ handle {$BACKEND_ENDPOINT}/* {
# ---- Admin-gated services ------------------------------------------------------ # ---- Admin-gated services ------------------------------------------------------
# Dozzle: live view of every container's logs, including the `traffic` # Docker socket access is root on the host.
# container's request-body log. It reads the Docker socket, so it is
# effectively root on the host: admin only. DOZZLE_BASE=/dozzle makes it serve
# under the prefix itself. Its log tails are server-sent events, which Caddy
# streams without buffering.
handle /dozzle/* { handle /dozzle/* {
import admin_gate import admin_gate
reverse_proxy dozzle:8080 { reverse_proxy dozzle:8080 {
@@ -189,24 +124,27 @@ handle /dozzle/* {
} }
} }
# garage-webui: buckets, keys and a file browser for the Garage object store. # garage-webui on stpcore, behind its Caddy, which wants X-Core-Token (header_up
# It holds Garage's admin token, so admin only, and its own login is left # replaces any client-sent one). Holds Garage's admin token. 2 GB for video
# unset (one login, not two). BASE_PATH=/garage makes it serve under the # uploads. A `route` so garage_upstream is set only after the gate passes.
# prefix. 2 GB so videos can be uploaded through it; the body streams through
# rather than landing on disk first.
handle /garage/* { handle /garage/* {
import admin_gate route {
request_body { import admin_gate
max_size 2GB request_body {
} max_size 2GB
reverse_proxy garage-webui:3909 { }
import proxy vars garage_upstream yes
reverse_proxy garage:3909 {
import proxy
header_up X-Core-Token {env.GARAGE_WEBUI_TOKEN}
transport http {
dial_timeout 3s
}
}
} }
} }
# The icecast ADMIN UI is a full station-control surface (kick sources, change # Station-control UI guarded only by the icecast password.
# metadata) protected only by the icecast admin password. Ahead of /radio/*,
# so listener traffic (the mount, status.xsl) is untouched.
handle /radio/admin/* { handle /radio/admin/* {
import admin_gate import admin_gate
uri strip_prefix /radio uri strip_prefix /radio
@@ -215,32 +153,9 @@ handle /radio/admin/* {
} }
} }
# Gitea's history views and archives. A crawler swarm (129k requests from # The notes editor is on stppriv, behind its admin gate.
# 103k IPs over 2026-10-18/19, so per-IP rate limits are useless) walks every
# file at every commit, and those pages are the expensive ones: diffs, blame,
# tarballs. 89% of its requests were these shapes. People browsing the code
# use the branch views (src/branch/..., commits/branch/...), which stay
# public, so the CV's repo links still work. Gitea's own
# REQUIRE_SIGNIN_VIEW=expensive would also block src/branch, hence doing it
# here. Ahead of /gitea/*.
@gitea_history path_regexp ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/)
handle @gitea_history {
import admin_gate
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes. NO
# prefix strip: it is a PWA told its own base path via SB_URL_PREFIX=/sb, and
# builds its service-worker scope and asset URLs from it. Strip the prefix and
# the app loads a blank page with no error in the log.
handle /sb/* { handle /sb/* {
import admin_gate redir https://priv.{$DOMAIN}{uri} 301
reverse_proxy {$SILVERBULLET_HOST}:{$SILVERBULLET_PORT} {
import proxy
}
} }
# ---- Public services ----------------------------------------------------------- # ---- Public services -----------------------------------------------------------
@@ -252,27 +167,20 @@ handle /radio/* {
} }
} }
handle /gitea/* { # Gitea is at git.DOMAIN; the registry at /v2/ is still proxied (prod.caddy).
uri strip_prefix /gitea handle_path /gitea/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} { redir https://git.{$DOMAIN}{uri} 301
import proxy
}
} }
# The public notes viewer, behind the denials at the top of this file. No # No prefix strip (SB_URL_PREFIX=/notes).
# prefix strip, for the same reason as /sb/ (SB_URL_PREFIX=/notes).
handle /notes/* { handle /notes/* {
reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} { reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} {
import proxy import proxy
} }
} }
# /py/hotels/search[/stream] and /py/hotels/scan/stream: public, minutes-long # Minutes-long searches with one slot on the Python side, so the limit is
# upstream calls to Travelodge/TfL with a single search slot on the Python # really concurrency protection. flush_interval passes NDJSON lines straight on.
# side, so this zone is really concurrency protection. flush_interval -1
# passes each NDJSON progress line on as it arrives (chunked responses are
# flushed anyway; this makes it explicit). `encode` never touches
# application/x-ndjson.
@hotels path_regexp ^/py/hotels/(search|scan) @hotels path_regexp ^/py/hotels/(search|scan)
handle @hotels { handle @hotels {
import limit hotel_search 3 1m import limit hotel_search 3 1m
@@ -292,43 +200,15 @@ handle /py/* {
} }
# ---- Job tracker (/jobs/) ---- # ---- Job tracker (/jobs/) ----
# Its own container (the adamf/job-tracker repo), which serves its SPA and its # On stppriv. A 301 turns a POST into a GET, so capture clients must call
# API from the same prefix, NOT stripped: the app is built to live at /jobs/. # priv. directly.
# Gated like /sb/ (the app checks the session itself too), with two
# exceptions ahead of it that a session cookie can never reach:
# - the capture API, called by the userscript from job sites' origins with
# the capture bearer token rather than cookies; the app's
# CaptureTokenMiddleware guards it;
# - the userscript itself: userscript managers fetch its @updateURL without
# the session, and it holds no secrets (the token is entered after
# install).
handle /jobs/api/capture* {
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/job-capture.user.js {
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/* { handle /jobs/* {
import admin_gate redir https://priv.{$DOMAIN}{uri} 301
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
} }
# ---- USACO practice log (/usaco/) ---- # ---- USACO (/usaco/) ----
# Its own container (the usaco repo's site/), shaped like /jobs/: SPA and API # Not stripped, not gated: the app checks the session for admin edits. The
# under one prefix that is NOT stripped, and no gate, because most of it is # Gitea webhook arrives here, signed with USACO_WEBHOOK_SECRET.
# public and the app checks the session itself for the admin's edits. Gitea's
# push webhook does not come through here: it calls the container directly
# on the Docker network.
handle /usaco/* { handle /usaco/* {
import limit api 30 1s import limit api 30 1s
reverse_proxy usaco:8080 { reverse_proxy usaco:8080 {
@@ -337,15 +217,8 @@ handle /usaco/* {
} }
# ---- Activity tracker (/tracker/) ---- # ---- Activity tracker (/tracker/) ----
# Its own container (the adamf/ccp repo): an ingest API for device collectors, # The collector API (bearer keys) and the userscript bypass the gate.
# which send batches of events with a per-device bearer key, plus a dashboard # Collectors must use www: the apex 301 turns POSTs into GETs.
# and setup page. Gated like /sb/ (the app also checks the session itself),
# with two exceptions ahead of it: the API, which collectors call with bearer
# keys and no cookies (the app guards each route, by device key, admin
# session or either), and the public userscript. Unlike /jobs/ the prefix IS
# stripped: the server serves /api/v1/... and /readyz from /. Collectors must
# use the www host: the apex 301 would turn their POSTs into GETs. Health Auto
# Export bodies can be several MB; the 50 MB default above covers them.
handle /tracker/api/v1/* { handle /tracker/api/v1/* {
import limit api 30 1s import limit api 30 1s
uri strip_prefix /tracker uri strip_prefix /tracker
@@ -371,21 +244,10 @@ handle /tracker/* {
} }
# ---- Receipt printer (/receipt/) ---- # ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi (not in # Runs on stppi (it is on the printer's LAN), reached over Tailscale.
# this stack: that machine reaches the printer on the home LAN), reached over # header_up replaces any client-sent X-Receipt-Token. A `route` so the
# Tailscale by IP. A page for printing a note or an uploaded image, plus its # receipt_upstream var is set only after the gate passes, so a backend outage
# API. Behind the permission gate on `receipt`, so an account granted it in # is not reported as "printer offline". 17 MB: 16 MB uploads plus framing.
# the admin panel can print without being an admin; the prefix IS stripped.
# The server trusts nothing without X-Receipt-Token, which only this proxy
# adds (header_up replaces any copy the client sent), and is told who is
# printing in X-Remote-User, which the gate sets.
#
# A `route`, so the steps run in the order written: receipt_upstream is set
# only after the gate has passed, so `errors` reports "printer offline" for a
# failed dial to stppi and not for a backend outage during the auth check.
# Its own zone, not `api`: a zone name must always carry the same numbers.
# 17 MB: the server caps uploads at 16 MB, plus room for the multipart
# framing around one.
handle /receipt/* { handle /receipt/* {
route { route {
import limit receipt 10 1s import limit receipt 10 1s
@@ -398,8 +260,7 @@ handle /receipt/* {
reverse_proxy {$RECEIPT_WEB_UPSTREAM} { reverse_proxy {$RECEIPT_WEB_UPSTREAM} {
import proxy import proxy
header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN} header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN}
# Caddy's default, spelt out: when stppi is off, fail fast and # Fail fast when stppi is off.
# let `errors` answer.
transport http { transport http {
dial_timeout 3s dial_timeout 3s
} }
@@ -409,10 +270,7 @@ handle /receipt/* {
# ---- Uploads (/uploads/) ---- # ---- Uploads (/uploads/) ----
# PRIVATE attachments (admin-only): files on *private* chat messages, which # Private chat attachments, always on disk. Must precede /uploads/*.
# the backend always writes to disk, at uploads/private/. Ahead of the public
# route below, and matched on the cleaned, lower-cased path, so no spelling of
# a path into private/ reaches the ungated one.
handle /uploads/private/* { handle /uploads/private/* {
import admin_gate import admin_gate
import upload_headers import upload_headers
@@ -420,20 +278,8 @@ handle /uploads/private/* {
file_server file_server
} }
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the Garage # Garage (on stpcore) first, disk second: a 404, 5xx or dial error falls back
# bucket's website endpoint, which serves the bucket anonymously and picks it # to the volume, so the bucket is the source of truth.
# by the Host header (garage/garage.toml: s3_web). The bucket is reachable
# only over app-network, so this is the only public way in. If Garage has no
# such file (404), errors (5xx), or cannot be reached at all (a dial error,
# caught by `errors` through the uploads_fallback variable), the file is
# served from the shared `uploads` volume instead (`uploads_disk`). That
# volume holds uploads from before Garage and anything the backend wrote
# there because Garage refused it (backend/services/uploads.go). So the bucket
# is the source of truth (deleting a file in garage-webui unpublishes it
# unless a disk copy exists), while a Garage outage only costs files that are
# nowhere else. dial_timeout 2s: Garage is on the same bridge, so a slow
# connect means it is down; fall back quickly. Range requests pass through
# either way, so video seeks.
handle /uploads/* { handle /uploads/* {
import upload_headers import upload_headers
vars uploads_fallback yes vars uploads_fallback yes
+3 -19
View File
@@ -1,22 +1,6 @@
# ============================================================================= # Dev (CADDY_SITE=dev): `/` goes to Vite, http and https both serve without
# sites/dev.caddy — LOCAL DEVELOPMENT sites. Imported by the Caddyfile when # redirects (listing the http:// addresses disables Caddy's), `tls internal`,
# CADDY_SITE=dev, which only docker-compose.dev.yml sets. # and no security headers or asset caching.
#
# HOW IT DIFFERS FROM sites/prod.caddy
# - `/` is proxied to the Vite dev server at vue:5173 instead of serving the
# built SPA. Its HMR websocket needs nothing extra.
# - http AND https both serve the full site, with no redirects, so
# http://localhost just works. Listing the http:// addresses is what
# stops Caddy adding its automatic http -> https redirect.
# - TLS is `tls internal`: a certificate from Caddy's own local CA, kept in
# ./caddy/data. Browsers warn until that CA is trusted, which is expected.
# - No security headers: HSTS on localhost would poison the browser for
# every other localhost project on the machine.
# - No static-asset caching: Vite serves those, and long cache lifetimes
# would defeat hot reload.
# Everything else, every proxied route, gate, denial and rate limit, is the
# same routes.caddy as production.
# =============================================================================
http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} { http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} {
tls internal tls internal
+17 -67
View File
@@ -1,30 +1,8 @@
# ============================================================================= # Production. The apex serves only the registry and otherwise redirects, so
# sites/prod.caddy — PRODUCTION sites. Imported by the Caddyfile unless # www is the one origin cookies and CORS assume.
# CADDY_SITE says otherwise. # 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
# FOUR SITES # fail the zone lookup ("expected 1 zone, got 0").
# 1. http:// apex + www -> 301 to https://www.DOMAIN.
# 2. https:// apex -> Gitea's registry at /v2/, else 301 to www, so
# there is exactly one canonical origin (cookies,
# CORS and the SPA all assume www).
# 3. https:// www -> the real site.
# (4. the healthcheck site, http://127.0.0.1, is in the Caddyfile.)
#
# CERTIFICATES
# Caddy obtains one for each name over DNS-01 through the Cloudflare API
# (`prod_tls`), keeps them in /data (./caddy/data on the host), and renews
# each when a third of its lifetime is left, in-process, with no reload.
# DNS-01 because the router forwards nothing: behind the tunnel no ACME
# server can reach :80 or :443. The token needs Zone -> Zone -> Read and
# Zone -> DNS -> Edit on this zone; see .env.example. Until the first
# certificate arrives (about a minute on a fresh ./caddy/data) the TLS
# handshake fails, so the tunnel, which verifies it, serves 502s.
#
# resolvers: on app-network, DOMAIN is a network alias for this very
# container, so Docker's DNS would answer the plugin's zone lookup itself
# and the order fails with "expected 1 zone, got 0". Asking Cloudflare's
# public resolvers sees the real zone.
# =============================================================================
(prod_tls) { (prod_tls) {
tls { tls {
@@ -33,8 +11,7 @@
} }
} }
# Spelt out rather than left to Caddy's automatic redirect, which goes to the # Explicit so http://apex is one hop to www, not two.
# same host: http://apex would then take two hops (https://apex, then www).
http://{$DOMAIN}, http://www.{$DOMAIN} { http://{$DOMAIN}, http://www.{$DOMAIN} {
import logging import logging
header -Server header -Server
@@ -47,15 +24,9 @@ http://{$DOMAIN}, http://www.{$DOMAIN} {
header Strict-Transport-Security "max-age=63072000; includeSubDomains" header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route { route {
# Gitea's container registry, which publishes images such as # Docker clients expect /v2/ (and Gitea's token endpoint) at the apex root
# DOMAIN/adamf/job-tracker. Docker always talks to /v2/ at the root of # and don't all follow redirects on blob uploads. No body limit: layers
# the host, whatever Gitea's ROOT_URL says, and Gitea advertises its # are large and stream through.
# token endpoint at https://DOMAIN/v2/token: on the apex, not under
# /gitea/ and not on www. So the apex serves /v2/ itself rather than
# redirecting it; a redirect on a blob upload is not something every
# Docker client follows. No request_body limit (routes.caddy's 50 MB
# is not imported here): image layers are far larger, and Caddy
# streams them to Gitea as they arrive.
handle /v2/* { handle /v2/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} { reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy import proxy
@@ -72,13 +43,8 @@ www.{$DOMAIN} {
import security_headers import security_headers
# ---- Static asset caching ---- # ---- Static asset caching ----
# Each matcher also requires the file to exist (`file`), so only a real # `file` so a 404 for a not-yet-deployed hash is never cached as immutable.
# file is marked cacheable: a 404 for a hash the browser asks for before
# the new build lands must never be cached for a year as `immutable`.
# (nginx's add_header without `always` skipped error responses the same
# way.)
# Vite hashed assets: a new build has new names, so these never change.
@hashed { @hashed {
path /assets/* path /assets/*
file { file {
@@ -103,27 +69,20 @@ www.{$DOMAIN} {
} }
header @week Cache-Control "public, max-age=604800" header @week Cache-Control "public, max-age=604800"
# This GIF is a "web stamp" other people's sites hot-link, so it needs a # A hot-linked web stamp; public and uncredentialed, so `*` is safe.
# CORS header. It is a public, deliberately hot-linkable image and nothing
# here is credentialed, so `*` is safe.
header /img/stamps/mine.gif Access-Control-Allow-Origin "*" header /img/stamps/mine.gif Access-Control-Allow-Origin "*"
route { route {
import ../routes.caddy import ../routes.caddy
# Static directories: a missing file is a 404, never the SPA's # 404 rather than index.html, so a stale asset hash isn't served HTML.
# index.html. A stale page asking for an old asset hash then gets an
# honest error rather than HTML served as JavaScript.
@static path /assets/* /fonts/* /img/* /sound/* @static path /assets/* /fonts/* /img/* /sound/*
handle @static { handle @static {
root * /srv/www root * /srv/www
file_server file_server
} }
# The built SPA (the vue_dist volume). Serve the file if it exists, # SPA fallback so deep links work on refresh.
# otherwise hand index.html to the browser so Vue Router can resolve
# the path client-side: that is what makes deep links like /admin or
# a canvas page's /<slug> work on refresh.
handle { handle {
root * /srv/www root * /srv/www
try_files {path} {path}/ /index.html try_files {path} {path}/ /index.html
@@ -133,22 +92,13 @@ www.{$DOMAIN} {
} }
# ---- Partner Radar (radar.DOMAIN) ---- # ---- Partner Radar (radar.DOMAIN) ----
# The adamf/cto "Partner Radar" demo: its own docker compose project on this # The adamf/cto stack's own Caddy. A subdomain because the app assumes it owns
# host (`make stpvm` there), whose `web` container (its own Caddy, serving the # `/`. No gate (it has its own login) and no security_headers (it sends its
# React app and proxying its API) joins app-network as `radar-web`. A # own, and www's would block the app).
# subdomain, not a /radar/ path, because the app assumes it owns `/` and its
# session cookie then stays apart from www's.
#
# No admin gate: the app has its own login and accounts. No security_headers
# either: the app's Caddy sends its own, and www's CSP would block the React
# app. Two zones of its own (see DEPLOYMENT.md §6): `radar` on every request,
# and `radar_login` on top of it for the login endpoint. radar_upstream lets
# `errors` answer "offline" when the stack is down instead of a bare 502.
(radar_proxy) { (radar_proxy) {
reverse_proxy {$RADAR_UPSTREAM} { reverse_proxy {$RADAR_UPSTREAM} {
import proxy import proxy
# Caddy's default, spelt out: when the stack is down, fail fast and # Fail fast when the stack is down.
# let `errors` answer.
transport http { transport http {
dial_timeout 3s dial_timeout 3s
} }
+6 -64
View File
@@ -1,90 +1,32 @@
# ============================================================================= # Dev overrides, layered on docker-compose.yml. Serves http://localhost (and
# docker-compose.dev.yml — local development OVERRIDE layer. # https with Caddy's local CA).
#
# WHAT IT DOES
# This file is never used alone. It is merged on top of docker-compose.yml:
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
# Compose merges per-key: `environment` entries are added to (not replacing)
# the base ones, while `command` and `ports` are replaced wholesale. Anything
# not mentioned here keeps its production definition.
#
# WHAT CHANGES vs PRODUCTION
# - vue : one-shot `vite build` becomes the long-running Vite dev server
# with the source bind-mounted for hot reload.
# - backend : dev flags on, including database seeding.
# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy instead of
# the production sites: no redirects, no security headers, a
# certificate from Caddy's own local CA, `/` proxied to Vite.
# - python : uvicorn --reload with the app source bind-mounted.
# - cloudflared : disabled entirely.
#
# HOW TO REACH IT
# http://localhost (HTTPS also works on :443 with the local-CA certificate,
# which the browser will warn about — that is expected).
#
# NOT USED ON THE PI. The deploy workflow runs plain `docker compose up`.
# =============================================================================
services: services:
vue: vue:
# Replaces the one-shot `vite build`: the container now stays up serving
# 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
# The bare path is an ANONYMOUS-VOLUME MASK, not a typo. Binding # Masks the bind mount so the image's node_modules survive.
# ./vue over /app would otherwise hide the node_modules that were
# installed *inside* the image. Declaring it as an anonymous volume
# re-exposes the image's copy on top of the bind mount, so the
# `npm ci` result survives and the host does not need node_modules.
- /app/node_modules - /app/node_modules
environment: environment:
- NODE_ENV=development - NODE_ENV=development
backend: backend:
environment: environment:
# Spotify requires an exact redirect URI match, so dev needs its own # Spotify needs an exact redirect match, registered in the app.
# (and this localhost URI must be registered in the Spotify app).
- SPOTIFY_REDIRECT_URI=https://localhost/api/spotify/callback - SPOTIFY_REDIRECT_URI=https://localhost/api/spotify/callback
# GraphQL playground + introspection: convenient locally, and off in
# production so the schema is not published to the world.
- GQL_PLAYGROUND=true - GQL_PLAYGROUND=true
- GQL_INTROSPECTION=true - GQL_INTROSPECTION=true
- DEV_MODE=true - DEV_MODE=true
# SEED_DB=true makes the backend populate the database with test # Dev only: seeds an admin with a known password.
# posts/users/messages on startup (services/ seeding). Safe here
# because dev uses a throwaway local dbdata volume; it is NEVER set
# in production — seeding a live database would inject fake content.
- SEED_DB=true - SEED_DB=true
caddy: caddy:
environment: environment:
# The single switch that loads caddy/sites/dev.caddy instead of
# the production sites: localhost on http and https, `tls
# internal`, `/` -> Vite.
- CADDY_SITE=dev - CADDY_SITE=dev
python: python:
# Same command as the Dockerfile's CMD plus --reload, paired with the
# source bind mount below so editing python/app/ restarts uvicorn.
# ${PYTHON_PORT} here is interpolated by the compose CLI from ./.env,
# not by the container's shell.
command: ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PYTHON_PORT:-8000} --root-path /py --reload"] command: ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PYTHON_PORT:-8000} --root-path /py --reload"]
volumes: volumes:
- ./python/app:/app/app - ./python/app:/app/app
# The tracker's image ships no hot reload; for that, run its own repo's
# `npm run dev`. Seeded like the backend, with the GraphQL playground at
# /jobs/api/graphql. Login still goes through the backend's seeded admin.
jobs:
environment:
- DEV_MODE=true
- SEED_DB=true
- GQL_PLAYGROUND=true
- GQL_INTROSPECTION=true
- MSGRAPH_REDIRECT_URI=https://localhost/jobs/api/email/callback
cloudflared: cloudflared:
# Profiles are opt-in: a service with a profile is only started when # Never start: a dev stack on the tunnel would get real visitors.
# that profile is explicitly requested. Nothing ever requests
# "disabled", so this is the idiomatic way to switch a service off in
# an override file. A dev stack must never join the production tunnel:
# Cloudflare would load-balance real visitors onto this machine's
# seeded database.
profiles: profiles:
- disabled - disabled
+84 -601
View File
@@ -1,105 +1,42 @@
# ============================================================================= # Production stack. Dev layers docker-compose.dev.yml on top.
# docker-compose.yml — production topology for the whole site. # Container names come from the *_HOST variables in .env, which Caddy also
# # uses for its upstreams, so the two always agree.
# WHAT IT DOES
# Defines every container, the single bridge network they share, and the # Pinned to the old folder name: the volumes and network are named after it.
# named volumes that survive restarts. This file alone IS production: name: web_server
# docker compose up --build
# Dev layers docker-compose.dev.yml on top of it (see that file).
#
# WHEN IT RUNS
# On the Raspberry Pi, via the Gitea Actions deploy workflow
# (.gitea/workflows/deploy.yaml) on every push to main, and by hand.
#
# ENV VARS
# Everything interpolated as ${VAR} below is read by the docker compose CLI
# from ./.env at the repo root (gitignored, and edited by hand on the host).
# Note the two distinct mechanisms:
# - ${VAR} in this file -> substituted by compose when parsing
# - `env_file: ./.env` -> the whole file injected into the container
# Many services need both: the container name comes from substitution, the
# app config from env_file.
#
# Required by this file: POSTGRES_{USER,PASSWORD,DB,PORT,HOST},
# POSTGRES_GITEA_DB, BACKEND_HOST,
# ICECAST_HOST, GITEA_HOST, OBSIDIAN_DIR, and the GITEA_*
# secrets. PYTHON_HOST/PYTHON_PORT/TFL_APP_KEY/LIQUIDSOAP_HARBOR_PORT have
# inline defaults.
#
# NAMING CONVENTION / WHY container_name IS SET FROM env
# Service discovery is by container name on app-network. Caddy builds its
# upstreams from the same ${*_HOST} variables (the caddy service's
# environment list), so naming the containers from .env keeps the proxy and
# the containers in sync from one source of truth. Renaming a *_HOST value
# renames the container AND repoints Caddy at it — do not change one without
# the other.
#
# WHAT IS PUBLISHED TO THE HOST
# Only caddy (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor
# port. Everything else is reachable only from inside app-network, which is
# why the backend, db, silverbullet and python have no `ports:` — they are
# deliberately not exposed and are reached through Caddy. Web traffic can
# also arrive through the `cloudflared` tunnel, which publishes nothing.
# =============================================================================
networks: networks:
# One flat bridge network; every service resolves every other by container # Subnet pinned so it cannot collide with the LAN.
# name via docker's embedded DNS at 127.0.0.11 (Caddy resolves an upstream
# through it each time it dials one). The subnet is pinned explicitly so it cannot collide
# with the Pi's LAN range or wander between compose versions.
app-network: app-network:
driver: bridge driver: bridge
ipam: ipam:
config: config:
- subnet: 172.28.0.0/16 - subnet: 172.28.0.0/16
# The usaco site's code runner and nothing else but the site. internal: # internal: code submitted to the usaco runner cannot reach the internet
# no route out, so code submitted to it cannot reach the internet, and # or anything on app-network.
# being off app-network keeps it away from postgres, gitea, garage and the
# backend. Docker picks the subnet; nothing here pins an address on it.
usaco-runner-net: usaco-runner-net:
driver: bridge driver: bridge
internal: true internal: true
# internal, and shared only with caddy: the admin gate is the only way in,
# since dozzle holds the Docker socket.
dozzle-net:
driver: bridge
internal: true
# PERSISTENT vs EPHEMERAL state # Named volumes survive `down`; only `down -v` deletes them.
# Named volumes below survive `docker compose down` and container rebuilds;
# they are only destroyed by `docker compose down -v` or an explicit
# `docker volume rm`. Bind mounts (./gitea/data, ./backend/token, ./logs,
# ./caddy/data) live in the repo checkout on the Pi and survive everything
# short of deleting the directory. Anything inside a container's own
# filesystem is ephemeral and gone on rebuild.
volumes: volumes:
# Postgres database — PERSISTENT. Holds the app DB *and* the Gitea DB. # Deleting this wipes posts, users and messages.
# Deleting this wipes posts, users, messages and every git repo's metadata.
dbdata: dbdata:
# File upload — PERSISTENT. Written by the backend at /backend/uploads, # Private attachments, plus any upload Garage refused. Caddy serves
# served read-only by Caddy at /uploads/. Shared so Caddy can serve user # /uploads/ from the bucket (on stpcore) first, then from here.
# uploads without proxying through the Go process. Since Garage, it holds
# private attachments (always), the uploads from before the bucket, and any
# upload the backend wrote here because Garage refused it. Caddy serves
# /uploads/ from the bucket first and only then from here.
uploads: uploads:
# Garage object store — PERSISTENT, both. garage_meta is the metadata DB # Written by the one-shot `vue` build container, served by Caddy.
# (buckets, keys, the object index, the cluster layout); garage_data is the
# object bytes. Lose meta and the bytes in data are unreadable, so back up
# the two together. A fresh pair needs garage/bootstrap.sh run once.
garage_meta:
garage_data:
# Vue build — EPHEMERAL in spirit but a named volume for handoff: the
# one-shot `vue` container writes the built SPA here and exits; Caddy mounts
# 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 # Named only so the image's VOLUME doesn't leave anonymous volumes behind.
# is needed across restarts (the Caddyfile is the source); named only so
# the image's VOLUME does not leave an anonymous volume behind on every
# recreate. The certificates are in ./caddy/data, not here.
caddy_config: caddy_config:
services: services:
# One-shot build container, NOT a long-running service. `vite build` writes # One-shot build: Exited (0) is the healthy state.
# the SPA into the shared vue_dist volume and the container exits 0. That
# exit is expected — `docker compose ps` showing vue as Exited is healthy.
# In dev this same service is overridden to run the Vite dev server instead
# (docker-compose.dev.yml) and does stay up.
vue: vue:
build: build:
context: ./vue context: ./vue
@@ -110,22 +47,10 @@ services:
networks: networks:
- app-network - app-network
# The only public entrypoint: Caddy (caddy/Caddyfile). Terminates TLS, # Explicit environment list so the edge never sees DB or JWT secrets; a
# serves the SPA, reverse-proxies everything else, and obtains and renews # variable the Caddyfile reads must be added here. Defaults live here, not
# its own certificates over DNS-01 into ./caddy/data, with no reload and no # in the Caddyfile, because Caddy's {$X:default} keeps a set-but-empty value.
# inbound port. It replaced nginx and the certbot container on 2026-11-17; # No depends_on: Caddy resolves upstreams per dial.
# both are in .deprecated/ (DEPLOYMENT.md §7 has the rollback).
#
# ENVIRONMENT: an explicit list, not the whole .env, so the edge never sees
# the database password or the JWT secret. A variable the Caddyfile reads
# must be added here, or it reaches Caddy empty. The ${X:-default} forms
# are the defaults nginx's entrypoint gave the optional services; they live
# here because Caddy's own {$X:default} keeps a variable that is set but
# empty, which is how a blank line in .env arrives.
#
# NO depends_on: Caddy resolves an upstream when it dials it, so it starts
# with any of them missing (502 until it appears), and there is no Vue
# build to wait for: the SPA is files in vue_dist, served as they appear.
caddy: caddy:
build: build:
context: ./caddy context: ./caddy
@@ -141,64 +66,45 @@ services:
- ICECAST_PORT=${ICECAST_PORT} - ICECAST_PORT=${ICECAST_PORT}
- GITEA_HOST=${GITEA_HOST} - GITEA_HOST=${GITEA_HOST}
- GITEA_PORT=${GITEA_PORT} - GITEA_PORT=${GITEA_PORT}
- SILVERBULLET_HOST=${SILVERBULLET_HOST:-silverbullet}
- SILVERBULLET_PORT=${SILVERBULLET_PORT:-3000}
- SILVERBULLET_PUBLIC_HOST=${SILVERBULLET_PUBLIC_HOST:-silverbullet-public} - SILVERBULLET_PUBLIC_HOST=${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}
- SILVERBULLET_PUBLIC_PORT=${SILVERBULLET_PUBLIC_PORT:-3000} - SILVERBULLET_PUBLIC_PORT=${SILVERBULLET_PUBLIC_PORT:-3000}
- PYTHON_HOST=${PYTHON_HOST:-python} - PYTHON_HOST=${PYTHON_HOST:-python}
- PYTHON_PORT=${PYTHON_PORT:-8000} - PYTHON_PORT=${PYTHON_PORT:-8000}
# A dead port by default, so /receipt/ reads "offline". # A dead port by default, so /receipt/ reads "offline".
- RECEIPT_WEB_UPSTREAM=${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9} - RECEIPT_WEB_UPSTREAM=${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}
- STPPRIV_LAN_IP=${STPPRIV_LAN_IP:-192.0.2.1}
- RECEIPT_WEB_TOKEN=${RECEIPT_WEB_TOKEN:-} - RECEIPT_WEB_TOKEN=${RECEIPT_WEB_TOKEN:-}
# Partner Radar (radar.DOMAIN): the adamf/cto stack's `web` container, - GARAGE_WEBUI_TOKEN=${GARAGE_WEBUI_TOKEN:-}
# which joins app-network under this alias (its docker-compose.stpvm.yml). # The adamf/cto stack's web container; "offline" while that stack is down.
# While that stack is down the name does not resolve and radar.DOMAIN
# answers "offline".
- RADAR_UPSTREAM=${RADAR_UPSTREAM:-radar-web:80} - RADAR_UPSTREAM=${RADAR_UPSTREAM:-radar-web:80}
# Zone -> Zone -> Read and Zone -> DNS -> Edit; see .env.example.
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-} - CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
# Keeps the Gitea hop on the LAN; public DNS points at Cloudflare.
# `garage` is on stpcore; the 127.0.0.1 default fails fast to disk.
extra_hosts:
- "${GITEA_HOST}:${GITEA_UPSTREAM}"
- "garage:${GARAGE_UPSTREAM:-127.0.0.1}"
networks: networks:
app-network: app-network:
# The site's public names, resolving to this container for everything # So cloudflared's origin (https://www.DOMAIN) lands here under a name
# on app-network. They exist for cloudflared: its tunnel origin is # the certificate covers.
# 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: aliases:
- ${DOMAIN} - ${DOMAIN}
- www.${DOMAIN} - www.${DOMAIN}
- radar.${DOMAIN} - radar.${DOMAIN}
# Fixed for cloudflared's extra_hosts (see there): an alias only # Matches cloudflared's extra_hosts.
# 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 ipv4_address: 172.28.255.251
dozzle-net:
ports: ports:
- 80:80 - 80:80
- 443:443 - 443:443
volumes: volumes:
# The certificates, their keys and the ACME account. PERSISTENT and # Private key material; never commit.
# private key material: gitignored, never commit. Losing it only costs
# a re-issue on the next start (seconds over DNS-01), during which the
# tunnel, which verifies the certificate, serves 502s.
- ./caddy/data:/data - ./caddy/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.
- vue_dist:/srv/www:ro - vue_dist:/srv/www:ro
# The JSON request-body log, kept on the host so it survives rebuilds
# and the `traffic` container can tail it. Caddy rotates it itself
# (50 MiB, five files kept).
- ./logs/caddy:/var/log/caddy - ./logs/caddy:/var/log/caddy
# restart: always only acts when the process exits. On 2026-10-19 nginx's # restart: always misses a hung server; autoheal restarts on unhealthy.
# 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
@@ -208,39 +114,19 @@ services:
labels: labels:
- autoheal=true - autoheal=true
# Cloudflare Tunnel: an OUTBOUND connection from here to Cloudflare's edge, # Remotely-managed Cloudflare Tunnel; routes live in the dashboard.
# which then forwards visitors' requests back down it to Caddy. Nothing is # Fixed IP because Caddy trusts CF-Connecting-IP from this address only.
# published to the host, so with the tunnel live the router's 80/443
# forwards can be closed. The tunnel is "remotely managed": its public
# hostnames and origin settings live in the Cloudflare dashboard, and this
# container only needs the token. The routing set up there (DEPLOYMENT.md,
# "Cloudflare Tunnel") is https://www.DOMAIN, which Caddy's network aliases
# resolve to Caddy itself, so the certificate verifies; Caddy's config,
# redirects and security headers apply to tunnel traffic exactly as to
# direct traffic, and both paths work side by side.
#
# Fixed address so Caddy can trust the CF-Connecting-IP header from this
# container and no other (trusted_proxies in caddy/Caddyfile). It sits
# at the top of the /16 because docker hands out dynamic addresses from the
# bottom; the two must change together.
#
# Disabled in dev via the `disabled` profile in docker-compose.dev.yml.
cloudflared: cloudflared:
image: cloudflare/cloudflared:2026.9.3 image: cloudflare/cloudflared:2026.9.3
container_name: cloudflared container_name: cloudflared
restart: always restart: always
command: ["tunnel", "--no-autoupdate", "run"] command: ["tunnel", "--no-autoupdate", "run"]
# Explicit, not env_file: the container only ever needs the token.
environment: environment:
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-} - TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
depends_on: depends_on:
- caddy - caddy
# Pins the tunnel origin's names to Caddy's fixed address. Its aliases # A stopped Caddy loses its aliases, and public DNS would loop the tunnel
# vanish while it is stopped (every deploy and the weekly maintenance), and # back to Cloudflare (error 1000). Pinning makes it a plain 502 instead.
# docker's DNS then forwards the name to public DNS, which answers with
# Cloudflare's own IPs: the tunnel sent requests back to the edge and
# visitors got error 1000. /etc/hosts wins over DNS, so a stopped Caddy is
# 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"
- "www.${DOMAIN}:172.28.255.251" - "www.${DOMAIN}:172.28.255.251"
@@ -255,43 +141,25 @@ services:
dockerfile: Dockerfile dockerfile: Dockerfile
container_name: "${BACKEND_HOST}" container_name: "${BACKEND_HOST}"
restart: always restart: always
# MAP form, not the list form used elsewhere: this waits for db's
# healthcheck to pass, not merely for its container to start. Without it
# the Go process raced Postgres on every boot, failed its first connection,
# died, and relied on `restart: always` to try again — noisy log churn and
# a slower cold start in practice.
# `restart: always` is deliberately KEPT as the backstop: if db's health
# probe were ever to stall past compose's patience, or the DB dropped out
# later, the restart policy still recovers the backend.
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
extra_hosts:
- "${GITEA_HOST}:${GITEA_UPSTREAM}"
- "garage:${GARAGE_UPSTREAM:-127.0.0.1}"
networks: networks:
- app-network - app-network
env_file: env_file:
- ./.env - ./.env
volumes: volumes:
# PERSISTENT, and the subtle one: the Spotify OAuth refresh token is # Spotify refresh token; without this every deploy forces a re-auth.
# written here as spotify_token.json. Without this bind mount the token
# would live in the container filesystem and be destroyed on every
# rebuild, forcing a manual re-authorisation of Spotify after each
# deploy. Gitignored (it is a credential).
- ./backend/token/:/backend/token - ./backend/token/:/backend/token
# The Obsidian vault on the host, read by the backend for the notes API. # Read-only: stppriv is the vault's only writer.
# Same directory is mounted read-write into silverbullet (the editor) and - ${OBSIDIAN_DIR}:/backend/notes:ro
# read-only into silverbullet-public (the /notes/ site).
- ${OBSIDIAN_DIR}:/backend/notes
- ./logs:/backend/logs - ./logs:/backend/logs
# 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;
# the backend reads them to report what is queued.
- ./icecast2/fallback_music:/backend/fallback_music - ./icecast2/fallback_music:/backend/fallback_music
# Reported to docker only: nothing acts on `unhealthy` since the autoheal # Informational only: autoheal does not watch this container.
# watchdog was retired (.deprecated/autoheal), so this just shows up in
# `docker ps`. `restart: always` covers a crashed process, not a hung one.
# start_period gives the Go process 10s to bind before failures start
# counting.
healthcheck: healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:8080/"] test: ["CMD", "wget", "-qO-", "http://localhost:8080/"]
interval: 30s interval: 30s
@@ -299,12 +167,7 @@ services:
retries: 3 retries: 3
start_period: 10s start_period: 10s
# Single Postgres instance serving TWO databases: ${POSTGRES_DB} for the Go # Holds the app DB plus the job and activity trackers' (created by hand).
# backend and ${POSTGRES_GITEA_DB} for Gitea. The postgres image only creates
# POSTGRES_DB on first init, so the Gitea database was created by hand once;
# a from-scratch restore must `createdb` it before Gitea will start.
# Schema for the app DB comes from GORM auto-migration at backend start —
# there are no migration files.
db: db:
image: postgres:16 image: postgres:16
container_name: "${POSTGRES_HOST}" container_name: "${POSTGRES_HOST}"
@@ -315,20 +178,8 @@ services:
- app-network - app-network
volumes: volumes:
- dbdata:/var/lib/postgresql/data - dbdata:/var/lib/postgresql/data
# Postgres is the one dependency the backend genuinely cannot start # Long start_period for cold first boots. $$ defers expansion to the
# without, so `backend` gates on this healthcheck (condition: # container's shell.
# service_healthy) instead of on mere container start.
# TUNED FOR SLOW ARM HARDWARE: on a Raspberry Pi with a cold page cache a
# first-boot Postgres can take well over a minute to finish initdb/recovery
# and accept connections. start_period is the grace window during which a
# failing probe does NOT count against `retries` and does NOT mark the
# container unhealthy, so 90s costs nothing on a warm boot and prevents a
# false "unhealthy" on a cold one. After that, 10 retries at 10s gives
# another ~100s before anything gives up. `pg_isready -U $POSTGRES_USER`
# is the cheapest real readiness probe (it does a protocol-level connect,
# not just a TCP open). Note $$POSTGRES_USER: the doubled $ escapes
# compose's own interpolation so the variable is expanded by the shell
# INSIDE the container, from env_file, at probe time.
healthcheck: healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\" -q"] test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\" -q"]
interval: 10s interval: 10s
@@ -336,18 +187,8 @@ services:
retries: 10 retries: 10
start_period: 90s start_period: 90s
# Internet radio: one container running BOTH icecast2 (the streaming server # icecast2 + liquidsoap. The harbor port is a raw live-DJ source input,
# listeners connect to, proxied at /radio/) and liquidsoap (the source that # so it is published directly rather than proxied.
# feeds it). See icecast2/entrypoint.sh.
#
# This is the only non-Caddy service that publishes a host port, and it has
# to: LIQUIDSOAP_HARBOR_PORT is the live-DJ input. A broadcasting client
# (e.g. butt) connects straight to the Pi on that port, by its Tailscale
# name now that the public domain resolves to Cloudflare, with the icecast
# source password and pre-empts the fallback playlist. It is NOT proxied
# through Caddy because it is a raw source protocol, not HTTP the SPA uses.
# Note the host:container mapping uses the same variable on both sides, so
# the published port always matches what liquidsoap actually binds.
icecast2: icecast2:
build: build:
context: ./icecast2 context: ./icecast2
@@ -363,76 +204,11 @@ services:
ports: ports:
- "${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. # Public read-only notes at /notes/. private/ stays private only with all
# Proxied at /sb/ behind Caddy's admin gate. The public site at /notes/ is # three: SB_SPACE_IGNORE (hides from listings, not direct fetches), Caddy's
# a SECOND, read-only SilverBullet over the same folder (silverbullet-public, # /notes/ deny regex (keep its folder list in step), and SB_REVISIONS
# below). # disabled (else history is served from the vault's .git).
# # Keep the image tag in step with the editor.
# SINGLE-SPACE MODE is auto-detected because the mounted folder is not empty
# (the alternative, multi-space, expects /data to be a SilverBullet-owned
# folder of spaces). In this mode it treats the mount as the space itself and
# writes NO database or metadata files into the vault — the folder stays a
# plain directory of markdown that Obsidian still understands.
silverbullet:
image: ghcr.io/silverbulletmd/silverbullet:2.11.0
container_name: "${SILVERBULLET_HOST:-silverbullet}"
restart: always
networks:
- app-network
environment:
SB_PORT: "${SILVERBULLET_PORT:-3000}"
# The app builds its service-worker scope and asset URLs from this, which
# is why Caddy must NOT strip the /sb/ prefix. See caddy/routes.caddy.
SB_URL_PREFIX: /sb
# Only .obsidian: it is editor config and plugin JS, not notes.
#
# Deliberately NOT silverbullet-public's list, which also hides private/
# and templates/. The two answer different questions: the public
# instance hides private/ because it must never be PUBLISHED, whereas
# this is the editor, reachable only through the admin gate, and hiding
# notes from it just stops you editing them.
#
# MUST be newline separated: a comma separated list is accepted silently
# and does nothing.
SB_SPACE_IGNORE: |
.obsidian
# Pinned rather than inferred from the mount's owner, so the files it
# writes match the vault's ownership on the host.
PUID: "1000"
PGID: "1000"
# Uncomment for a look-but-don't-touch first boot against a real vault:
# SB_READ_ONLY: "true"
volumes:
- ${OBSIDIAN_DIR}:/data
# The PUBLIC notes site at /notes/ (replaced Quartz): the same SilverBullet
# image in read-only mode over the same vault, with no auth. Visitors get the
# full client — navigation, backlinks, live queries — but cannot write.
# Edits made in the /sb/ editor show up here live, since both watch one folder.
#
# KEEPING private/ PRIVATE takes three layers, because none is enough alone:
# 1. SB_SPACE_IGNORE hides the paths from the file LIST, so they are
# never indexed, searched or shown. It does NOT stop
# a direct fetch of /.fs/private/x.md, nor the page
# URL /notes/private/x (server-rendered with the
# note's content), nor /.fs/.git/ — SilverBullet
# only applies it to listing (checked in 2.11.0).
# 2. Caddy deny rules 404 any private/ or templates/ segment and any
# nested dot-folder under /notes/; this is what
# actually closes those holes. Keep its folder list
# in step with the one below.
# 3. SB_REVISIONS the default ("unmanaged") serves history from the
# vault's own .git, i.e. every version of every file
# including private/ and deleted ones. Disabled here,
# and Caddy blocks /notes/.revisions as well.
#
# SB_READ_ONLY rejects writes server-side and also disables the shell and the
# /.proxy endpoint (otherwise an open fetch proxy). The :ro mount is a second
# lock on writes. It is flagged "legacy" upstream in favour of multi-space
# mode's per-space publish setting, which cannot exclude a folder and would
# mean migrating the editor too — revisit if single-space mode is removed.
#
# Keep the image tag in lockstep with the editor above.
silverbullet-public: silverbullet-public:
image: ghcr.io/silverbulletmd/silverbullet:2.11.0 image: ghcr.io/silverbulletmd/silverbullet:2.11.0
container_name: "${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}" container_name: "${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}"
@@ -441,14 +217,9 @@ 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: 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,
# so these match at any depth. Must match the folder list in the
# /notes/ deny regex in caddy/routes.caddy, or a new entry here is
# hidden from the list but still publicly fetchable.
SB_SPACE_IGNORE: | SB_SPACE_IGNORE: |
private/ private/
templates/ templates/
@@ -458,36 +229,26 @@ services:
volumes: volumes:
- ${OBSIDIAN_DIR}:/data:ro - ${OBSIDIAN_DIR}:/data:ro
# SilverBullet has no concept of git, so this commits and pushes what it # Pulls the vault (SYNC_MODE=pull: never commits or pushes). The editor and
# writes, and pulls what Obsidian pushes from elsewhere. # the only writer is on stppriv; two writers would conflict.
#
# WHY A SEPARATE CONTAINER and not SilverBullet's own shell backend: enabling
# that would give anyone who gets past Caddy's admin gate command execution
# inside the container. Since SilverBullet itself runs with no SB_USER, that
# gate is the only thing protecting it, so the blast radius stays here.
silverbullet-git: silverbullet-git:
image: alpine/git:v2.54.0 image: alpine/git:v2.54.0
container_name: "${SILVERBULLET_GIT_HOST:-silverbullet-git}" container_name: "${SILVERBULLET_GIT_HOST:-silverbullet-git}"
restart: always restart: always
networks: networks:
- app-network - app-network
# The vault's remotes are ssh://git@DOMAIN:2222/..., but Caddy's network # Gitea SSH on the LAN; public DNS points at Cloudflare.
# aliases make DOMAIN resolve to Caddy on app-network, which has no :2222,
# so every pull and push was refused. /etc/hosts wins over Docker's DNS, so
# this sends DOMAIN back to the host, where gitea publishes 2222. The name
# is unchanged, so known_hosts still matches.
extra_hosts: extra_hosts:
- "${DOMAIN}:host-gateway" - "${GITEA_HOST}:${GITEA_UPSTREAM}"
# Same uid SilverBullet writes as, so commits don't leave root-owned objects # Match SilverBullet's uid so .git objects stay host-owned.
# in .git that the host user can no longer clean up.
user: "1000:1000" user: "1000:1000"
environment: environment:
SYNC_MODE: pull
SYNC_INTERVAL: "${SILVERBULLET_GIT_INTERVAL:-300}" SYNC_INTERVAL: "${SILVERBULLET_GIT_INTERVAL:-300}"
GIT_AUTHOR_NAME: silverbullet GIT_AUTHOR_NAME: silverbullet
GIT_AUTHOR_EMAIL: "silverbullet@${DOMAIN}" GIT_AUTHOR_EMAIL: "silverbullet@${DOMAIN}"
GIT_COMMITTER_NAME: silverbullet GIT_COMMITTER_NAME: silverbullet
GIT_COMMITTER_EMAIL: "silverbullet@${DOMAIN}" GIT_COMMITTER_EMAIL: "silverbullet@${DOMAIN}"
# uid 1000 has no home in this image; give git somewhere writable.
HOME: /tmp HOME: /tmp
GIT_SSH_COMMAND: "ssh -i /ssh/id_ed25519 -o UserKnownHostsFile=/ssh/known_hosts -o IdentitiesOnly=yes" GIT_SSH_COMMAND: "ssh -i /ssh/id_ed25519 -o UserKnownHostsFile=/ssh/known_hosts -o IdentitiesOnly=yes"
entrypoint: ["/bin/sh", "/git-sync.sh"] entrypoint: ["/bin/sh", "/git-sync.sh"]
@@ -495,19 +256,9 @@ services:
- ${OBSIDIAN_DIR}:/space - ${OBSIDIAN_DIR}:/space
- ./silverbullet/git-sync.sh:/git-sync.sh:ro - ./silverbullet/git-sync.sh:/git-sync.sh:ro
- ./silverbullet/ssh:/ssh:ro - ./silverbullet/ssh:/ssh:ro
# 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 Caddy. # Mounted at /py/ (prefix stripped). Explicit env list: no DB or other secrets.
# ROOT_PATH=/py tells FastAPI it is mounted under a prefix so the generated
# OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own
# routes are written relative to /.
# Note this service uses `environment:` with an explicit allow-list rather
# than `env_file: ./.env` — it only gets the variables it needs and never
# sees the database password, Spotify secrets, or the other API keys.
# CLAUDE_API_KEY is the one secret on the list: the rowing photo reader
# (POST /internal/rowing/read, called by the backend, blocked at Caddy)
# makes its Claude call here.
python: python:
build: build:
context: ./python context: ./python
@@ -529,92 +280,19 @@ services:
retries: 3 retries: 3
start_period: 10s start_period: 10s
# The job application tracker, served at /jobs/. Built and published by its # USACO log (adamf/usaco). Git is its store, cloned into ./usaco-data
# own repo (adamf/job-tracker on this Gitea), whose README covers the # (must be uid 1000). The S3_* vars are all-or-nothing, hence the :+ forms.
# first-time database setup and the cutover from the old in-backend tracker. # stop_grace_period must exceed the app's SHUTDOWN_GRACE (5m).
#
# Like python, it gets an explicit `environment:` list rather than the whole
# .env: it never sees the site's database password or JWT secret, and has a
# database role of its own. A variable the tracker reads must be added to
# the list below as well as .env.example.
#
# It has no login. Caddy's admin gate gates /jobs/ like /sb/ (except the
# bearer-token capture API and the userscript), and the tracker checks
# again itself: AUTH_VALIDATE_URL is the backend's validate-admin route
# (the one Caddy's admin gate uses), which it asks with the visitor's
# cookies on each admin request.
#
# ./jobs-data holds the Microsoft Graph session and the capture token. The
# image runs as uid 1000, so the directory must be owned by it.
jobs:
image: adam-french.co.uk/adamf/job-tracker:${JOBS_IMAGE_TAG:-latest}
container_name: jobs
restart: always
depends_on:
db:
condition: service_healthy
networks:
- app-network
environment:
- DATABASE_URL=postgres://${POSTGRES_JOBS_USER:-jobs}:${POSTGRES_JOBS_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_JOBS_DB:-jobs}?sslmode=disable
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
- CLAUDE_API_KEY=${CLAUDE_API_KEY:-}
- CLAUDE_MODEL=${CLAUDE_MODEL:-}
- EMAIL_BACKEND=${EMAIL_BACKEND:-}
- EMAIL_SYNC_ENABLED=${EMAIL_SYNC_ENABLED:-}
- EMAIL_SYNC_INTERVAL=${EMAIL_SYNC_INTERVAL:-}
- MSGRAPH_CLIENT_ID=${MSGRAPH_CLIENT_ID:-}
- MSGRAPH_CLIENT_SECRET=${MSGRAPH_CLIENT_SECRET:-}
- MSGRAPH_TENANT_ID=${MSGRAPH_TENANT_ID:-}
- MSGRAPH_REDIRECT_URI=${MSGRAPH_REDIRECT_URI:-}
- IMAP_HOST=${IMAP_HOST:-}
- IMAP_PORT=${IMAP_PORT:-}
- IMAP_EMAIL=${IMAP_EMAIL:-}
- IMAP_PASSWORD=${IMAP_PASSWORD:-}
- JOB_LEADS_ENABLED=${JOB_LEADS_ENABLED:-}
- JOB_LEADS_INTERVAL=${JOB_LEADS_INTERVAL:-}
- ADZUNA_APP_ID=${ADZUNA_APP_ID:-}
- ADZUNA_APP_KEY=${ADZUNA_APP_KEY:-}
- REED_API_KEY=${REED_API_KEY:-}
volumes:
- ./jobs-data:/data
# The USACO practice log, served at /usaco/. Built and published by the
# usaco repo's CI (adamf/usaco on this Gitea; the server is in its site/
# directory), which pulls :latest into this service on every push to main
# that touches the site. Pin USACO_IMAGE_TAG to hold a version.
#
# It has no database: git is its store. It keeps a clone of adamf/usaco in
# ./usaco-data, pulled over the Docker network when Gitea's push webhook
# fires (USACO_WEBHOOK_SECRET signs it), and commits the admin's edits
# (status, link, notes, statement, explanations) back with USACO_GIT_TOKEN.
# CLAUDE_API_KEY powers the admin's Explain button (USACO_CLAUDE_MODEL picks
# the model; blank is claude-opus-5-5). Recording reviews also need
# USACO_OPENAI_API_KEY to transcribe, and keep the audio in Garage's
# private usaco-audio bucket when USACO_S3_* is set (the site refuses to
# start with only some S3_* set, so all five go together or not at all:
# the blank-key case blanks the rest). USACO_CLAUDE_MONTHLY_BUDGET (dollars,
# blank for none) stops new Claude jobs once a month's estimated spend
# reaches it. ./usaco-data holds that clone, the background jobs' records
# and the Claude spend ledger; deleting it is safe (it re-clones) but loses
# any answer not yet committed. The image runs as uid 1000, so the
# directory must be owned by it.
#
# On stop it lets running Claude jobs finish for up to SHUTDOWN_GRACE (5m
# by default) before exiting, so stop_grace_period must be longer than
# that, or Docker kills it mid-job.
#
# Same explicit `environment:` list as jobs. Like the tracker it has no
# login: visitors see solved problems, and AUTH_VALIDATE_URL decides who
# is the admin from the visitor's cookies.
usaco: usaco:
image: adam-french.co.uk/adamf/usaco:${USACO_IMAGE_TAG:-latest} image: adam-french.co.uk/adamf/usaco:${USACO_IMAGE_TAG:-latest}
container_name: usaco container_name: usaco
restart: always restart: always
stop_grace_period: 6m stop_grace_period: 6m
depends_on: depends_on:
- gitea
- usaco-runner - usaco-runner
extra_hosts:
- "${GITEA_HOST}:${GITEA_UPSTREAM}"
- "garage:${GARAGE_UPSTREAM:-127.0.0.1}"
networks: networks:
- app-network - app-network
- usaco-runner-net - usaco-runner-net
@@ -636,27 +314,9 @@ services:
volumes: volumes:
- ./usaco-data:/data - ./usaco-data:/data
# The usaco site's code runner (site/Dockerfile.runner in adamf/usaco): # Runs submitted code: no secrets, no network but the site's.
# compiles and runs solutions against their tests, and lints them, for the # tmpfs must allow exec (compiled programs run there). pids_limit is the
# admin's solve page. It runs submitted code, so it has no secrets (no # fork-bomb guard, since the runner can't use RLIMIT_NPROC.
# environment at all) and is only on usaco-runner-net, which is internal:
# no internet, and nothing but the site can reach it. Published by
# adamf/usaco's CI, which rolls it before `usaco`; pin
# USACO_RUNNER_IMAGE_TAG to hold a version.
#
# The hardening is the point:
# read_only the image is not writable; only /tmp is
# tmpfs /tmp one directory per request, removed after. Must NOT be
# noexec: the compiled program runs from it. Its pages count
# against mem_limit.
# mem_limit, cpus
# on top of the runner's own per-program limits (512 MB
# address space, CPU time, 64 MB files, wall clock)
# pids_limit what stops a fork bomb: the runner does not set
# RLIMIT_NPROC (it counts the whole uid, the server's own
# threads included). The image's tini reaps the leftovers.
# cap_drop, no-new-privileges
# the runner needs no capabilities, and runs as uid 1000
usaco-runner: usaco-runner:
image: adam-french.co.uk/adamf/usaco-runner:${USACO_RUNNER_IMAGE_TAG:-latest} image: adam-french.co.uk/adamf/usaco-runner:${USACO_RUNNER_IMAGE_TAG:-latest}
container_name: usaco-runner container_name: usaco-runner
@@ -674,22 +334,7 @@ services:
security_opt: security_opt:
- no-new-privileges:true - no-new-privileges:true
# The activity tracker (time spent per app, site, walk...), served at # Activity tracker (adamf/ccp), at /tracker/ (prefix stripped).
# /tracker/ with the prefix stripped. Built and published by its own repo
# (adamf/ccp on this Gitea), whose CI pulls :latest into this service on
# every push to main; pin ACTIVITY_TRACKER_IMAGE_TAG to hold a version.
#
# Same shape as jobs: an explicit `environment:` list and a database role of
# its own, created by hand once (the ccp README has the command). It applies
# its own migrations on start. No state outside Postgres.
#
# Two kinds of auth. Collectors send per-device bearer keys, made on the
# tracker's /tracker/setup page or with `docker exec activity-tracker
# tracker apikey create`. The dashboard and setup pages have no login of
# their own: Caddy's admin gate gates them like /sb/ (everything but
# /tracker/api/v1/ and the userscript), and like jobs the tracker also asks
# AUTH_VALIDATE_URL (the backend's validate-admin) with the visitor's
# cookies and sends anyone else to /admin/login.
activity-tracker: activity-tracker:
image: adam-french.co.uk/adamf/activity-tracker:${ACTIVITY_TRACKER_IMAGE_TAG:-latest} image: adam-french.co.uk/adamf/activity-tracker:${ACTIVITY_TRACKER_IMAGE_TAG:-latest}
container_name: activity-tracker container_name: activity-tracker
@@ -704,11 +349,7 @@ 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 Caddy's JSON request-body log to its own stdout, and does nothing # Tails Caddy's payload log so Dozzle shows it as its own stream.
# else. It exists so Dozzle shows the payloads as a stream of their own,
# rendered as JSON fields, instead of interleaved with Caddy's compact access
# log and error output. -F re-opens the file after rotation; -n0 skips the
# backlog on restart, which stays in the file on the host.
traffic: traffic:
image: busybox:1.38.0 image: busybox:1.38.0
container_name: traffic container_name: traffic
@@ -718,43 +359,23 @@ services:
volumes: volumes:
- ./logs/caddy:/logs:ro - ./logs/caddy:/logs:ro
# Dozzle: a live, searchable web view of every container's logs, served at # The Docker socket is root-equivalent even :ro, so: no published port,
# /dozzle/ behind the admin login (caddy/routes.caddy). The # admin gate in front, container actions left off.
# `traffic` container is the one to watch for incoming request bodies.
#
# The Docker socket is mounted :ro, but that only stops the file being
# replaced — the API behind it is still fully usable, which is effectively
# root on the Pi. Hence: no published port, the admin auth_request in front,
# and container actions and shell left at their default of off.
dozzle: dozzle:
image: amir20/dozzle:v11.2.0 image: amir20/dozzle:v11.2.0
container_name: dozzle container_name: dozzle
restart: always restart: always
networks: networks:
- app-network - dozzle-net
environment: environment:
- DOZZLE_BASE=/dozzle - DOZZLE_BASE=/dozzle
- DOZZLE_NO_ANALYTICS=true - DOZZLE_NO_ANALYTICS=true
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
# Restarts any container labelled autoheal=true once Docker marks it # Restarts containers labelled autoheal=true when unhealthy.
# unhealthy, which Docker itself never does (restart policies only see the # Root via the socket, so: no network, and pinned by digest. To bump:
# process exit). Only caddy carries the label today; give it to another # `docker buildx imagetools inspect willfarrell/autoheal:<tag>`.
# 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
# the host, so it gets no network at all: nothing can reach it, and it
# reaches nothing but the socket. For the same reason the image is pinned BY
# DIGEST, never a tag, so a push to Docker Hub cannot gain root here at the
# next pull. The digest is the multi-arch index of 1.2.0, the newest tagged
# release; it calls the API unversioned, so it keeps working as the engine's
# minimum API version moves. To bump: `docker buildx imagetools inspect
# willfarrell/autoheal:<tag>` and paste the top-level Digest.
#
# This is the watchdog retired on 2026-10-01 (.deprecated/autoheal), back
# with a label filter instead of `all`, so backend's and python's
# healthchecks stay informational.
autoheal: autoheal:
image: willfarrell/autoheal@sha256:31f580ef0279eaced5b38d631b08c474d70d8403c1c2fdd6ddcf2e879d5f3f7c image: willfarrell/autoheal@sha256:31f580ef0279eaced5b38d631b08c474d70d8403c1c2fdd6ddcf2e879d5f3f7c
container_name: autoheal container_name: autoheal
@@ -764,141 +385,3 @@ services:
- AUTOHEAL_CONTAINER_LABEL=autoheal - AUTOHEAL_CONTAINER_LABEL=autoheal
volumes: volumes:
- /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).
# The backend writes to it on :3900 once S3_ENDPOINT is set in .env; Caddy
# serves /uploads/ from it anonymously on :3902, falling back to the
# `uploads` volume; garage-webui manages it via :3903. Nothing is published
# to the host. Config is garage/garage.toml (no secrets in it); the two
# secrets come from .env through the explicit list below.
#
# Nothing depends on this container being up. Caddy is deliberately NOT
# given it in depends_on: it resolves garage when it dials it, so a missing
# or crash-looping garage only makes bucket-only files 404 (everything on
# the volume is still served), never Caddy's start; and the backend falls back
# to the volume when a write fails.
#
# FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access).
# The image is FROM scratch — no shell, so no in-container init script and
# a healthcheck that calls the binary itself.
garage:
image: dxflrs/garage:v2.5.0
container_name: garage
restart: always
networks:
- app-network
environment:
- GARAGE_RPC_SECRET=${GARAGE_RPC_SECRET}
- GARAGE_ADMIN_TOKEN=${GARAGE_ADMIN_TOKEN}
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
- garage_meta:/var/lib/garage/meta
- garage_data:/var/lib/garage/data
healthcheck:
test: ["CMD", "/garage", "status"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
# Admin web UI for Garage, served at /garage/ behind Caddy's admin gate.
# Manages buckets and keys, and browses/uploads/deletes objects. Its own
# login (AUTH_USER_PASS) is left unset because Caddy's admin gate already
# requires the site admin — and it holds the admin token, so never publish
# its port. It reads the s3/web settings from garage.toml; the token comes
# from .env instead, since the file has none.
#
# Files uploaded here land in the PUBLIC bucket and are served at
# /uploads/<path> with none of the backend's checks. Put hand-managed media
# under a prefix (e.g. media/) so it can't collide with the backend's
# random hex names.
garage-webui:
image: khairul169/garage-webui:1.1.0
container_name: garage-webui
restart: always
depends_on:
- garage
networks:
- app-network
environment:
- BASE_PATH=/garage
- API_BASE_URL=http://garage:3903
- API_ADMIN_KEY=${GARAGE_ADMIN_TOKEN}
- S3_ENDPOINT_URL=http://garage:3900
- S3_REGION=garage
# The image has no /tmp, and Go spools any multipart upload over 32MB to
# a temp file there, so without this every large upload fails with
# "open /tmp/multipart-…: no such file or directory".
tmpfs:
- /tmp
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
# main, executed by the act_runner that lives outside docker (gitea-runner/).
#
# ROOTLESS image: runs as an unprivileged user, so config lives in /etc/gitea
# and data in /var/lib/gitea (not /data as in the root image) — that is why
# the bind mounts look unlike most Gitea compose examples.
#
# The GITEA__section__KEY environment convention is Gitea's own: each maps to
# an app.ini key and overrides the file at runtime, which is how the secrets
# stay in .env instead of in the committed app.ini.template.
#
# entrypoint is overridden to run our wrapper (which materialises app.ini
# from the template on first boot) before handing off to Gitea's real
# docker-entrypoint.sh. dumb-init is kept as PID 1 for correct signal/zombie
# handling, exactly as the stock image does it.
gitea:
image: docker.gitea.com/gitea:1.25.4-rootless
container_name: "${GITEA_HOST}"
entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"]
networks:
- app-network
environment:
- GITEA__database__DB_TYPE=postgres
- GITEA__database__HOST=${POSTGRES_HOST}
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
- GITEA__database__USER=${POSTGRES_USER}
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
# The host's own name, which Gitea prints in SSH clone URLs. It lives in
# .env, not app.ini, so moving to another host is a one-line change;
# environment-to-ini writes it into the live app.ini on every start.
# localhost suits dev.
- GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
- GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
# Webhooks are refused to private addresses by default ("external").
# The usaco site's push hook targets http://usaco:8080 on the Docker
# network, so that one host is allowed by name.
- GITEA__webhook__ALLOWED_HOST_LIST=external,usaco
- USER_UID=1000
- USER_GID=1000
restart: always
volumes:
# PERSISTENT: repositories, LFS objects, avatars, sessions. The git data
# itself. (Gitea's *relational* data is in Postgres, not here.)
- ./gitea/data:/var/lib/gitea
# PERSISTENT: app.ini is generated into this host directory on first boot
# and then edited by Gitea itself, so it is gitignored — only the
# template is committed.
- ./gitea/config:/etc/gitea
# Mounted over the config dir so the wrapper script is available at the
# path the overridden entrypoint points at.
- ./gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
# Match the Pi's clock/zone so commit and CI timestamps are local time.
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
ports:
# 2222 = Gitea's *built-in* SSH server (the rootless image cannot use 22).
# Clones use ssh://git@host:2222/... — including the deploy workflow,
# which fetches from ssh://git@localhost:2222.
- "2222:2222"
# 3000 = HTTP, published directly as well as proxied at /gitea/, because
# the act_runner registers against http://localhost:3000 from the host.
- "3000:3000"
depends_on:
- db
-109
View File
@@ -1,109 +0,0 @@
#!/bin/sh
# =============================================================================
# One-time setup of the `garage` container. Run from the repo root, on the
# host, once the container is up:
#
# garage/bootstrap.sh
#
# Idempotent: every step checks before acting, so re-running it is harmless.
# Garage keeps all of this in the garage_meta volume, so it is only needed on
# a fresh volume — once on stpvm, and again whenever a dev stack starts from
# nothing.
#
# WHY A HOST SCRIPT
# The dxflrs/garage image is FROM scratch: a single binary, no shell. There
# is nothing to run an init script with inside it, so this drives the
# binary through `docker compose exec`.
#
# WHAT IT DOES
# 1. Gives the single node a role in the cluster layout. Until it has one,
# Garage accepts connections but refuses to store anything.
# 2. Creates the bucket (S3_BUCKET, default `uploads`).
# 3. Imports the backend's access key from .env (S3_ACCESS_KEY_ID /
# S3_SECRET_ACCESS_KEY). Importing rather than letting Garage generate
# one keeps .env the single source of truth: a wiped volume comes back
# with the same credentials and the backend needs no change.
# 4. Grants that key read+write on the bucket. garage-webui also browses
# with it: it borrows the first key that has access to a bucket.
# 5. Opens the bucket on the website endpoint, which is what Caddy serves
# /uploads/ from, anonymously.
#
# ENV / .env
# S3_ACCESS_KEY_ID required; "GK" + 24 hex chars
# S3_SECRET_ACCESS_KEY required; 64 hex chars
# S3_BUCKET optional, default uploads
# GARAGE_CAPACITY optional, default 20G. Only weights data placement
# between nodes; with one node it is no quota.
# COMPOSE optional, default `docker compose`. Set it to add
# the dev override, e.g.
# COMPOSE="docker compose -f docker-compose.yml -f docker-compose.dev.yml"
# =============================================================================
set -eu
COMPOSE=${COMPOSE:-docker compose}
# Read one KEY=value from .env without sourcing it: .env is not guaranteed to
# be valid shell (unquoted spaces, `$` in secrets). A value already in the
# environment wins, so the script also runs without a .env.
envval() {
eval "current=\${$1:-}"
if [ -n "$current" ]; then
printf '%s' "$current"
return
fi
[ -f .env ] || return 0
grep -E "^$1=" .env | tail -n 1 | cut -d= -f2- | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'$/\1/"
}
garage() {
$COMPOSE exec -T garage /garage "$@"
}
KEY_ID=$(envval S3_ACCESS_KEY_ID)
SECRET=$(envval S3_SECRET_ACCESS_KEY)
BUCKET=$(envval S3_BUCKET)
BUCKET=${BUCKET:-uploads}
CAPACITY=$(envval GARAGE_CAPACITY)
CAPACITY=${CAPACITY:-20G}
KEY_NAME=site-backend
# Garage rejects other shapes at import time with a less helpful message.
if ! printf '%s' "$KEY_ID" | grep -Eq '^GK[0-9a-f]{24}$'; then
echo "S3_ACCESS_KEY_ID must be GK followed by 24 hex chars (try: echo GK\$(openssl rand -hex 12))" >&2
exit 1
fi
if ! printf '%s' "$SECRET" | grep -Eq '^[0-9a-f]{64}$'; then
echo "S3_SECRET_ACCESS_KEY must be 64 hex chars (try: openssl rand -hex 32)" >&2
exit 1
fi
# 1. Layout. `node id -q` prints "<full id>@<addr>"; the id is what
# `layout assign` takes.
if garage layout show 2>/dev/null | grep -q "No nodes currently have a role"; then
NODE_ID=$(garage node id -q 2>/dev/null | cut -d@ -f1)
echo "Assigning node $(printf '%s' "$NODE_ID" | cut -c1-16) (capacity $CAPACITY)"
garage layout assign -z dc1 -c "$CAPACITY" "$NODE_ID"
garage layout apply --version 1
else
echo "Layout already applied"
fi
# 2. Bucket.
if garage bucket info "$BUCKET" >/dev/null 2>&1; then
echo "Bucket $BUCKET exists"
else
garage bucket create "$BUCKET"
fi
# 3. Key.
if garage key info "$KEY_ID" >/dev/null 2>&1; then
echo "Key $KEY_ID exists"
else
garage key import -n "$KEY_NAME" --yes "$KEY_ID" "$SECRET"
fi
# 4 and 5 are idempotent in Garage itself.
garage bucket allow --read --write "$BUCKET" --key "$KEY_ID"
garage bucket website --allow "$BUCKET"
echo "Garage ready: bucket $BUCKET, key $KEY_ID"
-51
View File
@@ -1,51 +0,0 @@
# =============================================================================
# Garage — the S3-compatible object store behind /uploads/.
#
# One node, one copy of everything (replication_factor = 1): this is storage
# on the same disk as the rest of the site, not a resilience layer, so the
# garage_meta and garage_data volumes still need backing up like the others.
#
# NO SECRETS IN THIS FILE. It is committed and mounted read-only into both
# `garage` and `garage-webui`. rpc_secret and admin_token come from the
# GARAGE_RPC_SECRET and GARAGE_ADMIN_TOKEN environment variables, which Garage
# reads in place of the config keys.
#
# Binds are 0.0.0.0 rather than Garage's usual [::]: containers on a bridge
# network without IPv6 may refuse an IPv6 bind. None of these ports is
# published to the host; everything reaches them over app-network.
#
# PORTS
# 3900 S3 API. The backend writes uploads here (signed with the key that
# garage/bootstrap.sh imports); garage-webui browses through it.
# 3901 RPC between Garage nodes. Only this node talks to itself.
# 3902 Website endpoint. Serves a bucket ANONYMOUSLY, choosing it from the
# Host header: "<bucket><root_domain>", so Caddy's /uploads/ route
# sends `Host: uploads.web.garage`. Only buckets that bootstrap.sh
# opened with `garage bucket website --allow` are served.
# 3903 Admin API, used by garage-webui and authenticated by admin_token.
# =============================================================================
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "lmdb"
# LMDB can be left unreadable by a crash mid-write; a periodic snapshot of
# the metadata is what `garage meta` restores from.
metadata_auto_snapshot_interval = "6h"
replication_factor = 1
rpc_bind_addr = "0.0.0.0:3901"
rpc_public_addr = "127.0.0.1:3901"
[s3_api]
api_bind_addr = "0.0.0.0:3900"
# Any string works; it only has to match what clients sign with (S3_REGION).
s3_region = "garage"
root_domain = ".s3.garage"
[s3_web]
bind_addr = "0.0.0.0:3902"
root_domain = ".web.garage"
index = "index.html"
[admin]
api_bind_addr = "0.0.0.0:3903"
-53
View File
@@ -1,53 +0,0 @@
#!/usr/bin/env bash
# =============================================================================
# gitea-runner/download.sh — fetch the act_runner binary for this machine.
#
# WHAT IT DOES
# Downloads the correct act_runner release asset for the host CPU and drops
# it next to this script as ./act_runner (gitignored — a binary, not source).
#
# WHY IT IS A SCRIPT AND NOT A CONTAINER
# The runner executes the deploy workflow, which itself runs
# `docker compose up -d --build` against this stack. Running it inside the
# stack would mean a container restarting its own parent mid-job. So the
# runner lives OUTSIDE docker, directly on the Pi, and is the one moving part
# of this repo that docker compose does not manage.
#
# ARCHITECTURE SELECTION (the Raspberry Pi bit)
# uname -m decides the asset. aarch64 is the 64-bit Pi OS case and is what
# this deployment actually uses; armv7l covers a 32-bit Pi OS install and
# x86_64 covers running the same script on a dev laptop. An unknown arch is a
# hard error rather than a silent wrong download.
#
# VERSION is pinned so a runner upgrade is an explicit commit, never a surprise
# on a re-run. Bump it here, delete ./act_runner, and re-run to upgrade.
#
# SCRIPT_DIR is resolved so the binary always lands beside the script even when
# invoked from another directory.
#
# USAGE: bash gitea-runner/download.sh (run.sh calls it automatically if the
# binary is missing)
# =============================================================================
set -euo pipefail
VERSION="0.2.11"
BASE_URL="https://gitea.com/gitea/act_runner/releases/download/v${VERSION}"
ARCH=$(uname -m)
case "$ARCH" in
x86_64) ASSET="act_runner-${VERSION}-linux-amd64" ;;
aarch64) ASSET="act_runner-${VERSION}-linux-arm64" ;;
armv7l) ASSET="act_runner-${VERSION}-linux-armv7" ;;
*)
echo "Unsupported architecture: $ARCH" >&2
exit 1
;;
esac
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DEST="${SCRIPT_DIR}/act_runner"
echo "Downloading act_runner v${VERSION} for ${ARCH}..."
curl -fSL "${BASE_URL}/${ASSET}" -o "$DEST"
chmod +x "$DEST"
echo "Downloaded to $DEST"
-73
View File
@@ -1,73 +0,0 @@
#!/usr/bin/env bash
# =============================================================================
# gitea-runner/run.sh — register (once) and then run the Gitea Actions runner.
#
# WHAT IT DOES
# 1. Downloads the act_runner binary if it is not already present.
# 2. Blocks until Gitea answers on http://localhost:3000.
# 3. Registers with Gitea the first time only.
# 4. execs the runner daemon in the foreground.
#
# WHEN IT RUNS
# On the Pi, outside docker, as a long-lived process (systemd unit or nohup).
# It must be started from THIS directory: the script uses relative paths
# (./act_runner, .runner) and `act_runner daemon` looks for .runner in the
# current working directory.
#
# WHY IT WAITS FOR PORT 3000
# On a Pi reboot this process and the docker stack race. Registering or
# starting the daemon against a Gitea that is not up yet fails permanently
# rather than retrying, so the loop polls (forever, by design — there is no
# sensible timeout when the answer is "wait longer") until Gitea responds.
# It targets localhost:3000, the port docker-compose.yml publishes directly,
# NOT the public /gitea/ path through Caddy — so the runner keeps working
# even while TLS or Caddy is broken.
#
# THE REGISTRATION TOKEN (one-shot, and easy to get wrong)
# GITEA_RUNNER_REGISTRATION_TOKEN comes from ./.env and is generated in the
# Gitea web UI (Site Administration -> Actions -> Runners -> Create new
# runner). It is a single-use enrolment token, NOT a lasting credential:
# registration exchanges it for a permanent runner identity written to the
# .runner file (gitignored — that file IS the real credential).
#
# The `if [ ! -f .runner ]` guard is what makes this idempotent. Once .runner
# exists the token is never used again and may safely be stale in .env. To
# re-register a runner you must delete .runner AND mint a FRESH token in the
# UI — reusing the old one will fail.
#
# --labels self-hosted must match `runs-on: self-hosted` in
# .gitea/workflows/*.yaml, or jobs queue forever with no runner picking them up.
#
# ENV VARS
# GITEA_RUNNER_REGISTRATION_TOKEN required for first registration only
# GITEA_RUNNER_NAME optional, defaults to "pi-runner"
# (this script does not source .env itself — export them or use an
# EnvironmentFile in the systemd unit)
#
# Diagnostics go to stderr so stdout stays clean for the daemon's own output.
# =============================================================================
if [ ! -f ./act_runner ]; then
echo "act_runner binary not found. Downloading..." >&2
bash "$(dirname "$0")/download.sh"
fi
echo "Waiting for localhost:3000 to respond..." >&2
while ! curl -sf http://localhost:3000 > /dev/null 2>&1; do
sleep 2
done
echo "localhost:3000 is up." >&2
if [ ! -f .runner ]; then
echo "No .runner file found. Registering runner..." >&2
./act_runner register --no-interactive \
--instance http://localhost:3000 \
--token "${GITEA_RUNNER_REGISTRATION_TOKEN}" \
--name "${GITEA_RUNNER_NAME:-pi-runner}" \
--labels self-hosted
fi
echo "Starting act_runner daemon..." >&2
exec ./act_runner daemon
-134
View File
@@ -1,134 +0,0 @@
; =============================================================================
; app.ini.template — seed configuration for Gitea, copied to app.ini on the
; FIRST boot on a host by gitea/entrypoint.sh and never touched again after.
;
; IMPORTANT: editing this file does nothing to a running install. Gitea owns
; ./gitea/config/app.ini (it rewrites it from the web UI) and that real file is
; gitignored because it accumulates generated secrets.
;
; SECRET FIELDS ARE DELIBERATELY BLANK HERE
; LFS_JWT_SECRET, PASSWD, SECRET_KEY and JWT_SECRET are empty on purpose so
; nothing sensitive is committed. Real values arrive at runtime as
; GITEA__section__KEY environment variables from ./.env (see
; docker-compose.yml), which override app.ini. SECRET_KEY is the exception —
; Gitea generates one itself on first run and writes it into the live app.ini.
;
; SETTINGS WORTH KNOWING
; ROOT_URL must match the public path Caddy serves Gitea at (/gitea/), or
; every link, clone URL and OAuth redirect Gitea emits will be wrong.
; START_SSH_SERVER = true with SSH_PORT 2222: the rootless image cannot bind
; 22 and cannot use the host's sshd, so Gitea runs its own Go SSH server.
; 2222 is published in docker-compose.yml; the deploy workflow clones over
; ssh://git@localhost:2222.
; SSH_DOMAIN and DOMAIN are not set here: they come from GITEA_SSH_DOMAIN in
; ./.env (see docker-compose.yml). The value is the host's Tailscale
; MagicDNS name, not the public domain: SSH
; (22 and 2222) is not forwarded by the router, so the SSH clone URL Gitea
; shows only works from a device on the tailnet. HTTPS clones go through
; Caddy at ROOT_URL and stay public.
; REVERSE_PROXY_LIMIT = 1 / TRUSTED_PROXIES = * : trust exactly one hop of
; X-Forwarded-For, i.e. our Caddy, so Gitea logs real client IPs. Caddy
; sends a single entry, the visitor (its `proxy` snippet). This is only
; safe because Caddy is the sole edge.
; INSTALL_LOCK = true skips the first-run web installer.
; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up.
; OFFLINE_MODE = true — no calls out to gravatar/CDNs.
; DB_TYPE postgres pointing at the shared `db` container, in its own database
; alongside the app's. WORK_PATH/APP_DATA_PATH are /var/lib/gitea, the
; rootless image's layout (the root image uses /data instead).
; =============================================================================
APP_NAME = Gitea: Git with a cup of tea
RUN_USER = git
RUN_MODE = prod
WORK_PATH = /var/lib/gitea
[repository]
ROOT = /var/lib/gitea/git/repositories
[repository.local]
LOCAL_COPY_PATH = /tmp/gitea/local-repo
[repository.upload]
TEMP_PATH = /tmp/gitea/uploads
[server]
APP_DATA_PATH = /var/lib/gitea
HTTP_PORT = 3000
ROOT_URL = https://adam-french.co.uk/gitea/
DISABLE_SSH = false
; In rootless gitea container only internal ssh server is supported
START_SSH_SERVER = true
SSH_PORT = 2222
SSH_LISTEN_PORT = 2222
BUILTIN_SSH_SERVER_USER = git
LFS_START_SERVER = true
LFS_JWT_SECRET =
OFFLINE_MODE = true
[database]
PATH = /var/lib/gitea/data/gitea.db
DB_TYPE = postgres
HOST = db
NAME = gitea
USER = postgres
PASSWD =
SCHEMA =
SSL_MODE = disable
LOG_SQL = false
[session]
PROVIDER_CONFIG = /var/lib/gitea/data/sessions
PROVIDER = file
[picture]
AVATAR_UPLOAD_PATH = /var/lib/gitea/data/avatars
REPOSITORY_AVATAR_UPLOAD_PATH = /var/lib/gitea/data/repo-avatars
[attachment]
PATH = /var/lib/gitea/data/attachments
[log]
ROOT_PATH = /var/lib/gitea/data/log
MODE = console
LEVEL = info
[security]
INSTALL_LOCK = true
SECRET_KEY =
REVERSE_PROXY_LIMIT = 1
REVERSE_PROXY_TRUSTED_PROXIES = *
PASSWORD_HASH_ALGO = pbkdf2
[service]
DISABLE_REGISTRATION = true
REQUIRE_SIGNIN_VIEW = false
REGISTER_EMAIL_CONFIRM = false
ENABLE_NOTIFY_MAIL = false
ALLOW_ONLY_EXTERNAL_REGISTRATION = false
ENABLE_CAPTCHA = false
DEFAULT_KEEP_EMAIL_PRIVATE = false
DEFAULT_ALLOW_CREATE_ORGANIZATION = true
DEFAULT_ENABLE_TIMETRACKING = true
NO_REPLY_ADDRESS = noreply.localhost
[lfs]
PATH = /var/lib/gitea/git/lfs
[mailer]
ENABLED = false
[openid]
ENABLE_OPENID_SIGNIN = true
ENABLE_OPENID_SIGNUP = true
[cron.update_checker]
ENABLED = false
[repository.pull-request]
DEFAULT_MERGE_STYLE = merge
[repository.signing]
DEFAULT_TRUST_MODEL = committer
[oauth2]
JWT_SECRET =
+2 -28
View File
@@ -1,31 +1,5 @@
# ============================================================================= # liquidsoap base (the hard one to install) plus icecast2. media-types gives
# Radio image — liquidsoap base with icecast2 added on top. # icecast correct content types. Both daemons run as `radio`, hence chroot 0.
#
# BASE CHOICE: savonet/liquidsoap:v2.3.2, pinned. Liquidsoap is by far the
# harder of the two to install (OCaml toolchain, many audio codecs), so the
# image starts from the official liquidsoap build and adds icecast2 from apt,
# rather than the other way round. Both daemons then run in one container so
# liquidsoap can reach icecast on localhost — see icecast2/entrypoint.sh.
#
# PACKAGES
# icecast2 the streaming server itself
# gettext provides `envsubst` for rendering the two config templates
# media-types the /etc/mime.types database; without it icecast serves the
# stream and its status pages with wrong content types
#
# THE USER SWITCH: apt needs root, so the image switches to root, installs,
# creates an unprivileged `radio` user, chowns everything the two daemons will
# need to write (icecast config, its logs, the music dir, the liquidsoap config
# dir) and then drops back to `radio` for the rest. Neither daemon runs as
# root, which is also why icecast.xml sets <chroot>0</chroot> — an unprivileged
# process cannot chroot anyway.
#
# The chown of /music matters even though it is mounted read-only at runtime:
# the mount inherits ownership from the host, and the directory must exist
# before the mount lands.
#
# The apt install is Debian-based and multi-arch; no platform pin needed on the Pi.
# =============================================================================
FROM savonet/liquidsoap:v2.3.2 FROM savonet/liquidsoap:v2.3.2
USER root USER root
RUN apt-get update \ RUN apt-get update \
+3 -48
View File
@@ -1,52 +1,7 @@
#!/bin/bash #!/bin/bash
# ============================================================================= # Runs icecast2 and liquidsoap together (liquidsoap feeds icecast over
# icecast2 entrypoint — runs the streaming server AND its audio source together. # localhost). Bare envsubst: an unset variable becomes "", including passwords.
# # If either daemon exits the container exits 1, so restart: always recycles it.
# WHAT IT DOES
# This one container holds two cooperating daemons:
# icecast2 - the HTTP streaming server listeners connect to. Caddy
# proxies /radio/ to it.
# liquidsoap - the *source*: it decides what audio to play and pushes a
# single MP3 stream into icecast's mount point.
# They are colocated because liquidsoap connects to icecast over
# host="localhost" (see stream.liq.template) — no network hop, and the source
# password never leaves the container.
#
# WHEN IT RUNS
# Container start (ENTRYPOINT), in both dev and production.
#
# THE TEMPLATING STEP
# Both configs are rendered by bare `envsubst` (no allow-list) because unlike
# the old nginx templates, neither icecast.xml nor stream.liq has any legitimate
# dollar-token of its own — every ${VAR} in them is meant to be substituted,
# so an unrestricted envsubst is safe here. NOTE the consequence: any
# referenced variable that is unset silently becomes an empty string, which
# for a password field means "empty password" rather than an error.
#
# STARTUP ORDER AND THE sleep 2
# liquidsoap's output.icecast connects to icecast as a client on startup and
# there is no readiness check available, so the script backgrounds icecast,
# waits a fixed 2 seconds for it to bind its port, then starts liquidsoap.
# It is a race, not a guarantee — but `fallible=true` in stream.liq means
# liquidsoap retries the connection rather than dying if it loses.
#
# PROCESS SUPERVISION
# `wait -n` returns as soon as EITHER daemon exits. We then kill whatever is
# still running and exit 1, so a half-dead container (icecast up, liquidsoap
# dead = silence forever) becomes a full crash that docker's
# `restart: always` will recycle. Exiting non-zero is deliberate.
#
# ENV VARS REQUIRED (from ./.env)
# ICECAST_SOURCE_PASSWORD shared by icecast (accepts) and liquidsoap (sends)
# ICECAST_RELAY_PASSWORD for relay clients
# ICECAST_ADMIN_USER / ICECAST_ADMIN_PASSWORD icecast web admin
# ICECAST_HOST / ICECAST_PORT / ICECAST_MOUNT listener-facing stream
# LIQUIDSOAP_HARBOR_MOUNT / LIQUIDSOAP_HARBOR_PORT live DJ input
#
# ASSUMES EXISTS
# /music - read-only bind mount of ./icecast2/fallback_music, the fallback
# playlist. If it is empty the stream falls through to silence.
# =============================================================================
set -e set -e
envsubst < /etc/icecast2/icecast.xml.template > /etc/icecast2/icecast.xml envsubst < /etc/icecast2/icecast.xml.template > /etc/icecast2/icecast.xml
+4 -38
View File
@@ -1,41 +1,7 @@
# ============================================================================= # Rendered by entrypoint.sh. Fallback chain: live harbor input, then the
# stream.liq.template — liquidsoap source script for the internet radio. # watched /music playlist, then silence. track_sensitive=false switches to a
# # live DJ immediately. amplify trims the loud fallback MP3s. fallible=true
# RENDERED BY icecast2/entrypoint.sh with bare envsubst into # survives the entrypoint's startup race.
# /etc/liquidsoap/stream.liq at container start. Every VAR placeholder below comes from
# ./.env; an unset one silently becomes an empty string.
#
# WHAT IT BUILDS, bottom of the fallback chain upward:
# blank() - digital silence; the last resort so the mount is never dropped.
# music - the fallback playlist read from the /music bind mount
# (./icecast2/fallback_music on the host). reload_mode="watch"
# means adding or removing an MP3 on the host is picked up live,
# with no container restart.
# live - a *harbor* input: liquidsoap itself listens on
# LIQUIDSOAP_HARBOR_PORT and accepts an incoming source
# connection. This is the "go live" path — a broadcasting client
# on the LAN/internet connects with ICECAST_SOURCE_PASSWORD and
# starts talking. It is the one reason icecast2 publishes a host
# port in docker-compose.yml.
#
# fallback(track_sensitive=false, [live, music, blank()])
# Picks the first available source in list order, so a live DJ pre-empts
# the playlist automatically. track_sensitive=false is the important flag:
# it makes the switch happen IMMEDIATELY rather than politely waiting for
# the current track to finish — otherwise going live could take minutes.
#
# amplify(0.7, ...) - a fixed -3dB or so trim, because the fallback MP3s are
# mastered loud and were clipping against the live input.
#
# OUTPUT
# Pushes to icecast on localhost (same container) at ICECAST_MOUNT, which is
# what Caddy exposes at /radio/. fallible=true tells liquidsoap this output
# is allowed to fail and be retried, instead of aborting the script — that is
# what makes the `sleep 2` startup race in the entrypoint survivable.
#
# settings.server.telnet := false — the liquidsoap control socket is off; there
# is no interactive way to poke the running stream.
# =============================================================================
settings.server.telnet := false settings.server.telnet := false
music = playlist("/music", mode="randomize", reload_mode="watch") music = playlist("/music", mode="randomize", reload_mode="watch")
+2 -26
View File
@@ -1,29 +1,5 @@
# ============================================================================= # ROOT_PATH: Caddy strips /py, so --root-path is what makes /py/docs work.
# FastAPI side-service image. # sh -c so ${PYTHON_PORT} and ${ROOT_PATH} expand at runtime.
#
# requirements.txt is copied and installed before the app source so the
# dependency layer is cached across code changes. --no-cache-dir keeps pip's
# download cache out of the image (this one is a plain layer, not a BuildKit
# cache mount, because the dependency set is small).
#
# PYTHONDONTWRITEBYTECODE stops .pyc files being written into the image and the
# dev bind mount; PYTHONUNBUFFERED makes logs appear in `docker logs`
# immediately instead of sitting in a buffer — both are standard for
# containerised Python and the second one matters for debugging.
#
# ROOT_PATH=/py: Caddy proxies /py/ and STRIPS the prefix, so the app's routes
# are written relative to /. --root-path tells FastAPI it is nonetheless
# mounted under a prefix, so the OpenAPI schema and Swagger UI emit correct
# /py/... URLs. Without it, /py/docs loads but cannot call anything.
#
# The CMD is a `sh -c` form on purpose: it needs the shell to expand
# ${PYTHON_PORT} and ${ROOT_PATH} at runtime, which the exec form cannot do.
# Both have defaults here so the image runs standalone; docker compose normally
# supplies them.
#
# EXPOSE 8000 is documentation only — the port is not published; Caddy reaches
# it over app-network.
# =============================================================================
FROM python:3.12-slim FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ ENV PYTHONDONTWRITEBYTECODE=1 \
+27 -42
View File
@@ -1,13 +1,6 @@
"""The Anthropic client and the one call every Claude caller here makes. """The Anthropic client and `ask_json`: one prompt for bare JSON, one parsed reply.
`rowing` (a photo in, three numbers out) is a call of a general shape: one The two exception types map to 502 and 503 in `main`. Never imports FastAPI.
prompt asking for bare JSON, one reply to parse. That whole sequence is
`ask_json` below, so a caller is a prompt, a pydantic model and three error
strings, and another caller would get the same handling around the call. Also
here: the lazily built client and the two exception types `main` maps to 502
and 503.
Like the modules that use it, this never imports FastAPI.
""" """
import functools import functools
@@ -22,37 +15,21 @@ log = logging.getLogger(__name__)
T = TypeVar("T", bound=BaseModel) T = TypeVar("T", bound=BaseModel)
# Which model every call uses. CLAUDE_MODEL comes from .env; changing it means # Read once at import; blank means the default. Unknown ids are passed
# recreating this container, which is why reading it once at import is enough. # through and treated as thinking models.
# Blank means the default.
#
# The ids listed in .env.example are the ones this module has been written for. Another
# id is passed through as it is, treated as a model that thinks (see below);
# if the API does not know it, every call fails with its `failed` message and
# the reason is in this service's log.
DEFAULT_MODEL = "claude-sonnet-5-5" DEFAULT_MODEL = "claude-sonnet-5-5"
MODEL = os.environ.get("CLAUDE_MODEL", "").strip() or DEFAULT_MODEL MODEL = os.environ.get("CLAUDE_MODEL", "").strip() or DEFAULT_MODEL
# Models that take no `output_config.effort` and do not think unless asked to. # Models that take no effort setting and don't think unless asked.
# Everything newer thinks by default, and that changes two things in the
# request - see _model_options.
_NO_EFFORT_PREFIXES = ("claude-haiku-4-5",) _NO_EFFORT_PREFIXES = ("claude-haiku-4-5",)
# Thinking is billed against `max_tokens` like the reply is, and the callers' # Thinking counts against max_tokens, and callers size theirs for the reply.
# ceilings are sized for the reply alone (a few hundred tokens of JSON). On a
# model that thinks, this is added on top so that a posting worth a moment's
# thought cannot use the whole allowance and leave no room for the answer.
THINKING_HEADROOM = 4000 THINKING_HEADROOM = 4000
# Every call here is extraction or classification: read something, return a # Set explicitly because the default differs between models.
# small JSON object. "low" is the level meant for that - the model skips
# thinking on most simple requests - and it is set explicitly because the
# default differs between models.
EFFORT = "low" EFFORT = "low"
# Seconds per attempt. The SDK retries twice on top (429/5xx/connection), so # Per attempt; the SDK retries twice. The Go caller's timeout sits above that.
# the worst case is roughly three of these plus backoff; the Go callers' own
# timeout is set above that so they see this side's error, not their own.
TIMEOUT_S = 30.0 TIMEOUT_S = 30.0
@@ -105,7 +82,10 @@ def _model_options(model: str, max_tokens: int) -> dict:
""" """
if model.startswith(_NO_EFFORT_PREFIXES): if model.startswith(_NO_EFFORT_PREFIXES):
return {"max_tokens": max_tokens} return {"max_tokens": max_tokens}
return {"max_tokens": max_tokens + THINKING_HEADROOM, "output_config": {"effort": EFFORT}} return {
"max_tokens": max_tokens + THINKING_HEADROOM,
"output_config": {"effort": EFFORT},
}
def ask_json( def ask_json(
@@ -145,12 +125,15 @@ def ask_json(
NotConfigured: no API key. NotConfigured: no API key.
ReadError: with one of the three messages above. ReadError: with one of the three messages above.
""" """
request = {"model": MODEL, "messages": messages, **_model_options(MODEL, max_tokens)} request = {
"model": MODEL,
"messages": messages,
**_model_options(MODEL, max_tokens),
}
if system is not None: if system is not None:
request["system"] = system request["system"] = system
# Outside the try: NotConfigured is not an API failure and must reach # Outside the try so NotConfigured reaches `main` and becomes the 503.
# `main` as itself, to become the 503.
api = (get_client or client)() api = (get_client or client)()
try: try:
message = api.messages.create(**request) message = api.messages.create(**request)
@@ -161,19 +144,21 @@ def ask_json(
log.warning("Claude API unreachable: %s", e) log.warning("Claude API unreachable: %s", e)
raise ReadError(failed) from e raise ReadError(failed) from e
# A refusal is an ordinary 200 whose content is not the answer. Say so in # A refusal is a 200; log it as such rather than as an unparseable reply.
# the log rather than letting it surface as an "empty" or "unparseable"
# reply, which would point at the prompt instead of at the classifier.
if getattr(message, "stop_reason", None) == "refusal": if getattr(message, "stop_reason", None) == "refusal":
log.warning("Claude declined the request: %s", getattr(message, "stop_details", None)) log.warning(
"Claude declined the request: %s", getattr(message, "stop_details", None)
)
raise ReadError(failed) raise ReadError(failed)
# By type, not position: on a model that thinks, the first block can be a # By type: on a thinking model the first block may be a thinking block.
# (possibly empty) thinking block.
text = next((block.text for block in message.content if block.type == "text"), None) text = next((block.text for block in message.content if block.type == "text"), None)
if text is None: if text is None:
if getattr(message, "stop_reason", None) == "max_tokens": if getattr(message, "stop_reason", None) == "max_tokens":
log.warning("Claude ran out of tokens before answering (max_tokens=%s)", request["max_tokens"]) log.warning(
"Claude ran out of tokens before answering (max_tokens=%s)",
request["max_tokens"],
)
raise ReadError(empty) raise ReadError(empty)
try: try:
+9 -39
View File
@@ -1,29 +1,8 @@
"""Small Python API service. """HTTP skin for `travelodge` and `rowing`.
Caddy proxies https://www.<DOMAIN>/py/... to this container and strips the Caddy strips /py, so routes are relative to "/" and --root-path keeps
/py prefix, so routes here are defined relative to "/". FastAPI's root_path /py/docs working. Field names in the hotel models are a contract with
(set via --root-path on the uvicorn command line) keeps the generated docs vue/src/views/hotels/. /internal/ routes are for the Go backend only.
at /py/docs working behind the proxy.
Endpoints
GET / service index
GET /health liveness probe
GET /hello/{name} demo route
GET /hotels/origins the known travel origins the UI offers
POST /hotels/search blocking cheapest-Travelodge search
POST /hotels/search/stream same search, streamed as NDJSON
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
POST /internal/rowing/read read a rowing display photo with Claude
(Go backend only - not reachable through Caddy)
All the hotel work lives in `travelodge`; this module is the HTTP skin around
it - request validation, a response cache, the one-search-at-a-time guard, and
the NDJSON framing. The rowing reader (`rowing`) is the one route here that
is not public: see the "Internal" sections at the bottom, which open with the
wrapper it is registered through. The hotel routes are consumed by
vue/src/views/hotels/ (SingleStayPanel.vue,
CheapestNightPanel.vue, useHotelForm.js), which fetch these paths with the /py
prefix. Field names in the models below are part of that contract.
""" """
import json import json
@@ -88,10 +67,7 @@ MAX_SCAN_DAYS = travelodge.SCAN_MAX_DAYS
CACHE_TTL_S = 10 * 60 CACHE_TTL_S = 10 * 60
CACHE_MAX = 200 CACHE_MAX = 200
# The service prices London hotels and London transport, so "today" means today # Dates are London dates, whatever the server's timezone.
# in London - not on whatever timezone the server happens to be set to. Using
# the server's local date refused a check-in that was still today for a user
# west of it (and, on a UTC server during BST, accepted one an hour late).
LONDON_TZ = ZoneInfo("Europe/London") LONDON_TZ = ZoneInfo("Europe/London")
@@ -99,15 +75,10 @@ def london_today() -> date:
"""Today's date in London, the reference for "today or later" validation.""" """Today's date in London, the reference for "today or later" validation."""
return datetime.now(LONDON_TZ).date() return datetime.now(LONDON_TZ).date()
# Only one live search or scan may run at a time, process-wide. A run can spend # One run at a time: a run can use the whole anonymous TfL budget. Others get
# the entire anonymous TfL budget (50 requests/min), so two concurrent runs # an immediate "try again".
# would simply starve each other into rate-limit backoff. Callers that find the
# slot taken get an immediate "try again" rather than queueing.
_search_slot = threading.Semaphore(1) _search_slot = threading.Semaphore(1)
# Finished responses, keyed by the canonical request body. Bounded as well as # Bounded because one response holds every row of a scan.
# swept: the one-at-a-time guard makes growth slow, but "slow" is not "never",
# and a response holds every row of a scan. Eviction is insertion order, so a
# repeatedly-requested entry still ages out and is refetched.
_cache = travelodge.TTLCache(CACHE_TTL_S, max_entries=CACHE_MAX) _cache = travelodge.TTLCache(CACHE_TTL_S, max_entries=CACHE_MAX)
@@ -726,8 +697,7 @@ MAX_IMAGE_B64_CHARS = 14_000_000
class RowingReadRequest(BaseModel): class RowingReadRequest(BaseModel):
"""An image for Claude to read, as the Go backend sends it.""" """An image for Claude to read, as the Go backend sends it."""
# The types the Anthropic API accepts for an image block. The Go handler # The Anthropic API's image types; the Go handler checks them first.
# checks the same list first so the admin gets its friendlier 400.
media_type: Literal["image/jpeg", "image/png", "image/gif", "image/webp"] media_type: Literal["image/jpeg", "image/png", "image/gif", "image/webp"]
data: str = Field(..., min_length=1, max_length=MAX_IMAGE_B64_CHARS, description="Base64 image bytes") data: str = Field(..., min_length=1, max_length=MAX_IMAGE_B64_CHARS, description="Base64 image bytes")
+5 -13
View File
@@ -1,20 +1,12 @@
"""Read a rowing machine display from a photo with Claude. """Read a rowing machine display from a photo with Claude.
This is the image half of the Go backend's admin-only POST /rowing. The Go The Go handler does auth, EXIF, dedup and bounds; this only turns pixels into
handler keeps everything that needs the database or the session cookie - the three numbers.
admin gate, the EXIF date, the duplicate check, the sanity bounds, the insert -
and hands the image here only once it has decided the Claude call is worth
paying for. This module just turns pixels into three numbers.
Like `travelodge`, it never imports FastAPI; `main` is the HTTP skin.
""" """
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
# Re-exported under the names this module has always had: the tests reach the # `_client` is the seam the tests replace.
# exceptions and the fence stripping through `rowing`. `_client` is the seam
# they replace to fake the API, which is why it is handed to ask_json below
# rather than left to its default.
from .claude import MODEL, NotConfigured, ReadError, ask_json, strip_markdown_fence from .claude import MODEL, NotConfigured, ReadError, ask_json, strip_markdown_fence
from .claude import client as _client from .claude import client as _client
@@ -23,8 +15,8 @@ __all__ = ["MODEL", "NotConfigured", "ReadError", "RowingReading", "read_display
# The answer is a three-key JSON object, so this is a ceiling, not a target. # The answer is a three-key JSON object, so this is a ceiling, not a target.
MAX_TOKENS = 256 MAX_TOKENS = 256
# The keys named here are the JSON contract: RowingReading's field names below # Keys must match RowingReading below and ExtractedRowingData in
# and ExtractedRowingData in backend/handlers/handle_rowing.go must match them. # backend/handlers/handle_rowing.go.
PROMPT = """Look at this rowing machine display. Extract the total elapsed time and total distance. PROMPT = """Look at this rowing machine display. Extract the total elapsed time and total distance.
Return ONLY a JSON object with these exact keys and numeric values: Return ONLY a JSON object with these exact keys and numeric values:
+45 -168
View File
@@ -1,63 +1,10 @@
"""Cheapest Travelodge (room + TfL transport) for a stay in London. """Cheapest Travelodge (room + TfL transport) for a stay in London.
Ported from ~/cheap_hotel/cheap_travelodge.py. The pricing logic is unchanged; The pricing method and the upstream fragility points are in python/README.md.
the plumbing around it has been rewritten for speed: Both APIs are undocumented JSON, read tolerantly: a renamed field becomes None,
not an error. Thread-based, with process-global caches, rate limiters and
* Travelodge result pages are fetched in parallel batches. session. Every network path takes a time.monotonic() `deadline`, so a long run
* TfL journeys are fetched by one flat worker pool (every hotel/query pair is returns partial work (summary["truncated"]) instead of being cut off.
submitted to it and results gathered per hotel), throttled to the anonymous API
limit (50 requests/min; 500/min with TFL_APP_KEY) and cached for a while
so repeat searches don't spend the budget again.
* `run_search` is a generator that yields the hotel list first and then one
event per priced hotel, so callers can stream progress to a browser.
Data sources
* Travelodge's own search JSON API -> live room prices for every hotel
matching a location search.
* TfL Journey Planner API -> route + pay-as-you-go fare from the origin to
each hotel.
Method
1. Pull every hotel for the search, drop ones with no availability, sort by
cheapest room price and keep only the cheapest `top` hotels.
2. For each, ask TfL for (a) the fastest route and (b) a bus-only route at
the given departure time. Pick the cheapest that isn't slower than
`max_travel_min`.
3. Apply a Railcard discount (1/3 off) to OFF-PEAK rail/tube fares. Buses
are never discounted.
4. Assume the return journey the next morning costs the off-peak equivalent
of the outbound.
5. Rank by room + round-trip transport. Cycling time is reported separately
(TfL cycle routing with an app key, otherwise a distance-based estimate).
Fragility
Neither API is a documented public contract for this use. Travelodge's
/api/v2/hotel endpoint is the JSON feed its own search page calls; the query
parameter names ("q", "checkIn", "rooms[0][adults]", the undocumented
"action=hotel_amend") and the response field names consumed in
`normalise_hotel` are whatever the site happens to send today. If Travelodge
reshapes its search page, every price here silently becomes None rather than
raising. Same for TfL's fare JSON: `price_journey` reads `fare.fares[].cost`
/ `peak` / `offPeak` / `chargeLevel`, and falls back to "no fare found" if the
shape changes. There is no HTML parsing anywhere in this module - both
upstreams are JSON - so there are no CSS/XPath selectors to break, but the
key names play the same role.
Concurrency
Everything here is thread-based (requests is blocking), not asyncio. Module
state - the two :class:`TTLCache` response caches, the rate limiters and the shared
requests.Session - is process-global and guarded by plain locks, so it is
shared across concurrent FastAPI requests. main.py additionally allows only
one live search at a time, which is what keeps the TfL budget spendable by a
single run.
Time budgets
Every network path takes an optional `deadline` (a time.monotonic() value).
Passing it down instead of using a wall-clock timeout lets a long run degrade
gracefully: work already done is returned with summary["truncated"] = True
instead of the whole request 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
@@ -71,19 +18,15 @@ from datetime import date, datetime, timedelta
import requests import requests
# Every upstream field is read tolerantly, so a Travelodge schema change would # Fields are read tolerantly, so this logger is the only way to tell a schema
# otherwise be indistinguishable from genuinely sold-out inventory. This logger # change from sold-out inventory (see `hotels_for`).
# is the only signal that the difference exists - see `hotels_for`.
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
TL_API = "https://www.travelodge.co.uk/api/v2/hotel" TL_API = "https://www.travelodge.co.uk/api/v2/hotel"
TL_SITE = "https://www.travelodge.co.uk" TL_SITE = "https://www.travelodge.co.uk"
TFL_API = "https://api.tfl.gov.uk/Journey/JourneyResults/{frm}/to/{to}" TFL_API = "https://api.tfl.gov.uk/Journey/JourneyResults/{frm}/to/{to}"
# A browser User-Agent is sent because Travelodge's edge rejects or throttles # Travelodge's edge throttles scripted User-Agents. If 403s or challenge pages
# obviously-scripted clients (python-requests/x.y). The Chrome version is # appear, bump the Chrome version first.
# arbitrary and is never checked for freshness; if requests start coming back
# as 403 or as a challenge page, this is the first thing to bump. The same
# headers are reused for TfL, where they are harmless.
HEADERS = { HEADERS = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36",
"Accept": "application/json", "Accept": "application/json",
@@ -104,49 +47,39 @@ 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. Set when nginx cut the connection # Wall-clock budget for one run_search call.
# 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 # Scans stop starting date fetches at the soft deadline and stop TfL pricing
# prices TfL once per unique hotel. Stop starting new date fetches after the # at the hard one.
# soft deadline; stop TfL pricing at the hard one and return what we have.
SCAN_FETCH_DEADLINE_S = 150 SCAN_FETCH_DEADLINE_S = 150
SCAN_DEADLINE_S = 240 SCAN_DEADLINE_S = 240
SCAN_DATE_WORKERS = int(os.environ.get("TL_SCAN_WORKERS", "4")) SCAN_DATE_WORKERS = int(os.environ.get("TL_SCAN_WORKERS", "4"))
SCAN_MAX_DAYS = 91 SCAN_MAX_DAYS = 91
# Normalised Travelodge results are cached per (location, dates, rooms) so a # Lets a re-scan with different settings skip Travelodge.
# re-scan with different weekday/transport settings is free on the Travelodge
# side. Prices may therefore be up to TL_CACHE_TTL_S old.
TL_CACHE_TTL_S = 30 * 60 TL_CACHE_TTL_S = 30 * 60
TL_CACHE_MAX = 600 TL_CACHE_MAX = 600
# Travelodge returns 10 hotels per page whatever you ask for; fetch pages in # Travelodge returns 10 per page regardless; batches stop when nothing is new.
# parallel batches until a batch comes back with nothing new.
TL_PAGE_SIZE = 10 TL_PAGE_SIZE = 10
TL_PAGE_BATCH = 6 TL_PAGE_BATCH = 6
TL_MAX_START = 500 TL_MAX_START = 500
# TfL: anonymous callers get 50 requests/min, keyed callers 500/min. A call # TfL allows 50 req/min anonymous, 500 keyed. The odd call hangs, so time out
# normally takes 1-5s; the odd one hangs, so time out early and retry. # early and retry.
TFL_WORKERS = 12 TFL_WORKERS = 12
TFL_TIMEOUT_S = 15 TFL_TIMEOUT_S = 15
TFL_RATE_ANON = 48 TFL_RATE_ANON = 48
TFL_RATE_KEYED = 450 TFL_RATE_KEYED = 450
TFL_CACHE_TTL_S = 2 * 60 * 60 TFL_CACHE_TTL_S = 2 * 60 * 60
# Cycling estimate when TfL cycle routing isn't used: straight-line distance # Fallback cycling estimate: straight-line distance times a winding factor.
# times a road-winding factor, at a relaxed London pace.
CYCLE_ROUTE_FACTOR = 1.3 CYCLE_ROUTE_FACTOR = 1.3
CYCLE_KMH = 14.0 CYCLE_KMH = 14.0
# One process-wide Session so TLS handshakes and any cookies the upstreams set # One shared Session reuses TLS connections. pool_maxsize must cover the widest
# are reused across requests (a fresh Session per call roughly doubles latency). # fan-out (TfL workers plus every scan worker's page fetches).
# pool_maxsize must cover the widest possible fan-out - TfL workers plus every
# scan date worker running its own batch of Travelodge page fetches - otherwise
# urllib3 starts discarding connections and logging pool-full warnings.
_session = requests.Session() _session = requests.Session()
_session.mount( _session.mount(
"https://", "https://",
@@ -316,8 +249,7 @@ def _fetch_page(params: dict, start: int, deadline: float | None = None) -> list
r.raise_for_status() r.raise_for_status()
return r.json().get("results") or [] return r.json().get("results") or []
except (requests.RequestException, ValueError, AttributeError) as e: except (requests.RequestException, ValueError, AttributeError) as e:
# ValueError covers r.json() on a non-JSON body; AttributeError covers a # ValueError: non-JSON body. AttributeError: JSON that isn't an object.
# JSON body that is a list or scalar rather than an object (no .get).
raise UpstreamError(f"Travelodge search failed: {e}") from e raise UpstreamError(f"Travelodge search failed: {e}") from e
@@ -371,11 +303,8 @@ def fetch_hotels(location, checkin, checkout, rooms, deadline=None) -> list[dict
if not absorb(first) or len(first) < TL_PAGE_SIZE: if not absorb(first) or len(first) < TL_PAGE_SIZE:
return hotels return hotels
# Fetch TL_PAGE_BATCH pages at a time and stop on the first batch that is # Batches stop on a short page or an all-duplicate batch; sequential paging
# either short (a page with fewer than TL_PAGE_SIZE results is the last one) # would blow the time budget. TL_MAX_START guards against endless paging.
# or wholly duplicate. Requesting speculatively overshoots by up to a batch,
# but a strictly sequential walk of ~50 pages would blow the time budget.
# TL_MAX_START is a hard stop in case the API ever pages forever.
start = TL_PAGE_SIZE start = TL_PAGE_SIZE
with ThreadPoolExecutor(max_workers=TL_PAGE_BATCH) as ex: with ThreadPoolExecutor(max_workers=TL_PAGE_BATCH) as ex:
while start <= TL_MAX_START: while start <= TL_MAX_START:
@@ -420,8 +349,6 @@ def normalise_hotel(h: dict) -> dict:
} }
# (location, checkin, checkout, rooms) -> [normalised hotel dicts]. Bounded by
# count, and expired entries are swept on every write (the cache is small).
_tl_cache = TTLCache(TL_CACHE_TTL_S, max_entries=TL_CACHE_MAX) _tl_cache = TTLCache(TL_CACHE_TTL_S, max_entries=TL_CACHE_MAX)
@@ -430,25 +357,17 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
Failures are not cached. Callers must treat the returned dicts as read-only. Failures are not cached. Callers must treat the returned dicts as read-only.
""" """
# Case/whitespace-insensitive location so "Central London" and
# "central london " share one cache entry; rooms must be hashable, hence
# the tuple.
key = (location.strip().lower(), checkin, checkout, tuple(rooms)) key = (location.strip().lower(), checkin, checkout, tuple(rooms))
hit = _tl_cache.get(key) hit = _tl_cache.get(key)
if hit is not None: if hit is not None:
return hit return hit
# The fetch deliberately happens outside any cache lock: a slow upstream # Fetched outside any lock; a racing duplicate fetch is harmless.
# must not block other threads reading the cache. Two threads racing on the
# same key both fetch and the second write wins, which is harmless.
raw = fetch_hotels(location, checkin, checkout, rooms, deadline=deadline) raw = fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)
hotels = [normalise_hotel(h) for h in raw] hotels = [normalise_hotel(h) for h in raw]
# A response that parsed but yielded nothing usable is the fingerprint of a # Sold-out results still carry names and codes, so an empty shape means a
# renamed upstream field: the tolerant .get()s in `normalise_hotel` turn a # renamed upstream field.
# schema change into "no hotels available", which looks exactly like a
# sold-out search. Genuine sold-out inventory still carries names and codes,
# so warn only when the shape itself came back empty.
if raw and not any(h["code"] and h["name"] for h in hotels): if raw and not any(h["code"] and h["name"] for h in hotels):
log.warning( log.warning(
"Travelodge returned %d hotels for %r (%s..%s) but none had a usable " "Travelodge returned %d hotels for %r (%s..%s) but none had a usable "
@@ -539,9 +458,7 @@ def price_journey(journey, adults=1, railcard_holders=1):
if not non_walk: # walking only if not non_walk: # walking only
return 0, 0, "walk" return 0, 0, "walk"
# TfL omits the fare block entirely for some journeys (e.g. ones involving # No fare block means unpriceable: drop the option rather than call it free.
# a mode it cannot price). Returning None makes the caller drop this option
# rather than treat it as free.
if not fare or not fare.get("fares"): if not fare or not fare.get("fares"):
return None return None
@@ -549,11 +466,8 @@ def price_journey(journey, adults=1, railcard_holders=1):
for f in fare["fares"]: for f in fare["fares"]:
cost = f.get("cost") or 0 cost = f.get("cost") or 0
peak, offpeak = f.get("peak") or 0, f.get("offPeak") or 0 peak, offpeak = f.get("peak") or 0, f.get("offPeak") or 0
# Two independent bus tests, because TfL is inconsistent about which # TfL marks buses inconsistently, so test both ways; a Railcard
# it provides: a fare with neither a peak nor an off-peak price is a # discount must never reach a bus fare.
# flat bus fare by construction, and otherwise the tap records name the
# mode outright. Getting this wrong would apply a Railcard discount to
# a bus fare, which does not exist.
is_bus = (peak == 0 and offpeak == 0) or any( is_bus = (peak == 0 and offpeak == 0) or any(
(t.get("tapDetails") or {}).get("modeType") == "Bus" for t in (f.get("taps") or []) (t.get("tapDetails") or {}).get("modeType") == "Bus" for t in (f.get("taps") or [])
) )
@@ -562,13 +476,9 @@ def price_journey(journey, adults=1, railcard_holders=1):
out += cost * adults out += cost * adults
ret += cost * adults ret += cost * adults
else: else:
# Railcards give 1/3 off *off-peak* rail/tube fares only, so the # Railcards discount off-peak rail/tube only. chargeLevel is free
# outbound is discounted only when this fare is off-peak. That is # text that has varied, so also match cost == off-peak price. The
# detected two ways because chargeLevel is free text that has # return leg is always treated as off-peak.
# historically read "Off Peak", "Off-peak" or been absent: a
# substring match on "off", or the cost simply equalling the
# off-peak price. The return is always treated as off-peak (see the
# docstring), so it is always discounted for railcard holders.
level = (f.get("chargeLevel") or "").lower() level = (f.get("chargeLevel") or "").lower()
out_full = cost out_full = cost
ret_full = offpeak or cost # next-day return assumed off-peak ret_full = offpeak or cost # next-day return assumed off-peak
@@ -577,9 +487,7 @@ def price_journey(journey, adults=1, railcard_holders=1):
out += out_full * full_fare + out_disc * railcard_holders out += out_full * full_fare + out_disc * railcard_holders
ret += ret_full * full_fare + ret_disc * railcard_holders ret += ret_full * full_fare + ret_disc * railcard_holders
# Short human summary of the route, e.g. "rail > tube Victoria". Walking # e.g. "rail > tube Victoria", with walking legs dropped.
# legs are dropped as noise, and "national-rail" is shortened purely to fit
# the column in the UI.
parts = [] parts = []
for l in legs: for l in legs:
m = (l.get("mode") or {}).get("id") m = (l.get("mode") or {}).get("id")
@@ -648,9 +556,7 @@ def _limiter(app_key: str | None) -> RateLimiter:
return lim return lim
# journey key -> journeys. Unbounded on purpose (entries are small and a long # Unbounded on purpose (a long scan wants every entry); swept only when large.
# scan wants them all), so expired entries are only swept once it is large,
# keeping the common write O(1).
_tfl_cache = TTLCache(TFL_CACHE_TTL_S, sweep_above=5000) _tfl_cache = TTLCache(TFL_CACHE_TTL_S, sweep_above=5000)
@@ -700,9 +606,7 @@ def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=N
} }
if extra: if extra:
params.update(extra) params.update(extra)
# Coordinates are rounded to 5dp (~1m) so that floating-point noise in # 5dp (~1m) absorbs float noise. app_key doesn't affect the answer.
# otherwise identical requests still hits the cache. app_key is excluded
# from the key on purpose: the route and fare do not depend on it.
key = (round(frm[0], 5), round(frm[1], 5), round(to[0], 5), round(to[1], 5), params["date"], params["time"], key = (round(frm[0], 5), round(frm[1], 5), round(to[0], 5), round(to[1], 5), params["date"], params["time"],
tuple(sorted((extra or {}).items()))) tuple(sorted((extra or {}).items())))
hit = _tfl_cache.get(key) hit = _tfl_cache.get(key)
@@ -714,14 +618,8 @@ def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=N
url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}") url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}")
limiter = _limiter(app_key) limiter = _limiter(app_key)
journeys = None journeys = None
# Retry policy, all deadline-aware (a skipped sleep means the deadline is # Deadline-aware retries: network error or 5xx wait 2s, 429 backs off
# too close, so stop rather than hammer): # linearly, any other non-200 (e.g. 300 disambiguation) is cached as no route.
# network error -> wait 2s
# 429 rate limited -> linear backoff, 5s then 10s then 15s
# 5xx -> wait 2s
# any other non-200 (notably 300 "disambiguation", meaning TfL wants the
# caller to pick between candidate locations) -> treat as "no route",
# do not retry, and cache the empty result
for attempt in range(retries): for attempt in range(retries):
remaining = TFL_TIMEOUT_S if deadline is None else deadline - time.monotonic() remaining = TFL_TIMEOUT_S if deadline is None else deadline - time.monotonic()
if remaining < 1 or not limiter.acquire(deadline): if remaining < 1 or not limiter.acquire(deadline):
@@ -749,13 +647,9 @@ def _tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=N
journeys = [] journeys = []
break break
# journeys is still None only if every attempt was abandoned; return empty # Only a successful empty answer is cached; abandoned attempts can retry later.
# without caching so a later, less rushed call can try again. An empty list
# from a *successful* response is cached - "no route" is a real answer.
if journeys is None: if journeys is None:
return [], True return [], True
# TFL_CACHE_TTL_S is long because journey times and fares for a fixed
# date/time do not change.
_tfl_cache.set(key, journeys) _tfl_cache.set(key, journeys)
return journeys, False return journeys, False
@@ -786,10 +680,8 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
return _tfl_journeys(frm, to, when, extra, app_key, retries, deadline)[0] return _tfl_journeys(frm, to, when, extra, app_key, retries, deadline)[0]
# Two journey queries per hotel, because TfL's default "LeastTime" answer is # A second, bus-only query because TfL's fastest route is rarely the cheapest.
# usually a tube fare and the cheapest option is very often a slower bus. The # "walking" is required alongside "bus" or routes needing a walk are refused.
# bus query has to name "walking" alongside "bus" or TfL refuses routes that
# need a walk to the stop.
TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"})) TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"}))
CYCLE_QUERY = {"mode": "cycle"} CYCLE_QUERY = {"mode": "cycle"}
@@ -913,9 +805,8 @@ def cycle_time(origin, hotel, when, app_key, deadline=None, journeys=None):
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# Search # Search
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# Every transport column blanked out. Splatted into a row to reset it, so # Resets a reused row's transport fields; a new transport field must be added
# adding a transport field means adding it here too or it will leak a stale # here or a scan leaks a stale value between nights.
# value from a previous night when rows are reused in a scan.
_UNPRICED = { _UNPRICED = {
"transport_out": None, "transport_out": None,
"transport_return": None, "transport_return": None,
@@ -1044,8 +935,7 @@ def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_trave
fut = pool.submit(_tfl_journeys, origin, dest, depart_dt, extra, app_key, deadline=deadline) fut = pool.submit(_tfl_journeys, origin, dest, depart_dt, extra, app_key, deadline=deadline)
owner[fut] = (code, label) owner[fut] = (code, label)
if app_key: if app_key:
# Cycle routing costs a third rate-limited request, so it is # A third rate-limited request, so only with an API key.
# only asked for when a key lifts the anonymous budget.
entry["cycle"] = pool.submit( entry["cycle"] = pool.submit(
_tfl_journeys, origin, dest, depart_dt, CYCLE_QUERY, app_key, 1, deadline _tfl_journeys, origin, dest, depart_dt, CYCLE_QUERY, app_key, 1, deadline
) )
@@ -1066,9 +956,6 @@ def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_trave
abandoned = any(entry["fares"][lbl][1] for lbl, _ in TRANSPORT_QUERIES) abandoned = any(entry["fares"][lbl][1] for lbl, _ in TRANSPORT_QUERIES)
cyc = None cyc = None
if entry["cycle"] is not None: if entry["cycle"] is not None:
# Already submitted above, so this wait is usually over by
# now; waiting here (in the consumer, never in a worker) is
# safe with a single flat pool.
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline, cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline,
journeys=entry["cycle"].result()[0]) journeys=entry["cycle"].result()[0])
yield code, t, cyc, (t is None and abandoned) yield code, t, cyc, (t is None and abandoned)
@@ -1289,11 +1176,7 @@ def _scan_order(night_list):
best[code] = key best[code] = key
if code not in coords: if code not in coords:
coords[code] = {"code": code, "lat": row["lat"], "lon": row["lon"]} coords[code] = {"code": code, "lat": row["lat"], "lon": row["lon"]}
# The estimate is a pure function of the coordinates, so any
# night's row carries the same values.
cycle_base[code] = {k: row[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")} cycle_base[code] = {k: row[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")}
# sorted() is stable and `best` is in first-seen order, matching the old
# index-based ordering exactly.
ordered = [coords[code] for code in sorted(best, key=lambda c: best[c])] ordered = [coords[code] for code in sorted(best, key=lambda c: best[c])]
return ordered, cycle_base return ordered, cycle_base
@@ -1309,9 +1192,7 @@ def _scan_transport(*, ordered, cycle_base, transport, summary, origin, depart_d
for code, t, cyc, timed_out in _price_hotels( for code, t, cyc, timed_out in _price_hotels(
ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
): ):
# Transport here is night-independent, so there is no room price to add: # Night-independent: the dummy total is discarded.
# a dummy 0 is passed and the resulting "total" discarded. Each night
# computes its own total in phase 3.
fields = _transport_fields({"room_price": 0}, t) fields = _transport_fields({"room_price": 0}, t)
fields.pop("total", None) fields.pop("total", None)
if timed_out: if timed_out:
@@ -1320,9 +1201,7 @@ def _scan_transport(*, ordered, cycle_base, transport, summary, origin, depart_d
if cyc: if cyc:
fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc
else: else:
# No TfL cycle result: keep the local estimate computed when the # Keep the local estimate; these fields are copied to every night.
# rows were built, since these fields are copied wholesale onto
# every night's copy of this hotel.
fields.update(cycle_base.get(code, {})) fields.update(cycle_base.get(code, {}))
fields["code"] = code fields["code"] = code
transport[code] = fields transport[code] = fields
@@ -1361,9 +1240,7 @@ def _scan_totals(night_list, transport, summary) -> None:
n["best_code"] = best["code"] n["best_code"] = best["code"]
n["best_room"] = min(r["room_price"] for r in n["hotels"]) n["best_room"] = min(r["room_price"] for r in n["hotels"])
# Cheapest night first; nights with no total (failed, skipped, or unpriced) # Cheapest first; unpriced nights last, then by room price and date.
# fall to the bottom, ordered by best room price and then by date so the
# list is still deterministic.
night_list.sort( night_list.sort(
key=lambda n: ( key=lambda n: (
n["best_total"] is None, n["best_total"] is None,

Some files were not shown because too many files have changed in this diff Show More