1 Commits
Author SHA1 Message Date
renovate 386ff76bff Update alpine/git Docker tag to v2.54.0
renovate/stability-days Updates have met minimum release age requirement
Test and deploy / test (push) Successful in 9m44s
Test and deploy / deploy (push) Has been skipped
2026-11-16 04:05:14 +00:00
273 changed files with 7583 additions and 4120 deletions
+3 -51
View File
@@ -1,6 +1,6 @@
# .deprecated # .deprecated
STATUS: nothing in here is live. No compose file, Caddyfile or script STATUS: nothing in here is live. No compose file, nginx template or script
references this directory. It is kept, not deleted, in line with the repo's references this directory. It is kept, not deleted, in line with the repo's
"legacy is kept" convention; the full history is also in git. "legacy is kept" convention; the full history is also in git.
@@ -34,53 +34,5 @@ effectively root on the host. To bring it back, layer
`docker-compose.autoheal.yml` the same way as above. `docker-compose.autoheal.yml` the same way as above.
Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers
labelled `autoheal=true` (caddy; nginx until 2026-11-17). This copy is the old labelled `autoheal=true` (nginx). This copy is the old `all` variant, kept for
`all` variant, kept for reference. reference.
## nginx/ and certbot/
The public edge until 2026-11-17, when Caddy (`caddy/`) replaced both:
`nginx/` is the image (three templates chosen at start by `entrypoint.sh`,
the shared route table, the payload log and security-header includes), and
`certbot/entrypoint.sh` obtained and renewed the certificate that nginx
reloaded through a sentinel file. Their compose services were removed in
`daa2a46`. The last certbot certificate is still in `./certbot/conf` on the
host, valid until 2027-01-20.
To bring them back: revert the commit that moved them here and then `daa2a46`;
DEPLOYMENT.md §7 ("Roll back to nginx") has the commands.
## 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.
@@ -1,84 +0,0 @@
# =============================================================================
# .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
+57 -19
View File
@@ -16,12 +16,13 @@
# #
# 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 (the S3 key id and secret) are dummies in the exact shape it requires, or that service won't start. # a service parses (Garage's hex secrets, Gitea's base64 JWT keys, the S3 key
# 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 tracker database # with. Only POSTGRES_DB is created on a fresh volume; the gitea, jobs and
# and role still have to be created by hand (.env.example). # tracker databases and roles still have to be created by hand (.env.example).
# ============================================================================= # =============================================================================
# --- Postgres ---------------------------------------------------------------- # --- Postgres ----------------------------------------------------------------
@@ -30,19 +31,55 @@ 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 -------------------------------------------------------------------
# Dev has no Gitea: GITEA_HOST is pinned to a TEST-NET address that never # The two JWT secrets must decode as base64url of 32 bytes; these decode to
# answers, so the home page's git feed is empty (and /gitea/ redirects to # the text "dev-only-not-a-secret-0123456789".
# git.localhost, which goes nowhere). GITEA_HOST=gitea
GITEA_HOST=git.localhost
GITEA_PORT=3000 GITEA_PORT=3000
GITEA_UPSTREAM=192.0.2.1 GITEA_INTERNAL_TOKEN=dev-gitea-internal-token
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
@@ -82,13 +119,12 @@ LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ---------------------------------------------------------- # --- TLS / identity ----------------------------------------------------------
# DOMAIN is also the auth cookie's domain, so it must be the host the browser # DOMAIN is also the auth cookie's domain, so it must be the host the browser
# is on. Nothing reads EMAIL any more (it was certbot's). # is on. certbot is disabled in dev, so EMAIL is never used.
DOMAIN=localhost DOMAIN=localhost
EMAIL=[email protected] EMAIL=[email protected]
# --- Cloudflare Tunnel ------------------------------------------------------- # --- Cloudflare Tunnel -------------------------------------------------------
# cloudflared is disabled in dev, and dev's Caddy sites use `tls internal`, # cloudflared is disabled in dev and certbot with it.
# so neither token is ever used.
CLOUDFLARE_TUNNEL_TOKEN=dev-dummy-tunnel-token CLOUDFLARE_TUNNEL_TOKEN=dev-dummy-tunnel-token
CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token
@@ -107,6 +143,9 @@ 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
@@ -118,16 +157,15 @@ TRACKER_TZ=Europe/London
TFL_APP_KEY=dev-dummy-tfl-key TFL_APP_KEY=dev-dummy-tfl-key
# --- Garage object store (public /uploads/, on stpcore) ----------------------- # --- Garage object store (public /uploads/) -----------------------------------
# Uploads fall back to the `uploads` volume unless a dev stpcore is running # Shapes Garage enforces: 64 hex for the RPC secret, "GK" + 24 hex for the key
# with LAN_BIND=172.17.0.1 and these same dummy values (see stpcore's README). # id, 64 hex for the secret. Uploads fall back to the `uploads` volume until
# Shapes Garage enforces: "GK" + 24 hex for the key id, 64 hex for the secret. # garage/bootstrap.sh has imported this key and created the bucket.
GARAGE_UPSTREAM=host-gateway GARAGE_RPC_SECRET=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
GARAGE_WEBUI_TOKEN=dev-garage-webui-token GARAGE_ADMIN_TOKEN=dev-garage-admin-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
+143 -79
View File
@@ -7,9 +7,10 @@
# it parses the file, before any container exists. This is how container # it parses the file, before any container exists. This is how container
# names and published ports are built. # names and published ports are built.
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment # 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
# variables inside that container. backend, db and icecast2 do this. # variables inside that container. nginx, backend, db, icecast2,
# The `python` service deliberately does neither wholesale — each # certbot and gitea all do this.
# uses an explicit `environment:` allow-list, so it never sees the site's # The `python` and `jobs` services deliberately do neither wholesale — each
# uses an explicit `environment:` allow-list, so neither sees the site's
# database password, the JWT secret, or any key it does not use. # database password, the JWT secret, or any key it does not use.
# #
# HOW TO USE # HOW TO USE
@@ -20,7 +21,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 service reads it, add it to that service's # starting. If the python or jobs 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,45 +34,116 @@
# ============================================================================= # =============================================================================
# --- Postgres ---------------------------------------------------------------- # --- Postgres ----------------------------------------------------------------
# One instance, two databases: POSTGRES_DB for the Go backend and # One instance, four databases: POSTGRES_DB for the Go backend,
# POSTGRES_TRACKER_DB for the activity tracker (with its own role). The job # POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker and
# tracker and Gitea have their own Postgres on stppriv and stpgit. Only # POSTGRES_TRACKER_DB for the activity tracker (each of the last two with its
# POSTGRES_DB is auto-created on first init; the tracker database must be # own role). Only POSTGRES_DB is auto-created on first init; the others must
# created by hand on a fresh volume (the ccp README has the commands). # be created by hand on a fresh volume (the job-tracker and ccp READMEs have
# 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 runs in its own LXC (the adamf/stpgit repo, whose variables are in its # GITEA_HOST is the container name AND the nginx upstream host.
# .env.example); this stack has no Gitea container. GITEA_HOST is its public # The three secrets below are passed as GITEA__section__KEY overrides so the
# name, used on its plain-HTTP port GITEA_PORT by Caddy's /v2/, the backend's # committed app.ini.template can keep those fields blank. Generate each as a
# feed and usaco, and as the SSH host for silverbullet-git. GITEA_UPSTREAM is # long random hex string.
# the LXC's LAN IP, which those containers pin GITEA_HOST to (extra_hosts), so GITEA_HOST=gitea
# 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_UPSTREAM= GITEA_INTERNAL_TOKEN=
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=
# --- Services that nginx substitutes but no longer runs -----------------------
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
# compose service uses them today. Harmless if blank.
# --- SilverBullet (notes) --------------------------------------------------- # --- SilverBullet (notes) ---------------------------------------------------
# The public read-only notes site at /notes/. The editor, and the vault's only # Two instances over the same vault: the admin-only editor at /sb/, and the
# writer, is stppriv (priv.DOMAIN/sb/); silverbullet-git here only pulls. # public read-only notes site at /notes/ (which replaced Quartz). All four
# Both default in docker-compose.yml. # default in nginx/entrypoint.sh and docker-compose.yml, so they can be left
# 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 pulls (default 300). # Seconds between notes commit/push cycles (default 300).
SILVERBULLET_GIT_INTERVAL= SILVERBULLET_GIT_INTERVAL=
# --- Go backend -------------------------------------------------------------- # --- Go backend --------------------------------------------------------------
# BACKEND_HOST is the container name and the Caddy upstream. # BACKEND_HOST is the container name and the nginx upstream.
# BACKEND_ENDPOINT is the public URL prefix Caddy mounts the API at and then # BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then
# strips; the Vue app's GraphQL client assumes /api. # strips; the Vue app's GraphQL client assumes /api.
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs # BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
# everyone out. # everyone out.
@@ -81,8 +153,8 @@ BACKEND_SECRET=
BACKEND_ENDPOINT=/api BACKEND_ENDPOINT=/api
# --- Obsidian vault ---------------------------------------------------------- # --- Obsidian vault ----------------------------------------------------------
# HOST path, interpolated straight into the bind mounts: read-write into # HOST path, interpolated straight into the bind mounts: read-write into the
# silverbullet-git (which pulls it), read-only into the backend and # backend, silverbullet and silverbullet-git, read-only into
# 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=
@@ -101,7 +173,7 @@ SPOTIFY_AUTH_STATE=
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast # ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
# with it, and a live-broadcasting client authenticates to the liquidsoap # with it, and a live-broadcasting client authenticates to the liquidsoap
# harbor port with it. Anyone holding it can take over the stream. # harbor port with it. Anyone holding it can take over the stream.
# LIQUIDSOAP_HARBOR_PORT is the only non-Caddy port published to the host. # LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host.
ICECAST_SOURCE_PASSWORD= ICECAST_SOURCE_PASSWORD=
ICECAST_RELAY_PASSWORD= ICECAST_RELAY_PASSWORD=
ICECAST_ADMIN_USER= ICECAST_ADMIN_USER=
@@ -113,11 +185,9 @@ LIQUIDSOAP_HARBOR_MOUNT=/live
LIQUIDSOAP_HARBOR_PORT=8001 LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ---------------------------------------------------------- # --- TLS / identity ----------------------------------------------------------
# DOMAIN is the APEX domain with no scheme and no www; Caddy gets a # DOMAIN is the APEX domain with no scheme and no www; certbot requests both
# certificate for it and for www.DOMAIN, and canonicalises to www. # it and www.DOMAIN on one certificate, and nginx canonicalises to www.
# EMAIL was certbot's Let's Encrypt account address. Nothing reads it since # EMAIL is the Let's Encrypt account address for expiry notices.
# the move to Caddy, which registers its ACME account without one; it stays
# for the nginx/certbot rollback (.deprecated/, DEPLOYMENT.md §7).
DOMAIN= DOMAIN=
EMAIL= EMAIL=
@@ -128,19 +198,17 @@ EMAIL=
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves # dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
# the container restarting with an error and the site reachable directly. # the container restarting with an error and the site reachable directly.
CLOUDFLARE_TUNNEL_TOKEN= CLOUDFLARE_TUNNEL_TOKEN=
# Cloudflare API token for Caddy's DNS-01 challenge (caddy/sites/prod.caddy): # Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API
# My Profile -> API Tokens -> Create Token -> "Edit zone DNS", limited to this # Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the
# zone, then add Zone -> Zone -> Read on the same zone (the template only has # certificate renews without any inbound port, so the router's 80/443
# DNS -> Edit). Certificates are issued and renewed with no inbound port, so # forwards can close. Blank falls back to HTTP-01 on port 80.
# the router forwards nothing. Required in production: Caddy has no HTTP
# challenge to fall back to. Changing it needs `docker compose up -d caddy`.
CLOUDFLARE_DNS_API_TOKEN= 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 usaco # pipeline's classifier. The backend no longer calls Claude itself. The jobs
# container gets the same key for its own calls. # and usaco containers get the same key for their 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
@@ -158,6 +226,12 @@ 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
@@ -188,12 +262,13 @@ 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,
# (`usaco-audio` on stpcore), never `uploads` (that one is served publicly at # never `uploads` (that one is served publicly at /uploads/). Its own key,
# /uploads/). Its own key, same shapes as S3_ACCESS_KEY_ID / # same shapes as S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY above. With the
# S3_SECRET_ACCESS_KEY below. With the key blank the recordings are thrown # key blank the recordings are thrown away once transcribed. One-off setup:
# away once transcribed. Put the same pair in stpcore's .env and run its # docker compose exec -T garage /garage bucket create usaco-audio
# garage/bootstrap.sh, which creates the bucket and imports the key. # docker compose exec -T garage /garage key import -n usaco-site --yes "$USACO_S3_ACCESS_KEY_ID" "$USACO_S3_SECRET_ACCESS_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=
@@ -207,54 +282,43 @@ TRACKER_TZ=Europe/London
# --- Receipt printer (/receipt/) --------------------------------------------- # --- Receipt printer (/receipt/) ---------------------------------------------
# Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi, # Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi,
# which reaches the printer over the home LAN, and Caddy proxies to it over # which reaches the printer over the home LAN, and nginx proxies to it over
# Tailscale. # Tailscale.
# host:port of that server, by Tailscale IP. Blank points nowhere and # host:port of that server, by Tailscale IP. Blank points nowhere and
# /receipt/ answers "offline". # /receipt/ answers "offline".
RECEIPT_WEB_UPSTREAM=100.107.152.119:8765 RECEIPT_WEB_UPSTREAM=100.107.152.119:8765
# Shared secret Caddy adds as X-Receipt-Token; the same value as # Shared secret nginx adds as X-Receipt-Token; the same value as
# RECEIPT_WEB_TOKEN in stppi's ~/.config/receipt-web.env. Generate with # RECEIPT_WEB_TOKEN in stppi's ~/.config/receipt-web.env. Generate with
# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`. # `openssl rand -hex 32`. Changing it needs `docker compose up -d nginx`.
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) ----------------------------------------------
# A separate compose project on this host (adamf/cto, `make stpvm`), whose web
# container joins app-network as `radar-web`. Only set this to point
# radar.DOMAIN somewhere else.
# RADAR_UPSTREAM=radar-web:80
# TfL Unified API key (500 req/min); used by the Python hotel finder # TfL Unified API key (500 req/min); used by the Python hotel finder
TFL_APP_KEY= TFL_APP_KEY=
# --- Garage object store (public /uploads/, on stpcore) ----------------------- # --- Garage object store (public /uploads/) -----------------------------------
# Garage runs on the stpcore LXC (adamf/stpcore); its README is the runbook # See garage/garage.toml and DEPLOYMENT.md ("Garage"). Everything here is
# and its .env holds Garage's own secrets. Everything here is optional for # optional for the site to run: with S3_ENDPOINT blank the backend keeps
# the site to run: with S3_ENDPOINT blank, or stpcore down, the backend # writing uploads to the `uploads` volume exactly as before.
# writes uploads to the `uploads` volume and Caddy serves them from there.
# #
# stpcore's LAN IP: the name `garage` is pinned to it in caddy, backend and # Garage's own secrets, passed to the garage and garage-webui containers.
# usaco. `host-gateway` in dev. Blank means 127.0.0.1, which fails fast. # Generate each with `openssl rand -hex 32`. The RPC secret must never change
GARAGE_UPSTREAM= # once the node has data; the admin token unlocks garage-webui's whole API.
# Shared secret Caddy adds as X-Core-Token on /garage/, after the admin GARAGE_RPC_SECRET=
# gate; the same value as GARAGE_WEBUI_TOKEN in stpcore's .env. GARAGE_ADMIN_TOKEN=
# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`. # The backend's S3 access, imported into Garage by garage/bootstrap.sh.
GARAGE_WEBUI_TOKEN= # Garage only accepts this shape:
# 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. http://garage:3900 stores new public uploads # Blank keeps uploads on disk. Set to http://garage:3900 (after running
# in the bucket; recreate the backend after changing it. If a write to Garage # garage/bootstrap.sh) to store new public uploads in the bucket; recreate the
# fails the backend logs it and writes to disk instead. # backend after changing it. If a write to Garage fails the backend logs it and
# writes to disk instead, and nginx serves the file from there.
S3_ENDPOINT= S3_ENDPOINT=
# Optional; these defaults match stpcore's garage.toml and bootstrap.sh. # Optional; these defaults match 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=
+101 -41
View File
@@ -1,11 +1,46 @@
# `test` runs on every push, on the build VM (stpbuild, label `build`); # =============================================================================
# `deploy` runs for main only after it passes, on stpvm (`self-hosted`), # deploy.yaml — test every push; deploy pushes to main that pass.
# since it recreates the stack there. #
# The runner is in host mode with only git and docker on the host, so Go and # TWO JOBS
# Python run in containers pinned to the same images as their Dockerfiles # test runs on every push, to any branch: `go vet` + `go test` for the
# (bump together), and checkout is plain git rather than actions/checkout. # backend and pytest for the Python service. These are the same
# The Vue build isn't tested here: a failed image build in `up --build` # checks as `make check-backend` and `make check-python`.
# aborts before any container is replaced. # deploy runs only for refs/heads/main, and only if `test` passed
# (`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:
@@ -13,20 +48,22 @@ on:
jobs: jobs:
test: test:
runs-on: build runs-on: self-hosted
env: env:
# Via env so a branch name is never parsed as shell. # The commit and ref this push delivered. Passed through env rather
# 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 }}
# Over HTTP with the job's own token (read access to this repo while REMOTE: ssh://git@localhost:2222/adamf/web_server.git
# the job runs), so the runner needs no SSH key or Gitea user. GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
REMOTE: http://git.adam-french.co.uk:3000/adamf/stpweb.git # Bare repo kept between runs so each fetch is incremental (the
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} # history is ~140MB; a fresh clone per push would be slow on the
# Kept between runs so fetches are incremental. # Pi's SD card). Lives outside the deploy directory on purpose.
CACHE: /home/adamf/.cache/stpweb-ci/repo.git CACHE: /home/adamf/.cache/web_server-ci/repo.git
# Per run, not just per commit: the build runner takes two jobs at # This run's source tree, exported from the cache and removed in
# once, and the same commit pushed to two branches runs twice. # the last step. Keyed by commit so two runs cannot share a tree.
SRC: /home/adamf/.cache/stpweb-ci/src-${{ github.sha }}-${{ github.run_id }} SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }}
steps: steps:
- name: Export the pushed commit to a scratch directory - name: Export the pushed commit to a scratch directory
shell: bash shell: bash
@@ -34,24 +71,33 @@ 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"
# $SHA, not FETCH_HEAD: test this run's commit even if the # Fetch the pushed ref, then export the exact pushed commit.
# branch has moved on. # Using $SHA rather than FETCH_HEAD means that if the branch
# The job's token as a Basic auth header, passed via env rather # has moved on since this run was queued we still test the
# than -c so it never shows in the process list. # commit this run is about, not a newer one.
auth=$(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0) git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
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"
# In case the shell lacks pipefail. # Do not rely on the shell having pipefail: if the archive
# 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"
# Read-only so root in the container can't leave files the # The whole repo is mounted read-only. Tests write only to
# clean-up step can't delete. The named volumes are Go caches. # t.TempDir(), and a read-only mount means the container (root)
# 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: |
@@ -59,12 +105,17 @@ jobs:
docker run --rm \ docker run --rm \
-v "$SRC":/src:ro \ -v "$SRC":/src:ro \
-w /src/backend \ -w /src/backend \
-v stpweb_ci_gomod:/go/pkg/mod \ -v web_server_ci_gomod:/go/pkg/mod \
-v stpweb_ci_gobuild:/root/.cache/go-build \ -v web_server_ci_gobuild:/root/.cache/go-build \
golang:1.26 \ golang:1.26 \
sh -c 'go vet ./... && go test ./...' sh -c 'go vet ./... && go test ./...'
# Read-only source, so bytecode and the pytest cache are off. # requirements-dev.txt pulls in requirements.txt plus pytest. The
# 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: |
@@ -72,33 +123,41 @@ jobs:
docker run --rm \ docker run --rm \
-v "$SRC":/src:ro \ -v "$SRC":/src:ro \
-w /src/python \ -w /src/python \
-v stpweb_ci_pip:/root/.cache/pip \ -v web_server_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/stpweb working-directory: /home/adamf/deploy/web_server
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/stpweb git config --global --add safe.directory /home/adamf/deploy/web_server
git fetch ssh://git@git.adam-french.co.uk:2222/adamf/stpweb.git main git fetch ssh://git@localhost:2222/adamf/web_server.git main
# Deploy only the tested commit; a newer main gets its own # Deploy only the commit the test job just passed. If main
# run. This also stops a re-run rolling the site back. # has moved on since this run started, FETCH_HEAD is a newer
# 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."
@@ -107,10 +166,11 @@ 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/stpweb working-directory: /home/adamf/deploy/web_server
env: env:
COMPOSE_BAKE: "false" COMPOSE_BAKE: "false"
# Shared with maintenance.yaml so the two never run compose at once. # The lock is shared with maintenance.yaml, so a deploy and the
# 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
+15 -6
View File
@@ -2,7 +2,9 @@ name: Weekly Maintenance
on: on:
schedule: schedule:
# Restarts dockerd, so it runs when nobody is likely mid-edit. # 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and
# 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:
@@ -22,14 +24,21 @@ jobs:
- name: Autoremove obsolete packages - name: Autoremove obsolete packages
run: sudo apt-get -y autoremove --purge run: sudo apt-get -y autoremove --purge
# .compose.lock is shared with deploy.yaml, so two compose runs # Both compose steps below take .compose.lock, the same flock
# never race. Taken per step to keep deploys from waiting long. # deploy.yaml holds while it runs compose. Without it this weekly
# 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/stpweb working-directory: /home/adamf/deploy/web_server
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/stpweb working-directory: /home/adamf/deploy/web_server
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
@@ -40,7 +49,7 @@ jobs:
- name: Show running containers - name: Show running containers
run: docker compose ps run: docker compose ps
working-directory: /home/adamf/deploy/stpweb working-directory: /home/adamf/deploy/web_server
- name: Show disk usage after - name: Show disk usage after
run: df -h / run: df -h /
+43 -10
View File
@@ -1,20 +1,53 @@
# Weekly Renovate run (config in /renovate.json5), on the build VM (stpbuild, # =============================================================================
# label `build`). --network host uses the # renovate.yaml — weekly dependency-update PRs, opened against this repo.
# host's /etc/hosts pin to reach Gitea on the LAN, and RENOVATE_GIT_URL=endpoint #
# stops it cloning via the public ROOT_URL. Secrets are passed as bare `-e NAME` # Renovate stands in for Dependabot, which does not exist outside GitHub. What
# so they never appear in the process list. Gitea refuses secret names starting # it updates is configured in /renovate.json5; this file is only how it runs.
# 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 nginx 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:
# Clear of the Sunday maintenance rebuild. # 04:00 UTC Monday: clear of the Sunday 05:00 maintenance rebuild, and
# 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: build runs-on: self-hosted
steps: steps:
- name: Run Renovate - name: Run Renovate
shell: bash shell: bash
@@ -29,9 +62,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://git.adam-french.co.uk:3000/api/v1 \ -e RENOVATE_ENDPOINT=http://localhost:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \ -e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv,adamf/stpcore,adamf/stprunner \ -e RENOVATE_REPOSITORIES=adamf/web_server \
-e RENOVATE_TOKEN \ -e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \ -e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \ -e LOG_LEVEL=info \
+4 -14
View File
@@ -1,13 +1,10 @@
icecast2/fallback_music/* icecast2/fallback_music/*
.claude/ .claude/
!icecast2/fallback_music/.gitkeep !icecast2/fallback_music/.gitkeep
# The retired certbot's data (code in .deprecated/certbot/), still on the
# host as the rollback certificate
certbot/conf certbot/conf
certbot/www certbot/www
# Caddy's certificates, keys and ACME account (docker-compose.yml)
caddy/data/
backend/token/ backend/token/
jobs-data/
usaco-data/ usaco-data/
.env .env
.env.bak .env.bak
@@ -15,19 +12,12 @@ 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's pre-move state, kept as the rollback (.deprecated/gitea/README) gitea/data/*
.deprecated/gitea/data/ gitea/config/app.ini
.deprecated/gitea/config/
.deprecated/gitea/dev-leftovers/
# The old runner directory: gone from git, but still on stpvm holding the # Gitea runner
# 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
+11 -13
View File
@@ -10,7 +10,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
make check make check
``` ```
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, `docker compose config` for both compose files, and the Caddy image build, which validates `caddy/` for both modes. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`, `check-caddy`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it. Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it.
### Full stack (dev mode, HTTP only) ### Full stack (dev mode, HTTP only)
@@ -19,7 +19,7 @@ cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
``` ```
`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and 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. `.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
### Full stack (production, HTTPS) ### Full stack (production, HTTPS)
@@ -57,17 +57,15 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies. **Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served 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 through Nginx (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, `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. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
**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/`. **Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
**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. **Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Uploads / Garage** (Garage 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. **Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public.
**Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit <zone> <events> <window>`) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea 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
@@ -95,12 +93,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` (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). - **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`. - **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`. - **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. 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. nginx's *permission gate* (`set $auth_permission <key>; auth_request /internal/auth/validate;`, see `nginx/nginx_routes.conf.template`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its location from the admin gate to the permission gate. `/auth/validate-admin` and the admin gate are unchanged.
- **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 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. - **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor.
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API. - **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
- **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.
@@ -116,7 +114,7 @@ Each area has its own README with the detail that doesn't belong here:
## Conventions ## Conventions
- **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. - **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
- **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.
+307 -416
View File
File diff suppressed because it is too large Load Diff
+60 -16
View File
@@ -1,17 +1,41 @@
# `make check` before pushing; `make help` lists targets. A missing toolchain # =============================================================================
# fails only the targets that need it. # Makefile — one place for the commands that verify and run this repo.
#
# 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
# 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
# At the root, not in python/, which is a docker build context. # The virtualenv for the Python checks. At the repo root rather than inside
# 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
# Re-installs only when a requirements file changes. # Written after a successful install. Being a file target that depends on both
# 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 generate dev
help: help:
@echo "Targets:" @echo "Targets:"
@@ -20,16 +44,20 @@ help:
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)" @echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
@echo " make check-vue vite build of vue/ into a throwaway directory" @echo " make check-vue vite build of vue/ into a throwaway directory"
@echo " make check-compose validate docker-compose.yml, alone and with the dev override" @echo " make check-compose validate docker-compose.yml, alone and with the dev override"
@echo " make check-caddy build the Caddy image, which validates caddy/ for prod and dev"
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit" @echo " make 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)"
check: check-backend check-python check-vue check-compose check-caddy # Run with `make -k check` to keep going past the first failing area.
check: check-backend check-python check-vue check-compose
check-backend: check-backend:
cd backend && go vet ./... && go test ./... cd backend && go vet ./... && go test ./...
# Recreated from scratch so packages dropped from the files don't linger. # requirements-dev.txt `-r`-includes requirements.txt, so one install covers
# 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)
@@ -40,7 +68,11 @@ $(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
# Builds into a temp directory, so vue/dist is never touched. # A Vite build is enough to catch a broken import or template; there is no
# 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"; \
@@ -48,9 +80,22 @@ 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
# Without a .env, validates against a temp project dir holding .env.example # Validates the compose files: YAML, schema, and that every ${VAR} they
# (compose refuses a missing env_file, and a blank OBSIDIAN_DIR is an invalid # interpolate resolves to something usable.
# 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 \
@@ -66,12 +111,11 @@ 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 image build runs `caddy validate` for both modes. # Rewrites backend/graph/generated.go and graph/model/models_gen.go from
check-caddy: # graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
docker build -q -t stpweb-caddy:check caddy/
generate: generate:
cd backend && go run github.com/99designs/gqlgen generate cd backend && go run github.com/99designs/gqlgen generate
# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx.
dev: 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
+51 -30
View File
@@ -1,3 +1,4 @@
Gay bal;;s
# My Web # My Web
![screenshot](vue/public/img/screenshot.png) ![screenshot](vue/public/img/screenshot.png)
@@ -14,18 +15,20 @@ After hearing all the hype on LinkedIn and feeling the pressure to keep up a hig
## Architecture ## Architecture
All services run in Docker containers orchestrated by Docker Compose behind Caddy as a reverse proxy on a single bridge network. (nginx and certbot did that job until 2026-11-17.) All services run in Docker containers orchestrated by Docker Compose behind Nginx as a reverse proxy on a single bridge network.
``` ```
vue ── Frontend build (outputs dist to shared volume) vue ── Frontend build (outputs dist to shared volume)
caddy (80, 443) ── Frontend SPA + Reverse Proxy + TLS certificates nginx (80, 443) ── Frontend SPA + Reverse Proxy
backend (8080) ── Go API (GraphQL + REST) backend (8080) ── Go API (GraphQL + REST)
db (5432) ── PostgreSQL 16 db (5432) ── PostgreSQL 16
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap) icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
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 ── Pulls the notes repo (the editor and its pushes are on stppriv) silverbullet-git ── Commits/pushes notes edits to the notes repo
python (8000) ── Python API (FastAPI) python (8000) ── Python API (FastAPI)
certbot ── SSL Certificate Management (disabled in dev)
``` ```
## Tech Stack ## Tech Stack
@@ -36,7 +39,7 @@ python (8000) ── Python API (FastAPI)
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2 **Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
**Infrastructure** - Docker Compose, Caddy, Let's Encrypt (DNS-01 via Cloudflare), Cloudflare Tunnel, Gitea + Act Runner **Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner
## Features ## Features
@@ -51,9 +54,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: runs on stppriv (`priv.<DOMAIN>/jobs/`), from the `adamf/job-tracker` repo - Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only) - Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
- Admin-gated routes: `/tracker`, `/dozzle`, `/garage` and more require the admin session, checked by Caddy's `forward_auth` against the backend - Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request`
- 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)
@@ -66,10 +69,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` | 301 to the job tracker on stppriv | | `/cv/jobs` | Job application tracker (admin-only, hidden print) |
| `/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/` | 301 to the note editor on stppriv (`priv.<DOMAIN>/sb/`) | | `/sb/` | Obsidian note editor (via SilverBullet, admin-only) |
| `/shrines` | Fan shrine index + individual shrines | | `/shrines` | Fan shrine index + individual shrines |
## API ## API
@@ -120,7 +123,7 @@ python (8000) ── Python API (FastAPI)
| POST | `/api/auth/refresh` | Refresh token | | POST | `/api/auth/refresh` | Refresh token |
| GET | `/api/auth/check` | Check token validity | | GET | `/api/auth/check` | Check token validity |
| POST | `/api/auth/logout` | Logout | | POST | `/api/auth/logout` | Logout |
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Caddy's `forward_auth` admin gate) | | GET | `/api/auth/validate-admin` | Validate admin JWT (used by Nginx auth_request) |
Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry. Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry.
@@ -171,7 +174,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
| --- | --- | --- | | --- | --- | --- |
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) | | GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
### Proxy Routes (Caddy) ### Nginx Proxy Routes
| Route | Target | Notes | | Route | Target | Notes |
| ---------- | ------------ | ------------------------------------------ | | ---------- | ------------ | ------------------------------------------ |
@@ -179,11 +182,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`, `/jobs` | 301 to `priv.<DOMAIN>` | Editor and job tracker, on stppriv | | `/sb` | silverbullet:3000 | Obsidian notes editor (admin-only) |
| `/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 |
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. `/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
### Deprecated Endpoints ### Deprecated Endpoints
@@ -212,9 +215,14 @@ 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 pulls (defaults to `300`) | | `SILVERBULLET_GIT_INTERVAL` | Seconds between notes commit/push cycles (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 |
@@ -244,7 +252,13 @@ Create a `.env` file in the project root. All services read from this file.
### Gitea Config ### Gitea Config
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`). Copy from the template and fill in secrets:
```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
@@ -254,23 +268,25 @@ Gitea is not part of this stack. It runs in its own LXC from the `adamf/stpgit`
### 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 a pull-only clone of the notes repo (`silverbullet-git`, `SYNC_MODE=pull`), 2. The vault is mounted read-write into `silverbullet` at `/data`, which serves it as an
mounted read-only into `silverbullet-public`, which serves it publicly at `/notes/` with editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at
`SB_READ_ONLY`. The editor, and the vault's only writer, is on stppriv (`priv.<DOMAIN>/sb/`) `/notes/` with `SB_READ_ONLY`
3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off 3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off
`/notes/` by `SB_SPACE_IGNORE` **and** Caddy deny rules — the Caddy rules are the ones that `/notes/` by `SB_SPACE_IGNORE` **and** nginx deny blocks — the nginx blocks are the ones that
actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary") actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary")
4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above) 4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above)
### TLS certificates ### SSL Certificates (Certbot)
Caddy obtains and renews them itself, over DNS-01 through the Cloudflare API, so no port has to be reachable from the internet: **Initial setup (production):**
1. Set `DOMAIN` and `CLOUDFLARE_DNS_API_TOKEN` in `.env` (the token needs Zone → Zone → Read and Zone → DNS → Edit on the zone) 1. Set `DOMAIN` and `EMAIL` in `.env`
2. `docker compose up -d`. Caddy serves immediately and fetches both certificates (apex and www) into `./caddy/data` within seconds 2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/`
3. Renewal is automatic and needs no restart 3. Certbot requests a certificate via `certbot certonly --webroot`
4. Once the certificate is issued to `certbot/conf/live/<DOMAIN>/`, restart Nginx — it will detect the certs and switch to the full `nginx.conf.template`
5. Certbot checks for renewal every 12 hours automatically
**Dev mode:** Caddy issues a certificate for localhost from its own local CA. **Dev mode:** Nginx generates a self-signed certificate for localhost automatically.
### Icecast Radio ### Icecast Radio
@@ -278,7 +294,9 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
### Gitea Runner ### 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. 1. Download the `act_runner` binary from [Gitea releases](https://gitea.com/gitea/act_runner/releases) and place in `gitea-runner/`
2. Set `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`
3. The runner registers automatically on first startup
## Dev Mode ## Dev Mode
@@ -291,9 +309,9 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
This: This:
- Loads Caddy's dev sites (`caddy/sites/dev.caddy`): all the same routing (SPA via Vite, backend proxy, radio, gitea, etc.) on both http and https, with no redirects or security headers - Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.)
- Uses a localhost certificate from Caddy's local CA - Generates a self-signed certificate for localhost
- Disables the Cloudflare tunnel - Disables certbot
- Seeds the database with test data (`SEED_DB=true`) - Seeds the database with test data (`SEED_DB=true`)
- Enables GraphQL playground and introspection - Enables GraphQL playground and introspection
@@ -313,7 +331,7 @@ Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets defaul
make check make check
``` ```
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build, `docker compose config` validation and the Caddy image build, which validates the edge config. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`. Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass. The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass.
@@ -324,9 +342,12 @@ These files are git-ignored and must be created manually:
| File | Notes | | File | Notes |
| ------------------------------- | --------------------------------------------------------------- | | ------------------------------- | --------------------------------------------------------------- |
| `.env` | See setup section above | | `.env` | See setup section above |
| `caddy/data/` | Created automatically by Caddy (certificates and their keys) | | `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
| `certbot/conf/`, `certbot/www/` | Created automatically by certbot; use dev mode to skip |
| `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
+33 -3
View File
@@ -1,5 +1,32 @@
# Static binary (CGO_ENABLED=0) on a slim base. ca-certificates for outbound # =============================================================================
# HTTPS; the cache mounts keep rebuilds fast. # Go backend image — multi-stage: build with the full toolchain, ship a slim
# 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.
# nginx 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
@@ -17,7 +44,10 @@ RUN --mount=type=cache,target=/go/pkg/mod \
FROM debian:bookworm-slim FROM debian:bookworm-slim
# For the compose healthcheck. # wget is not just for humans: the compose healthcheck probes the server with
# `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/*
+17 -20
View File
@@ -1,11 +1,11 @@
# Backend # Backend
The Go API for adam-french.co.uk. It is one process behind Caddy, serving a The Go API for adam-french.co.uk. It is one process behind nginx, serving a
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
that needs Claude is asked of the Python service, not called from here. that needs Claude is asked of the Python service, not called from here.
Caddy strips the `/api` prefix before proxying, so a browser request to Nginx strips the `/api` prefix before proxying, so a browser request to
`/api/graphql` arrives here as `/graphql`. Every path below is as this service `/api/graphql` arrives here as `/graphql`. Every path below is as this service
sees it. sees it.
@@ -33,12 +33,12 @@ graph/ GraphQL layer
## Request lifecycle ## Request lifecycle
1. Caddy terminates TLS, applies its own rate limits, strips `/api`, and 1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
proxies to this service. proxies to this service.
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so 2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
that `ClientIP()` — which the login rate limiter keys on — cannot be that `ClientIP()` — which the login rate limiter keys on — cannot be
spoofed via `X-Forwarded-For`. spoofed via `X-Forwarded-For`.
3. **REST**: the route's middleware chain runs. `AuthMiddleware` requires a 3. **REST**: the route's middleware chain runs. `AuthMiddlewear` 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,17 +55,17 @@ 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` and `tv`; - `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary
- `refresh_token` (90 days) carries `id` and `tv`. requests authorise without a database hit;
Every check loads the user row (one SELECT) to compare `tv`, and takes - `refresh_token` (365 days) carries only `id`.
`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, so the 90 days slide while the account is in use. token for a new pair, re-reading the user — and therefore the admin flag —
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.
- `GET /auth/validate/:permission` is the same for one named permission - `GET /auth/validate/:permission` is the same for one named permission
(200 / 403 / 401, and 404 for a key that does not exist). It backs Caddy's (200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
*permission gate*, which lets a non-admin account into one service — the *permission gate*, which lets a non-admin account into one service — the
receipt printer at `/receipt/` — without making it an admin. Grantable keys receipt printer at `/receipt/` — without making it an admin. Grantable keys
are the registry `services.PermissionTypes` (`services/permissions.go`); are the registry `services.PermissionTypes` (`services/permissions.go`);
@@ -73,14 +73,11 @@ graph/ GraphQL layer
Users tab (`setUserPermissions`). Admins pass every permission check. The Users tab (`setUserPermissions`). Admins pass every permission check. The
check reads the user row, not the token, so a grant or revoke applies on check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which the next request. On 200 it returns the username in `X-Auth-User`, which
Caddy forwards to the gated service as `X-Remote-User`. nginx forwards to the gated service as `X-Remote-User`.
- Revocation is by `User.TokenVersion`: logout and a password change bump it, - Tokens are stateless. **Logout only clears the browser's cookies**; nothing
which invalidates every token already issued to that user. Demoting an admin is revoked server-side, and a token that has already been issued stays valid
applies on their next request. until it expires. The same is true of demoting an admin: it takes effect on
- Any request that is not GET/HEAD/OPTIONS must come from the site's own their next refresh, not immediately.
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
@@ -198,7 +195,7 @@ no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at
`/jobs/` is a separate app with its own Claude calls.) It reaches the `/jobs/` is a separate app with its own Claude calls.) It reaches the
internal routes directly over the Docker network internal routes directly over the Docker network
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through (`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
Caddy, which answers 404 for `/py/internal/`: nginx, which answers 404 for `/py/internal/`:
| route | caller | sends | gets back | | route | caller | sends | gets back |
| --- | --- | --- | --- | | --- | --- | --- | --- |
@@ -247,7 +244,7 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
to show them. Public files go to the Garage bucket wrapped in to show them. Public files go to the Garage bucket wrapped in
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or `FallbackFileStore` (a failed S3 write is logged and retried on disk), or
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
(the edge cannot gate a bucket). Caddy serves `/uploads/` from the bucket (nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
first and disk second, so either store's files work at the same URL. A new first and disk second, so either store's files work at the same URL. A new
handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind
admin-only `GET /uploads`, for the canvas's upload picker) returns the union admin-only `GET /uploads`, for the canvas's upload picker) returns the union
+40 -39
View File
@@ -1,53 +1,52 @@
module adam-french.co.uk/backend module adam-french.co.uk/backend
go 1.26.0 go 1.26
require ( require (
github.com/99designs/gqlgen v0.17.98 github.com/99designs/gqlgen v0.17.95
github.com/aws/aws-sdk-go-v2 v1.48.0 github.com/aws/aws-sdk-go-v2 v1.47.3
github.com/aws/aws-sdk-go-v2/credentials v1.21.0 github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.11.0
github.com/golang-jwt/jwt/v5 v5.3.1 github.com/golang-jwt/jwt/v5 v5.3.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
github.com/vektah/gqlparser/v2 v2.5.64 github.com/vektah/gqlparser/v2 v2.5.37
github.com/zmb3/spotify/v2 v2.4.3 github.com/zmb3/spotify/v2 v2.4.3
golang.org/x/crypto v0.59.0 golang.org/x/crypto v0.55.0
golang.org/x/oauth2 v0.38.0 golang.org/x/oauth2 v0.30.0
gorm.io/driver/postgres v1.6.3 gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.2 gorm.io/gorm v1.31.1
) )
require ( require (
github.com/agnivade/levenshtein v1.2.2 // indirect github.com/agnivade/levenshtein v1.2.1 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
github.com/aws/smithy-go v1.28.9 // indirect github.com/aws/smithy-go v1.28.5 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect github.com/cloudwego/base64x v0.1.6 // indirect
github.com/coder/websocket v1.8.15 // indirect github.com/coder/websocket v1.8.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-json v0.10.2 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.10.0 // indirect github.com/jackc/pgx/v5 v5.6.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
@@ -55,19 +54,21 @@ require (
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect github.com/mattn/go-isatty v0.0.24 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect github.com/quic-go/quic-go v0.54.0 // indirect
github.com/sosodev/duration v1.4.0 // indirect github.com/sosodev/duration v1.4.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect github.com/ugorji/go/codec v1.3.0 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.uber.org/mock v0.5.0 // indirect
golang.org/x/arch v0.22.0 // indirect golang.org/x/arch v0.20.0 // indirect
golang.org/x/net v0.62.0 // indirect golang.org/x/mod v0.40.0 // indirect
golang.org/x/sync v0.25.0 // indirect golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.50.0 // indirect golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.44.0 // indirect golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/tools v0.49.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect google.golang.org/protobuf v1.36.12 // indirect
) )
+78 -85
View File
@@ -31,44 +31,42 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/99designs/gqlgen v0.17.98 h1:t7UTlygkXMx1tJmKyR0LxttcufXnJ7fF6fAaeHSofAc= github.com/99designs/gqlgen v0.17.95 h1:882h7F5iJImgtyUVttc4MOK2NbzbMYc2oyNeHqkjpP4=
github.com/99designs/gqlgen v0.17.98/go.mod h1:tIoiUl+cgIT7nayvObZkKDgplxd1pHcUAmEXAyv+8f4= github.com/99designs/gqlgen v0.17.95/go.mod h1:kHYPrpwOXDU1OQyxIg3Z7nVXSnlUoHVWBY7CMJCAM4M=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/agnivade/levenshtein v1.2.2 h1:fI8RgiztYX1Nn5pBHHqQ9EMCCklhrmXqPRIedFmx5M4= github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
github.com/agnivade/levenshtein v1.2.2/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc= github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0= github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
github.com/aws/aws-sdk-go-v2/credentials v1.21.0 h1:OViwhqeipkQzSHuO2eQDUCdLrI6r3nzGxFUyM8GqnCs= github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
github.com/aws/aws-sdk-go-v2/credentials v1.21.0/go.mod h1:OffaVQod3fyZzhZJyPtw11WpHPF1uIHADc+/MYlXmbA= github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY= github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
@@ -88,12 +86,12 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -103,16 +101,16 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
@@ -177,8 +175,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
@@ -199,21 +197,18 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
@@ -222,41 +217,37 @@ github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERA
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/vektah/gqlparser/v2 v2.5.64 h1:N32yM6hQ6Kd5RdjCCEJsUrbCebVoA9yLLMOIa88Mkk0= github.com/vektah/gqlparser/v2 v2.5.37 h1:jbb1Ilv+xBklV6653tKb4oVUupPNTLb5LmrnBKVI12Y=
github.com/vektah/gqlparser/v2 v2.5.64/go.mod h1:nILRSUbsWDTuf8hSmAgFxuYh0SaMZdkvl6JSEbkJX8g= github.com/vektah/gqlparser/v2 v2.5.37/go.mod h1:9O4Ox6Ngd3Y12bMD3w6i3CRQXh8W1oC1q0m6olCymDM=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zmb3/spotify/v2 v2.4.3 h1:4divquzK2Mzo90XVIij4K7Z98Hf+6A3qPnksqtcDIuo= github.com/zmb3/spotify/v2 v2.4.3 h1:4divquzK2Mzo90XVIij4K7Z98Hf+6A3qPnksqtcDIuo=
github.com/zmb3/spotify/v2 v2.4.3/go.mod h1:XOV7BrThayFYB9AAfB+L0Q0wyxBuLCARk4fI/ZXCBW8= github.com/zmb3/spotify/v2 v2.4.3/go.mod h1:XOV7BrThayFYB9AAfB+L0Q0wyxBuLCARk4fI/ZXCBW8=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
@@ -265,8 +256,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -299,6 +290,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -331,16 +324,16 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20210810183815-faf39c7919d5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210810183815-faf39c7919d5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -351,8 +344,8 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -386,8 +379,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -403,8 +396,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -450,6 +443,8 @@ golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -539,12 +534,10 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.3 h1:bAn6O2pUa8LtpWEvL5NFU4+52Tfx8Ut7IVaIacCLcI0= gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.3/go.mod h1:0c4fQA44XhOklXDkgtuKqysHCycTa5i9e3EIpDGCwXk= gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+4 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -14,6 +14,9 @@ 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
+26 -7
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -19,7 +19,12 @@ 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) {
// Gin context for the client IP and cookies. Shares the REST login's limiter. // The Gin context is needed for two things GraphQL cannot express: the
// 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")
@@ -29,6 +34,8 @@ 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")
@@ -45,7 +52,8 @@ 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)
// Tokens travel only as HttpOnly cookies. // The payload carries no token: the tokens only ever travel as HttpOnly
// cookies, so client JavaScript never sees them.
return &model.AuthPayload{User: &user}, nil return &model.AuthPayload{User: &user}, nil
} }
@@ -56,9 +64,12 @@ 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")
} }
// Best effort, always succeeds, like the REST endpoint. // Bumping the token version is what actually revokes the tokens; clearing
// 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 {
// Claims in ctx are already verified, so this can't target others. // The context only carries claims from a token that already
// 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)
} }
@@ -81,7 +92,11 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
return nil, fmt.Errorf("unauthorized") return nil, fmt.Errorf("unauthorized")
} }
// Re-reads admin and token version from the DB. // Shared with the REST refresh endpoint, but the messages below are the
// 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 {
@@ -106,12 +121,16 @@ 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) {
// Not @signedIn: this query's error has always been "unauthorized". // Checked here rather than with @signedIn because the message differs:
// 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 {
+1 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
+4 -2
View File
@@ -12,8 +12,10 @@ import (
"adam-french.co.uk/backend/models" "adam-french.co.uk/backend/models"
) )
// These go into a style binding; a quote or bracket in the image could still // The SPA puts these values straight into a style binding, as
// end url() early, hence the narrow shapes. // `background-color` and `url("<image>")`. Vue sets them through the CSSOM,
// 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".
+4 -2
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -23,7 +23,9 @@ 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 and a bad id is "not found". // Loaded first so the deleted record can be returned to the client, and
// 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
+18 -8
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -15,7 +15,9 @@ 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 here, not in the gorm tag; see models.Box.Framed. // Framed defaults to true here rather than in the gorm tag — see the
// 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,
@@ -43,7 +45,8 @@ 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's own html would only go stale. // A linked box takes its html from the component, so its own is
// 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)
@@ -72,8 +75,10 @@ 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: the canvas sends only geometry after a drag and only html after // Partial update: nil fields are left alone. The canvas sends only the
// an edit, so neither overwrites the other. // geometry after a drag and only the html after an edit, so this is
// 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
@@ -82,7 +87,8 @@ 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 {
// Edit linked html via updateComponent, or it forks a copy. // A linked box's html is the component's; changing it here would
// 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")
} }
@@ -134,8 +140,12 @@ 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) {
// Ordered by z so DOM and tab order match stacking. Admin-only content is // Public: this is the page layout every visitor loads. Ordered by z so
// filtered server-side so it never reaches anyone else. // DOM order matches stacking order, which keeps tab order sensible.
//
// 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
+10 -3
View File
@@ -1,6 +1,8 @@
package graph package graph
// Helpers live outside *.resolvers.go because gqlgen moves unknown code there. // Hand-written helpers for box.resolvers.go. Kept out of that file because
// gqlgen moves unknown code in a resolvers file to the end, under a warning
// comment, on every regenerate.
import ( import (
"errors" "errors"
@@ -24,7 +26,9 @@ func setInt(dst *int, src *int) {
} }
} }
// validateBox clamps geometry, so an overshooting drag lands at the edge. // validateBox checks the fields a box needs to render and clamps geometry
// 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")
@@ -48,13 +52,16 @@ 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 doesn't parse: a style binding confines it to one property. // validateShadow trims a box-shadow value and bounds its length. The value is
// 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 {
+4 -5
View File
@@ -35,14 +35,13 @@ func TestValidateBox(t *testing.T) {
}) })
} }
// Geometry is clamped, not rejected: x may go negative, into the margin // Geometry is clamped, not rejected: a drag past the canvas edge lands
// left of a centred canvas, but nothing goes above the top or below a // at the edge, and a box can never shrink below a grabbable size.
// 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 != -30 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize { if box.X != 0 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize {
t.Fatalf("clamped to %d,%d %dx%d; want -30,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize) t.Fatalf("clamped to %d,%d %dx%d; want 0,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize)
} }
} }
+14 -5
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -16,6 +16,8 @@ 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
@@ -25,6 +27,7 @@ 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
@@ -54,7 +57,8 @@ 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) {
// Linked boxes read the html from here, so nothing else to update. // Partial, like updateBox. Nothing to do for the linked boxes: they
// 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
@@ -96,7 +100,9 @@ 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) {
// Linked boxes become copies, so deleting never changes a page. // The linked boxes keep showing what they showed, as copies, so
// 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
@@ -115,8 +121,9 @@ 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 first linked instance. A linked box must be // The box becomes the component's first linked instance, so carrying
// detached first. // on editing it edits the component. A box that is already linked
// 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
@@ -154,6 +161,8 @@ 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
+9 -2
View File
@@ -27,6 +27,9 @@ 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
@@ -50,8 +53,12 @@ func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error
return name, nil return name, nil
} }
// fillLinked sets linked boxes' HTML in memory only: saving a filled box would // fillLinked sets each linked box's in-memory HTML to its component's, with
// freeze a copy into it. A missing component leaves the HTML empty. // one query for all of them. Only for boxes about to be returned or
// 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 {
+30 -7
View File
@@ -7,10 +7,17 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
// Resolvers get only a context.Context; AuthContextMiddleware puts the // This file is the bridge between Gin's request handling and gqlgen's
// verified claims and the *gin.Context into it. // resolvers. gqlgen resolvers receive only a context.Context, so
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
// the *gin.Context itself into that context, and these accessors read them
// back out.
// Unrelated to the "userClaims" key handlers.AuthMiddleware sets on Gin's context. // contextKey is a private named type so that these keys can never collide
// 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 (
@@ -18,8 +25,10 @@ const (
ginContextKey contextKey = "ginContext" ginContextKey contextKey = "ginContext"
) )
// UserClaimsFromCtx returns nil for anonymous requests; refusing is the // UserClaimsFromCtx returns the verified JWT claims, or nil when the request
// directives' job. // is anonymous. nil means "not authenticated": a missing or invalid token is
// 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 {
@@ -28,6 +37,12 @@ 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 {
@@ -40,7 +55,12 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true return uint(idF), true
} }
// IsAdminFromCtx reads the claims, whose admin flag comes from the user row. // IsAdminFromCtx reports whether the request carries an admin token. It is
// 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 {
@@ -50,7 +70,10 @@ func IsAdminFromCtx(ctx context.Context) bool {
return ok && admin return ok && admin
} }
// GinContextFromCtx is nil if the middleware wasn't installed. // GinContextFromCtx returns the underlying *gin.Context, which resolvers need
// 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 {
+1 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
+9 -3
View File
@@ -36,14 +36,18 @@ 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: the server never reads inside it, so it need only be a // checkCoverLetterBody reports why body can't be stored. The server never
// JSON object of sane size. // reads inside it, so it only has to be a JSON object of a sane size — an
// 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)
@@ -56,7 +60,9 @@ func checkCoverLetterBody(body string) error {
return nil return nil
} }
// cleanSnippetText counts characters, not bytes. // cleanSnippetText trims text and reports why it can't be a bank paragraph.
// 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 == "" {
+28 -4
View File
@@ -7,16 +7,34 @@ import (
"github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql"
) )
// The @admin and @signedIn directives. The front end shows these error // The schema's two authorisation directives. A field marked @admin or
// strings verbatim (the tracker reads "admin access required" as a lapsed // @signedIn in graph/schema/*.graphql has the matching function here run
// session), so don't reword them. // before its resolver; if it returns an error the resolver is never called
// 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 shared by main and the tests. A nil directive fails closed. // Directives is the set gqlgen needs in graph.Config. It is a function so
// 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,
@@ -24,6 +42,9 @@ 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)
@@ -31,6 +52,9 @@ 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)
+42 -11
View File
@@ -20,8 +20,15 @@ import (
"adam-french.co.uk/backend/handlers" "adam-french.co.uk/backend/handlers"
) )
// Covers both the directive functions and which fields carry them. No // Authorisation is declared in the schema (@admin / @signedIn) and enforced
// database: refused fields never reach their resolvers. // by directives.go. These tests cover both halves: that the two functions
// 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.
@@ -93,7 +100,9 @@ func TestDirectivesAreAllImplemented(t *testing.T) {
} }
} }
// guardOf fails on both directives at once: @signedIn adds nothing to @admin. // guardOf reports which authorisation directive a field carries: "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
@@ -114,8 +123,14 @@ func schemaUnderTest() *ast.Schema {
return NewExecutableSchema(Config{}).Schema() return NewExecutableSchema(Config{}).Schema()
} }
// publicMutations is the allow-list; any other unguarded mutation fails // publicMutations is the complete list of mutations that anyone may call.
// TestEveryMutationIsGuarded. // A mutation is public only by being named here, so adding one to the schema
// 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) {
@@ -144,7 +159,9 @@ func TestEveryMutationIsGuarded(t *testing.T) {
} }
} }
// Pinned so loosening @admin to @signedIn needs a change here. // The mutations that need only a session rather than an admin. Pinned so that
// 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
@@ -159,8 +176,15 @@ func TestSignedInMutationsArePinned(t *testing.T) {
} }
} }
// Queries are public by default, so the guarded set is pinned exactly. // Queries are public by default — the home page is built from them — so the
// me, messages and spotifyNeedsReauth vary by caller without a directive. // rule cannot be "every field is guarded". Instead the guarded set is pinned
// 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",
@@ -193,7 +217,9 @@ func TestGuardedQueriesArePinned(t *testing.T) {
} }
} }
// Keep directives on root fields: the tests above only look there. // The directives are FIELD_DEFINITION only and are meant for the two root
// 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 {
@@ -208,7 +234,10 @@ func TestDirectivesOnlyOnRootFields(t *testing.T) {
} }
} }
// execute runs an operation as main wires it, with an empty Store. // execute runs one operation through the real executable schema, wired the
// 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{
@@ -269,7 +298,9 @@ func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
} }
} }
// IDs stay quoted decimal strings on the wire, accepting strings or numbers. // IDs: the wire form must be what it was when every type had a hand-written
// 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
+47 -11
View File
@@ -1,15 +1,51 @@
// Package graph is the GraphQL layer behind POST /graphql. // Package graph is the GraphQL layer: the single POST /graphql endpoint that
// serves most of the site's data.
// //
// graph/schema/*.graphql is the source of truth; gqlgen regenerates // How the pieces fit:
// generated.go and model/models_gen.go (never edit them). gqlgen.yml maps
// object types onto the GORM structs in backend/models.
// //
// Nothing guards the endpoint itself. A field is protected only by an // - graph/schema/*.graphql is the source of truth. Running
// @admin or @signedIn directive (directives.go); a field with neither is // `go run github.com/99designs/gqlgen generate` regenerates generated.go
// public. directives_test.go fails if a mutation has neither and isn't on its // and model/models_gen.go, and adds stubs for any new field to the
// public allow-list. Finer rules (post ownership, hiding private messages) // matching *.resolvers.go. Never edit those two generated files.
// live in resolvers via IsAdminFromCtx / UserIDFromCtx. // - gqlgen.yml maps most GraphQL object types straight onto the GORM
// 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.
// //
// gqlgen may move hand-written code in *.resolvers.go; _helpers.go files are // Authorisation, which is the thing most likely to catch out a newcomer:
// untouched. // there is NO middleware guarding this endpoint. AuthContextMiddleware only
// 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 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
+1383 -850
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -24,7 +24,10 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Not cached, so an empty feed is retried next time. // FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
// 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
} }
+4 -1
View File
@@ -5,7 +5,10 @@ import (
"adam-french.co.uk/backend/services" "adam-french.co.uk/backend/services"
) )
// mapGiteaFeed requires a non-nil feed. // mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
// 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,
+1 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
+33 -8
View File
@@ -1,5 +1,8 @@
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"
@@ -14,7 +17,9 @@ import (
const maxLayoutNameLen = 100 const maxLayoutNameLen = 100
// layoutBox is a box minus id and page. Renaming fields breaks saved layouts. // layoutBox is one box as a layout stores it: what makes it look the way it
// 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"`
@@ -29,7 +34,9 @@ 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"`
// HTML is kept too, so a layout outlives a deleted component. // ComponentID is the component a linked box was linked to. HTML is
// 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"`
} }
@@ -39,6 +46,7 @@ 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 == "" {
@@ -50,14 +58,18 @@ func cleanLayoutName(name string) (string, error) {
return name, nil return name, nil
} }
// Checked up front so the admin gets a sentence, not a constraint violation. // layoutNameTaken reports whether a live layout other than exceptID has this
// 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: boxes on any other key would never be shown. // canvasExists reports whether page is a canvas boxes can be put on: the
// 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
@@ -70,13 +82,16 @@ func canvasExists(db *gorm.DB, page string) (bool, error) {
return count > 0, err return count > 0, err
} }
// pageBoxes includes adminOnly boxes; admin callers only. // pageBoxes is every box on page, adminOnly ones included, in the order the
// 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 {
@@ -124,6 +139,7 @@ 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 "/"
@@ -131,6 +147,7 @@ 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++ {
@@ -142,17 +159,22 @@ func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
} }
} }
// applyLayoutTo creates new rows, so nothing stays linked to the layout. // applyLayoutTo copies layout onto page inside tx; see applyLayout in
// 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 copies stack above the page's existing boxes. // Added on top, the copies keep their own stacking order but all sit
// above what the page already has.
zShift := 0 zShift := 0
if replace { if replace {
// Save what's being replaced first, so a replace can be undone. // What is being replaced is kept first, so a replace can be undone by
// 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 {
@@ -212,6 +234,7 @@ 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 {
@@ -228,6 +251,8 @@ 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 {
+10 -4
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -12,15 +12,21 @@ import (
) )
// AuthorID is the resolver for the authorId field. // AuthorID is the resolver for the authorId field.
// The chat hub's connection number, not a User id. // AuthorID is the resolver for the authorId field. The value is the chat
// 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. Keep in step with the WebSocket // Non-admins get the public subset rather than an error, so the chat
// history filter (services.HandleWebSocket), which is oldest first. // history loads for everyone. The same filter is applied to the history
// 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) {
+21 -2
View File
@@ -8,20 +8,39 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// AuthContextMiddleware never rejects: a bad or missing token leaves the // AuthContextMiddleware prepares the request context for the GraphQL handler.
// 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()
} }
+7 -3
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -45,7 +45,9 @@ 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. A new slug moves the boxes and background in the same transaction. // Partial update, like updateBox. A new slug moves the page's boxes and
// 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
@@ -132,7 +134,9 @@ 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 for missing or hidden pages: the SPA shows its 404 on null. // Null, not an error, for a missing page: the SPA's catch-all route asks
// 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) {
+16 -5
View File
@@ -13,13 +13,20 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Slugs are URL-safe as they stand. // pageKeyPattern is the shape of a box's page key and of a page slug: lower
// 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
// Paths Caddy or the SPA's routes answer first, plus "index". "shrines" and // reservedFirstSegments are paths a page could never be reached at, because
// "stp" are canvas pages, so not reserved. // nginx or one of the SPA's own routes answers them first (see
// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the
// 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,
@@ -44,7 +51,9 @@ func validateSlug(slug string) error {
return nil return nil
} }
// A key with no Page row is never hidden. // pageHiddenFrom reports whether the page with this key is an adminOnly page
// 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
@@ -54,7 +63,9 @@ func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error)
return count > 0, err return count > 0, err
} }
// Checked up front for a readable error; the partial unique index backs it. // slugTaken reports whether a live page other than exceptID has this slug.
// 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 -1
View File
@@ -20,7 +20,7 @@ func TestValidateSlug(t *testing.T) {
{"shrines", true}, // the index is a canvas page too {"shrines", true}, // the index is a canvas page too
{"shrines/demoman", true}, // no longer an SPA route {"shrines/demoman", true}, // no longer an SPA route
{"admin/pages", false}, // under an SPA route {"admin/pages", false}, // under an SPA route
{"jobs/x", false}, // under a Caddy route {"jobs/x", false}, // under an nginx route
{"stp", true}, // the home page is a canvas page too {"stp", true}, // the home page is a canvas page too
{"stp2", false}, // an SPA route {"stp2", false}, // an SPA route
{"index", false}, // the landing canvas's key {"index", false}, // the landing canvas's key
+5 -2
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -14,7 +14,10 @@ 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) {
// @signedIn: places are the site's one shared list, with no ownership. // Any signed-in user, not just an admin — places are the one shared,
// 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,
+17 -5
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -16,12 +16,16 @@ 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")
} }
// Stops a stray click publishing a blank post. // The admin form submits whatever is in its fields, so an accidental click
// 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")
} }
@@ -46,12 +50,15 @@ 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")
} }
// Only the author may edit, even among admins. // Admin alone (the @admin on the field) is not enough: a post may only be
// 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")
} }
// Full replace: an omitted field is blanked. // Both fields are non-pointer in the input, so this is a full replace —
// 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 {
@@ -77,6 +84,9 @@ 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
} }
@@ -86,7 +96,9 @@ 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) {
// Without Preload, author resolves to null silently. // Preload issues a second query for the authors and fills in Post.Author.
// 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
+11 -1
View File
@@ -7,7 +7,17 @@ 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 holds the same handlers.Store the REST handlers use. // Resolver is the root of the GraphQL schema and the only dependency every
// 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
} }
+3 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -21,6 +21,8 @@ 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 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
// Mutation returns MutationResolver implementation. // Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} } func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
+7 -1
View File
@@ -1,4 +1,10 @@
# A page key's background; null for an adminOnly page unless admin. # The background behind a canvas page, keyed by the same page key as its
# 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!
+10 -2
View File
@@ -1,5 +1,13 @@
# Boxes on a page key. Public reads, admin writes; adminOnly boxes go to # Boxes on a canvas page: the landing page (page "index") or an
# admins only. kind is "widget" or "html" (sandboxed iframe). # admin-created Page (page = its slug; the home page /stp is the Page "stp").
# 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!
+10 -2
View File
@@ -1,5 +1,13 @@
# Named HTML boxes, placed as copies or linked (Box.componentId); linked boxes # Components: named HTML boxes that can be placed on any canvas page, either
# share only the html. Admin only, reads included. # as a copy (an ordinary box) or linked (a Box whose componentId is set).
# 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!
+14 -3
View File
@@ -1,5 +1,12 @@
# Saved snapshots of a page's boxes and background; loading copies them. # Saved layouts: a named copy of one canvas page's boxes and background,
# Admin only, reads included, since layouts keep adminOnly boxes. # which can be loaded onto any canvas page — the landing page ("index") or a
# 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!
@@ -32,6 +39,10 @@ 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
# replace: true first saves the page as a layout, then swaps in this one. # Copies the layout onto `page` and answers with that page's boxes.
# 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
} }
+29 -4
View File
@@ -1,10 +1,35 @@
# Root types; each file extends Query and Mutation. Use # comments, not """ # Root of the GraphQL schema.
# (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
# A field is public unless it has @admin or @signedIn (graph/directives.go). # Authorisation. There is no middleware in front of /graphql, so a field is
# directives_test.go enforces this for mutations. # PUBLIC unless it carries one of these. Each is implemented once, in
# 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
+1 -1
View File
@@ -10,7 +10,7 @@ type User {
} }
# One grantable service, from services.PermissionTypes: `key` is what is # One grantable service, from services.PermissionTypes: `key` is what is
# stored and what Caddy gates on, `label` and `path` are for display. # stored and what nginx gates on, `label` and `path` are for display.
type PermissionType { type PermissionType {
key: String! key: String!
label: String! label: String!
+9 -2
View File
@@ -3,8 +3,15 @@ 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 turns []T into []*T for gqlgen. Loading into []*T directly would // ptrs copies a slice of values into a slice of pointers to those values.
// 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 {
+6 -2
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -51,7 +51,11 @@ 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
+8 -1
View File
@@ -5,6 +5,10 @@ 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))
@@ -31,7 +35,10 @@ 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 -1
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
+4 -1
View File
@@ -8,7 +8,10 @@ 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 {
+13 -5
View File
@@ -3,7 +3,7 @@ package graph
// This file will be automatically regenerated based on the schema, any resolver // This file will be automatically regenerated based on the schema, any resolver
// implementations // implementations
// will be copied through when generating and any unknown code will be moved to the end. // will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.98 // Code generated by github.com/99designs/gqlgen version v0.17.95
import ( import (
"context" "context"
@@ -18,6 +18,9 @@ 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
@@ -52,7 +55,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return nil, fmt.Errorf("unauthorized") return nil, fmt.Errorf("unauthorized")
} }
// Stops the last admin locking everyone out. // Guards against the last admin demoting themselves and locking everyone
// 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")
} }
@@ -72,8 +76,10 @@ 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) {
// Full replace. Unknown keys are refused so a stale UI can't silently // The whole list is replaced, so the admin panel sends every ticked box
// save less than it showed. // each time. An unknown key is refused rather than dropped, so a stale
// 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) {
@@ -93,7 +99,8 @@ 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: the gate reads this column on every request. // No token bump needed: the permission gate reads this column on every
// 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
@@ -122,5 +129,6 @@ 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
} }
+131 -33
View File
@@ -12,36 +12,62 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
// REST auth endpoints and middleware. GraphQL's login/logout/refresh live in // This file holds the REST authentication endpoints and the Gin middleware
// graph/auth.resolvers.go; both mint cookies through services.Auth. // that guards the other REST routes. GraphQL has its own parallel
// 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"`
} }
// AuthMiddleware requires a valid, unrevoked access token. It does not fall // AuthMiddlewear requires a valid access token on a REST route and stashes
// back to the refresh token: the client refreshes and retries on 401. // the claims for AdminMiddleware to read.
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
} }
// Gin context key; graph/context.go uses its own, separate mechanism. // Stored under a plain string key in the *Gin* context. This is a
// 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 must follow AuthMiddleware, whose claims carry the row's // AdminMiddleware requires the access token to carry admin=true. It must be
// admin flag. // chained after AuthMiddlewear, which is what populates "userClaims"; on its
// 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 {
@@ -55,7 +81,8 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
return return
} }
// Tokens minted before the admin claim have none: not an admin. // A token minted before the admin claim existed simply has no "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"})
@@ -65,18 +92,37 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
ctx.Next() ctx.Next()
} }
// ValidateAdmin answers 200/403/401 with no body, for the SPA, Caddy's admin // ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// gate and the jobs container. It falls back to the refresh token and may // decide whether to show admin UI, nginx's admin gate calls as an
// mint new cookies, so a returning admin needn't log in again. // auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// 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, _ *jwt.MapClaims) bool { store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
return user.Admin // On the access-token path admin is read from the token, as
// 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 Caddy's permission gate, like ValidateAdmin but // ValidatePermission backs GET /auth/validate/:permission, nginx's permission
// reading the user row. An unknown key is 404, so a typo in a Caddy route // gate (see services/permissions.go). Same bare-status contract and refresh
// fails visibly rather than looking like a missing grant. // fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in an nginx location fails closed and
// 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) {
@@ -88,9 +134,16 @@ func (store *Store) ValidatePermission(ctx *gin.Context) {
}) })
} }
// validateSession identifies the caller by access token, else refresh token // validateSession is the body shared by the two validate endpoints: identify
// (allow then gets nil claims), and answers 200/403/401. On 200 the username // the caller from the access token, or failing that the refresh token, and
// goes in X-Auth-User for Caddy to pass upstream. // answer 200 / 403 / 401 according to allow.
//
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which nginx can lift with
// auth_request_set and hand to the service behind the gate, so that service
// knows who is using it without having accounts of its own.
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 {
@@ -106,19 +159,27 @@ 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 returns whether it wrote the response (200 or 403), // tryRefreshAndValidate re-authenticates from the refresh token.
// 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
@@ -141,12 +202,17 @@ 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 returns the current user. A valid token for a deleted user gets // CheckToken backs GET /auth/check: it returns the current user for a valid
// 404 and cleared cookies. // access token, or 401. If the token is valid but the user no longer exists
// 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 {
@@ -154,6 +220,11 @@ 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) {
@@ -169,8 +240,11 @@ func (store *Store) CheckToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, user) ctx.JSON(http.StatusOK, user)
} }
// RefreshToken exchanges the refresh token for a new pair. It is not rotated, // RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
// but logout and password changes revoke it via the token version. // for a new cookie pair and returns the user.
//
// 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 {
@@ -178,6 +252,11 @@ 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 {
@@ -205,9 +284,13 @@ 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) {
// On top of Caddy's limit. ClientIP is trustworthy because main.go pins // Per-IP limit (5/min) on top of nginx's own login rate limit.
// the trusted proxy range. // ctx.ClientIP is only trustworthy because main.go pins the trusted
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
// client talking through nginx.
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
@@ -219,7 +302,9 @@ func (store *Store) Login(ctx *gin.Context) {
return return
} }
// Same message for unknown user and wrong password. // Unknown user and wrong password return the identical message, so the
// 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"})
@@ -243,8 +328,13 @@ func (store *Store) Login(ctx *gin.Context) {
ctx.JSON(http.StatusAccepted, user) ctx.JSON(http.StatusAccepted, user)
} }
// Logout clears the cookies and bumps the token version, revoking every copy // Logout backs POST /auth/logout. As well as clearing the browser's cookies
// of the tokens. Always 200. // it bumps the user's token version, so the tokens it just discarded — and
// 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)
@@ -252,8 +342,12 @@ func (store *Store) Logout(ctx *gin.Context) {
ctx.Status(http.StatusOK) ctx.Status(http.StatusOK)
} }
// revokeCallerTokens verifies the token before bumping, or a forged cookie // revokeCallerTokens bumps the token version of whoever made this request,
// could revoke any user's sessions. // identified from the access token or, failing that, the refresh token.
//
// 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)
@@ -265,12 +359,16 @@ 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)
} }
+7 -2
View File
@@ -7,7 +7,10 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// GetNoteFile: Notes.ParsePath does the containment check. // GetNoteFile serves one file from the notes directory for the admin-only
// 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")
@@ -26,7 +29,9 @@ func (store *Store) GetNoteFile(ctx *gin.Context) {
return return
} }
// Exposed so cross-origin fetch() can read it. // The SPA reads Last-Modified to show a note's edit date. Browsers hide
// 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")
+41 -13
View File
@@ -9,18 +9,27 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Radio fallback music management. Disabled songs live in a "disabled" // Admin management of the radio's fallback music. These handlers only move
// subdirectory: that is the whole of the radio's state. // files around on disk; the Python service is what actually streams them, and
// 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"
// Not sniffed: admin-only, and audio sniffs unreliably. // allowedAudioExtensions is the upload allow-list, keyed by lower-cased
// 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 keeps the original filename, which the admin sees, so it is // UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat
// sanitised. // uploads the original filename is kept, because it is what the admin sees in
// 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 {
@@ -40,18 +49,22 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
return return
} }
// Base strips traversal; the absolute-path check below is a second guard. // filepath.Base strips any directory component, so "../../etc/passwd"
// 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 trailing separator stops a same-prefix sibling directory passing. // The separator is appended before comparing so a sibling directory whose
// 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
} }
// Check-then-write race accepted: admin-only. // Refuse to overwrite. There is a check-then-write race here, but the
// 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
@@ -65,7 +78,11 @@ 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"`
@@ -73,15 +90,17 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
Disabled bool `json:"disabled"` Disabled bool `json:"disabled"`
} }
// [] not null in the JSON. // Initialised empty rather than nil so the response is [] and not null.
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 also skips "disabled". // Skipping directories is also what keeps the "disabled" subdirectory out
// 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
@@ -98,7 +117,9 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
}) })
} }
// Created lazily, so a missing directory just means none disabled. // The disabled directory is created lazily by DisableRadioSong, so a read
// 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 {
@@ -122,8 +143,12 @@ 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) {
// Base returns "." or "/" for degenerate input; both are rejected. // filepath.Base neutralises traversal in the :filename route parameter.
// 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"})
@@ -151,6 +176,7 @@ 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 == "/" {
@@ -173,7 +199,9 @@ func (store *Store) EnableRadioSong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"enabled": filename}) ctx.JSON(http.StatusOK, gin.H{"enabled": filename})
} }
// DeleteRadioSong can't reach disabled songs; enable one first. // DeleteRadioSong permanently removes an enabled song. It cannot reach the
// 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 == "/" {
+68 -22
View File
@@ -15,30 +15,51 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// CreateRowing reads a photo of the rowing machine display. The Claude call // Rowing log. The interesting endpoint is CreateRowing: rather than a form,
// is in python/app/rowing.py; auth, EXIF, dedup and bounds checks stay here. // the admin uploads a photo of the rowing machine display and Claude reads the
// 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 matches RowingReading in python/app/rowing.py. // ExtractedRowingData is the JSON contract for what Claude reads off the
// 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"`
} }
// Internal: Caddy refuses /py/internal/, so only a direct container call works. // rowingReadPath is the Python route. It is internal: nginx refuses
// /py/internal/ and the route itself refuses anything nginx 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) {
// []byte marshals as standard base64, as the Anthropic API expects. // Data is a []byte so that it is sent as standard base64, the encoding
// 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
if err := store.DB.Order("created_at DESC").Find(&rowing).Error; err != nil { // "Created_At" works because Postgres folds unquoted identifiers to lower
// 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
@@ -46,8 +67,13 @@ func (store *Store) GetRowing(ctx *gin.Context) {
ctx.JSON(http.StatusOK, rowing) ctx.JSON(http.StatusOK, rowing)
} }
// CreateRowing is admin-only, so its checks target misreadings, not hostile // CreateRowing backs the admin-only POST /rowing: it takes a photo of the
// input. // rowing machine display, dates it from EXIF, has Claude read the time and
// 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 {
@@ -62,7 +88,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
} }
defer f.Close() defer f.Close()
// EXIF is required: it is both the session date and the duplicate key. // EXIF is required, not optional: it is both the session date and the
// 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"})
@@ -75,14 +103,19 @@ 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
} }
// Bounded before buffering, to cap memory and the paid API call. // Cap the upload before buffering it (and then base64-encoding it, 1.33x
const maxPhotoSize = 10 << 20 // bigger, on its way to the Python service): the route is admin-only but
if file.Size > maxPhotoSize { // an unbounded read would still let a giant file exhaust the Pi's memory
// 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
} }
@@ -99,16 +132,24 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
"image/gif": true, "image/gif": true,
"image/webp": true, "image/webp": true,
} }
// The browser's claimed type, checked only to keep the API call // This is the browser's claimed type, not a sniffed one; it is passed
// well-formed and give a clear 400. // straight through to the Anthropic API, so the allow-list is there to
// 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
} }
// Checked before the paid call. Fails closed: only ErrRecordNotFound // Duplicate guard: two photos of the same session share an EXIF capture
// means "no duplicate". // time to the second. Checked before the Claude call so a re-upload costs
// 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 {
@@ -124,7 +165,9 @@ 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)
// Pass on the reader's own messages; hide plumbing failures. // The reader's own messages ("failed to parse image data", ...) are
// 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) {
@@ -141,8 +184,10 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
// A misread digit usually lands outside human performance; the pace check // Sanity bounds on what Claude claims to have read. A misread digit
// catches plausible time and distance that disagree. // typically lands far outside human rowing performance, and the pace
// 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
@@ -166,9 +211,10 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return return
} }
// A display-only estimate, ~500 kcal per 7500 m. // Rough calorie estimate from distance alone: roughly 500 kcal per
const kcalPerMetre = 500.0 / 7500.0 // 7500 m. Not from the machine and not physiologically derived — it is a
calories := float64(extractedData.Distance) * kcalPerMetre // display figure only.
calories := float64(extractedData.Distance) / 7500.0 * 500.0
rowing := models.Rowing{ rowing := models.Rowing{
Date: dateTaken, Date: dateTaken,
+1 -1
View File
@@ -32,7 +32,7 @@ func TestReadRowingDisplayRequestAndReply(t *testing.T) {
var forwarded bool var forwarded bool
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) { store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path path = r.URL.Path
// The Python route treats either header as "came through Caddy" and // The Python route treats either header as "came through nginx" and
// answers 404, so this call must never carry them. // answers 404, so this call must never carry them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != "" forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil { if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+37 -9
View File
@@ -10,22 +10,35 @@ import (
"github.com/zmb3/spotify/v2" "github.com/zmb3/spotify/v2"
) )
// The callback must be REST (Spotify redirects a browser to it); the rest // These REST endpoints predate the equivalent GraphQL queries in
// predate the GraphQL equivalents. // graph/spotify.resolvers.go and are kept for the OAuth callback (which must
// be REST, because Spotify redirects a browser to it) and for direct use.
// CompleteSpotifyAuth installs the client on the Store, so no restart is needed. // CompleteSpotifyAuth handles Spotify's OAuth redirect to
// 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")
// The real CSRF check: the library compares state against the value we // CSRF check: the state must be a nonce this process handed out from
// pass it, which is the one just received. // StartSpotifyAuth and has not seen come back yet. Without it, anyone who
// 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
} }
// The client outlives this request. // context.Background, not the request context: the client built below
// 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)
@@ -48,7 +61,13 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
}) })
} }
// StartSpotifyAuth returns the authorisation URL with a fresh state nonce. // StartSpotifyAuth backs the admin-only GET /spotify/auth. It returns the
// 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 {
@@ -60,6 +79,9 @@ 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()
@@ -78,7 +100,9 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
ctx.JSON(200, playing) ctx.JSON(200, playing)
} }
// RecentlyPlayed shares its cache with the GraphQL spotifyRecent resolver. // RecentlyPlayed backs GET /spotify/recent, serving the shared one-minute
// 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"})
@@ -95,7 +119,11 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
ctx.JSON(200, played) ctx.JSON(200, played)
} }
// RecentlyPlayedTracks requires a non-nil SpotifyClient. // RecentlyPlayedTracks returns the last few played tracks, from the cache when
// 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
+25 -5
View File
@@ -10,8 +10,19 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
// Upload stores a multipart `file` via services.Uploads.Save and returns its // Upload backs POST /uploads (login required): the one endpoint the frontend
// URL. `private` is admin-only, as private messages are. // stores a file through (vue/src/uploads.js). Multipart form:
//
// 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) {
@@ -38,7 +49,12 @@ func (store *Store) Upload(ctx *gin.Context) {
} }
} }
// ListUploads is admin-only: listing is what turns unguessable URLs into known ones. // ListUploads backs GET /uploads (admin): every public upload, newest first,
// 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 {
@@ -52,8 +68,12 @@ func (store *Store) ListUploads(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"files": files}) ctx.JSON(http.StatusOK, gin.H{"files": files})
} }
// requestIsAdmin: this route is in `protected`, not `admin`, since any // requestIsAdmin reports whether the caller's access token carries admin=true.
// 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 {
+33 -7
View File
@@ -12,8 +12,24 @@ import (
"github.com/zmb3/spotify/v2" "github.com/zmb3/spotify/v2"
) )
// Handlers needing a live DB, multipart requests or container paths aren't // What is deliberately NOT covered here, and why:
// 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 -------------------------------------------
@@ -99,13 +115,15 @@ func TestNewSpotifyStatePrunesExpired(t *testing.T) {
// --- Cache TTL rules ------------------------------------------------------ // --- Cache TTL rules ------------------------------------------------------
// Empty counts as stale on purpose; pinned so it isn't "fixed". // Each cache treats "empty" as stale, which is deliberate (an empty listening
// 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},
@@ -197,6 +215,9 @@ 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)
@@ -210,7 +231,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 AuthMiddleware stores; accepting // A by-value jwt.MapClaims is not what AuthMiddlewear 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},
@@ -233,7 +254,9 @@ func TestRequestIsAdmin(t *testing.T) {
// --- Permission gate ------------------------------------------------------ // --- Permission gate ------------------------------------------------------
// Must 404 before any session lookup (a nil Store would panic). // An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in an nginx
// 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{}
@@ -249,6 +272,9 @@ 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
+65 -15
View File
@@ -13,8 +13,18 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Store is the dependency container shared by every handler and resolver. // Package handlers holds the REST endpoints and the shared Store that every
// Cache fields are guarded by cacheMu: use the accessors, never the fields. // request handler — and, through graph.Resolver, every GraphQL resolver —
// 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
@@ -23,43 +33,63 @@ type Store struct {
Notes *services.Notes Notes *services.Notes
LoginLimiter *services.RateLimiter LoginLimiter *services.RateLimiter
// The Python service on the Docker network, no trailing slash. // Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx, 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
// 1 minute TTL. // Cached latest Gitea activity entry, 1 minute TTL.
GiteaHost string GiteaHost string
GiteaPort string GiteaPort string
GiteaFeed *services.GiteaFeedResponse GiteaFeed *services.GiteaFeedResponse
GiteaFeedFetchedAt time.Time GiteaFeedFetchedAt time.Time
// 5 minute TTL. // Cached Steam status and recent games, 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
// One-shot OAuth CSRF nonces. In memory: a lost nonce only restarts a // spotifyStates holds the one-shot CSRF nonces handed out by
// seconds-long flow. // GET /spotify/auth, mapped to their creation time. In-memory is enough:
// 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
// Every page visit would otherwise log "Spotify not authenticated". // spotifyNilLoggedAt rate-limits the "Spotify not authenticated" log line:
// 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 nonce. Pruning here is the only cleanup; only an // NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation
// admin can add entries. // URL and remembers it. Expired entries are pruned on the way through, which
// 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 {
@@ -82,7 +112,9 @@ func (s *Store) NewSpotifyState() (string, error) {
return state, nil return state, nil
} }
// ConsumeSpotifyState removes the nonce, so a replayed callback fails. // ConsumeSpotifyState checks a nonce returned by Spotify's redirect and
// 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
@@ -99,7 +131,15 @@ func (s *Store) ConsumeSpotifyState(state string) bool {
return time.Since(created) <= spotifyStateTTL return time.Since(created) <= spotifyStateTTL
} }
// LogSpotifyUnauthenticated logs at most once an hour. // The cache accessors below are the only supported way to touch the cache
// 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()
@@ -110,7 +150,9 @@ 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 treats an empty list as stale. // CachedRecentSongs returns the cached Spotify recently-played list if it is
// 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()
@@ -124,6 +166,7 @@ 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()
@@ -132,6 +175,9 @@ 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()
@@ -142,6 +188,7 @@ 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()
@@ -150,8 +197,10 @@ func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.GiteaFeedFetchedAt = time.Now() s.GiteaFeedFetchedAt = time.Now()
} }
// CachedSteam judges freshness on the games list only, so an empty list is // CachedSteam returns the cached Steam recent games and online flag if they
// always re-fetched. // are within their five-minute TTL. As before, freshness is judged only on the
// 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()
@@ -162,6 +211,7 @@ 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()
+91 -22
View File
@@ -20,9 +20,18 @@ import (
"adam-french.co.uk/backend/services" "adam-french.co.uk/backend/services"
) )
// Command backend is the site's Go API. GraphQL is guarded by schema // Command backend is the Go API for adam-french.co.uk.
// 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 {
@@ -35,11 +44,16 @@ 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 may set X-Forwarded-For, or clients could spoof // Only the Docker network nginx sits on may set X-Forwarded-For. Without
// their IP past the login rate limiter. Must match docker-compose.yml. // this pin any client could spoof its IP and defeat the per-IP login rate
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
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)
@@ -55,25 +69,38 @@ 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)
} }
// Used for both the WebSocket origin check and the cookie domain. // DOMAIN does double duty: the WebSocket origin allow-list and the auth
// 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
// Sliding: every refresh, including the gates', mints a new one. refreshTokenLifetime := 365 * 24 * time.Hour
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)
@@ -87,7 +114,10 @@ func main() {
steamAPIKey := os.Getenv("STEAM_API_KEY") steamAPIKey := os.Getenv("STEAM_API_KEY")
steamID := os.Getenv("STEAM_ID") steamID := os.Getenv("STEAM_ID")
// Called over the Docker network, not through Caddy. // PYTHON SERVICE
// Called directly over the Docker network, not through nginx, 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"
@@ -98,7 +128,11 @@ func main() {
} }
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort) pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// Defaults match stpcore's garage/garage.toml and garage/bootstrap.sh. // UPLOADS
// 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"
@@ -110,18 +144,24 @@ 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/")
// Shared by REST and GraphQL login, on top of Caddy's limit. // 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Nginx rate-limits the login route too.
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}
// Caddy strips /api before proxying. // Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
protected := r.Group("/", store.AuthMiddleware) // the Gin context, so the order in the admin group matters.
admin := r.Group("/", store.AuthMiddleware, store.AdminMiddleware) //
// Paths below have no /api prefix: nginx 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)
@@ -129,43 +169,69 @@ 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)
// The callback is open (Spotify redirects a logged-out browser) and is // SPOTIFY
// protected by the state nonce that only the admin-only start mints. // The callback must be open — Spotify redirects a logged-out browser to
// 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)
// Public: the handler reads the cookies itself for admin privileges. // MESSAGES
// /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)
// One unguarded POST route: authorisation is the schema's @admin and // GRAPHQL
// @signedIn directives, so a field with neither is public. gqlgen fails // GraphQL is assembled by hand rather than with handler.NewDefaultServer
// closed if Directives is dropped. // so the transports and extensions below are explicit.
//
// 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))
// Production never publishes its schema. // Introspection and the playground are both off unless DEV_MODE *and*
// 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)
}) })
@@ -175,12 +241,15 @@ 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")
// Exit non-zero so Docker doesn't report a port clash as success. // Blocks until the server stops. Any return is a failure — a port clash,
// 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)
} }
+139 -50
View File
@@ -6,29 +6,64 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// These structs are also the GraphQL object types (gqlgen.yml), so a field or // Package models holds the GORM entities, which are also the GraphQL object
// tag change affects the DB, REST JSON and GraphQL at once. // types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
// 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, created only by an admin or the dev seeder. // User is an account. There is no public sign-up: users are created by an
// 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; gqlgen.yml hides it from GraphQL too. // bcrypt hash, never the plaintext. `json:"-"` keeps it out of REST
// responses, and gqlgen.yml marks the GraphQL password field
// resolver:false so it is not exposed there either.
Password []byte `json:"-"` Password []byte `json:"-"`
// Copied into the access token, so changes apply on the next refresh. // Admin gates almost every mutation. It is copied into the access token,
// so a change here only takes effect on the user's next token refresh.
Admin bool `json:"admin"` Admin bool `json:"admin"`
// Keys from services.PermissionTypes. Read from the row on each request, // Permissions names the gated services this non-admin user may use, one
// not the token, so grants apply immediately. // key each from services.PermissionTypes (admins pass every check
// 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"`
// Every JWT carries this; bumping it revokes all of the user's tokens. // TokenVersion is the session generation counter. Every issued JWT
// 0 and a missing claim are both treated as 1 (services.tokenVersionOf). // carries the value current at the time it was minted, and
// 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 nil unless preloaded. // Post is a blog entry. Author is loaded with Preload("Author") by the post
// 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"`
@@ -40,20 +75,27 @@ type Post struct {
Content string `json:"content"` Content string `json:"content"`
} }
// Message is a chat message; the WebSocket hub keeps only the latest 50. // Message is one chat message. The table is capped at 50 rows by the
// AuthorID is the hub's per-process connection number, not a User ID. // WebSocket hub, which soft-deletes older ones on every insert.
//
// 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"`
// Visible only to admins. // Private messages are visible only to admins; both the WebSocket
// 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. // Activity is a "currently doing" entry on the home page. Structurally
// 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"`
@@ -75,9 +117,13 @@ type Favorite struct {
Link *string `json:"link"` Link *string `json:"link"`
} }
// Rowing is one rowing machine session read from a photo of the display. // Rowing is one rowing machine session, created by uploading a photo of the
// Date is the photo's EXIF time and the dedup key. Time is seconds, Distance // display (see handlers.CreateRowing).
// 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"`
@@ -100,7 +146,9 @@ type Bookmark struct {
Link string `gorm:"not null" json:"link"` Link string `gorm:"not null" json:"link"`
} }
// Place is a places-to-go entry; any signed-in user may edit it. // Place is an entry on the places-to-go list. Creating or editing one needs
// 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"`
@@ -116,15 +164,20 @@ 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 is a page key ("index" or a Page.Slug), // Box is one panel on a canvas page. Page names the canvas it belongs to:
// not a foreign key. Geometry is px on a fixed 1400px-wide canvas. "html" // "index" for the landing page, or a Page.Slug for an admin-created page
// boxes render in a sandboxed iframe. // (the home page is the Page "stp") — it is a key, not a foreign key, so the
// 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"`
// Boxes from before pages existed migrate to "stp". // default:stp is what the boxes that predate pages are migrated to.
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"`
@@ -135,20 +188,30 @@ 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: GORM skips zero values on insert, so default:true would // No gorm default on Framed: GORM omits zero values for defaulted columns
// turn an explicit false into true. CreateBox defaults it. // on insert, so default:true would turn an explicit false into true.
// CreateBox applies the true default itself.
Framed bool `gorm:"not null" json:"framed"` Framed bool `gorm:"not null" json:"framed"`
// A CSS box-shadow, or "". // Shadow is a CSS box-shadow value drawn around the box, or "" for none.
// 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 bool `gorm:"not null;default:false" json:"adminOnly"` // AdminOnly boxes are never sent to anyone but an admin (the boxes
// The box shows the component's HTML (its own is nil). No association // resolver filters them out), so they suit private notes.
// field, or DB.Save(&box) would write the component back too. AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
// 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 at /<Slug>. The unique index is // Page is an admin-created canvas page, served by the SPA's catch-all route
// partial so a soft-deleted slug can be reused. // at /<Slug> (e.g. "shrines/evangelion"). Its content is the Boxes whose Page
// 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"`
@@ -156,40 +219,60 @@ 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 bool `gorm:"not null;default:false" json:"adminOnly"` // AdminOnly hides the whole page, boxes included, from everyone else.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
} }
// Background is a canvas page's background; no row means the theme default. // Background is the page background behind one canvas (Page is the same page
// 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"`
// "" means the theme colour. // Color is a CSS colour, or "" for the theme's page 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"`
// "cover", "contain" or "tile". // Fit is how Image fills the window: "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 saved snapshot of a page's boxes and background. Loading it // Layout is a named copy of one canvas page's boxes and background, saved so
// creates new boxes, so nothing stays linked. Stored as JSON because it is // it can be loaded onto any page later (graph/layout_helpers.go). It is a
// only ever read and written whole. // snapshot, not a link: loading it creates new boxes that belong to the
// 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 string `gorm:"not null" json:"sourcePage"` // SourcePage is the page key it was saved from, for the list only.
// JSON array of box content and geometry, without id or page. SourcePage string `gorm:"not null" json:"sourcePage"`
Boxes string `gorm:"type:text;not null" json:"-"` // Boxes is a JSON array of the boxes' content and geometry, without id
// 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. Linked boxes share only its HTML; the other // Component is a named HTML box that can be placed on any canvas page, either
// fields are the defaults for a newly placed box. // as a copy (an ordinary box) or linked (a box with ComponentID set). Linked
// 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"`
@@ -200,13 +283,17 @@ 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, as for Box.Framed. // No gorm default on Framed, for the same reason as 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; Body is JSON in views/CV/coverLetter.js's shape. // CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the
// 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"`
@@ -216,7 +303,9 @@ 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 cover-letter paragraph; Section only groups the bank. // CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into
// 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"`
+122 -40
View File
@@ -11,13 +11,20 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// Auth mints and verifies HS256 JWTs. Revocation is by User.TokenVersion: // Auth mints and verifies the HS256 JWTs that back the site's login. Tokens
// every token carries it as "tv", and bumping it kills them all. // are handed to the browser as HTTP-only cookies (see handlers.Store.Login).
//
// 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
} }
// Domain is the cookie domain; Endpoint is the backend's public base URL. // AuthConfig carries the signing secret and cookie/token lifetimes. Domain is
// 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
@@ -26,13 +33,16 @@ 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 panics on a short secret: HS256 accepts a zero-length key, which // InitAuth builds the Auth service from config. An absent or too-short
// would make admin tokens forgeable. // secret is fatal: HS256 happily signs and verifies with a zero-length key,
// 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)")
@@ -41,8 +51,18 @@ func InitAuth(config *AuthConfig) *Auth {
return &Auth{Config: config} return &Auth{Config: config}
} }
// GenerateJWT issues an access/refresh pair. The admin claim is informational: // GenerateJWT issues an access/refresh pair for user.
// 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,
@@ -71,13 +91,20 @@ func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil
} }
// The key is fixed; VerifyJWT pins the algorithm, which is what stops // keyFunc supplies the HMAC secret to the JWT parser. The token argument is
// algorithm-confusion attacks. // ignored because only one key is ever in use; VerifyJWT separately pins the
// 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 returns the claims. Numbers decode as float64. // VerifyJWT parses and validates a signed token, returning its claims.
// 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 {
@@ -92,16 +119,31 @@ func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
return &claims, nil return &claims, nil
} }
// Distinct so REST and GraphQL can each map them to their own status codes. // Typed errors returned by AuthenticateToken so each call site can keep its
// 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 = errors.New("invalid token") // ErrInvalidToken means the token is missing, malformed, expired or not
// 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 = errors.New("user not found") // ErrUserNotFound means the token named a user that no longer exists (or
ErrTokenRevoked = errors.New("token revoked") // has been soft deleted).
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 treats 0 (old rows, tokens without "tv") as 1, the column // tokenVersionOf normalises a stored or claimed token version.
// 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
@@ -109,46 +151,66 @@ func tokenVersionOf(v uint) uint {
return v return v
} }
// AuthenticateToken turns a token into a user, checking signature, expiry, // AuthenticateToken is the one place a token string is turned into a user: it
// the user row and the token version. Errors are always the sentinels above. // verifies the signature and expiry, reads the id claim, loads the row, and
// 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 also returns the claims, for "admin". It costs // AuthenticateTokenWithClaims is AuthenticateToken plus the raw claims, for
// one SELECT per request, which is the price of revocation. // the middlewares that go on to read claims the User struct does not carry
// (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
} }
// Soft-deleted users are excluded, so a deleted account fails here. // Pre-setting the primary key and calling First with no explicit
// 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 revokes all of userID's tokens. COALESCE treats a NULL // BumpTokenVersion invalidates every token previously issued to userID by
// version as 1. // incrementing the user's version counter. Callers treat a failure as
// 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).
@@ -156,23 +218,43 @@ func BumpTokenVersion(db *gorm.DB, userID uint) error {
Error Error
} }
const ( // SetAuthCookies writes the access/refresh cookie pair.
secure = true //
httpOnly = true // It lives in services because both handlers and graph need it and handlers
) // 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. //
// SameSite=Lax survives the redirect back from an OAuth provider. // gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
// 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("access_token", tokens.AccessToken, int(config.AccessTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly) gc.SetCookie(
gc.SetCookie("refresh_token", tokens.RefreshToken, int(config.RefreshTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly) "access_token",
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 must match SetAuthCookies' attributes, or the browser // ClearAuthCookies expires both auth cookies. The max-age of -1 is what tells
// keeps the originals. // the browser to delete them; path, domain and the Secure/HttpOnly flags must
// 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, secure, httpOnly) gc.SetCookie("access_token", "", -1, "/", config.Domain, true, true)
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, secure, httpOnly) gc.SetCookie("refresh_token", "", -1, "/", config.Domain, true, true)
} }
+20 -4
View File
@@ -10,8 +10,20 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Token expiry and cookie attributes. Cookies are checked through a real gin // Companion to auth_test.go, covering the two pure things it leaves out: the
// context, since gin builds the header. // expiry the minting code bakes into each token, and the cookie attributes
// 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.
@@ -28,7 +40,9 @@ func cookiesFrom(fn func(*gin.Context)) map[string]*http.Cookie {
return out return out
} }
// Cookie max-age is derived from the same lifetime. // exp must track the configured lifetime, because the cookie max-age is derived
// 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()
@@ -110,7 +124,9 @@ func TestSetAuthCookies(t *testing.T) {
} }
} }
// A deletion that differs in path, domain or flags silently fails. // A browser only replaces a cookie when path, domain and flags match the
// 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) {
+15 -3
View File
@@ -9,8 +9,12 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
// Stops short of the row lookup (no DB in CI); revocation is covered via // The tests below deliberately stop short of AuthenticateToken's happy path:
// tokenVersionOf. // that branch needs a live *gorm.DB and the only driver in go.mod is postgres,
// 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{
@@ -43,6 +47,9 @@ 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
@@ -97,6 +104,9 @@ 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})
@@ -181,7 +191,9 @@ func TestVerifyJWTRejections(t *testing.T) {
} }
} }
// Both return before the row lookup, so a nil DB is safe. // A verified token with no usable id is a server-side inconsistency, not a
// 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 {
+14 -4
View File
@@ -18,7 +18,9 @@ type SQLConfig struct {
Port string Port string
} }
// sslmode=disable: Postgres is only on the Docker network. // connectToPostgreSQL opens the GORM connection. sslmode=disable is safe
// 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",
@@ -33,8 +35,12 @@ func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
return db, nil return db, nil
} }
// AutoMigrate never drops or renames, so removed fields leave columns and // migrateDatabase brings the schema up to date. This project has no
// renamed ones start empty. New models must be listed here. // migration files: GORM's AutoMigrate is the only schema source, so it will
// 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{},
@@ -60,7 +66,11 @@ func migrateDatabase(db *gorm.DB) error {
return ensureStpPage(db) return ensureStpPage(db)
} }
// ensureStpPage creates the /stp Page row once. Unscoped, so deleting it sticks. // ensureStpPage turns the home page (/stp) into an ordinary canvas Page once.
// 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 {
+23 -7
View File
@@ -8,27 +8,35 @@ import (
"time" "time"
) )
// The latest Gitea push, for the home page. // This file talks to the self-hosted Gitea instance over the private Docker
// 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).
// Gitea's own capitalised keys. // GiteaFeedCommit is one commit inside a push event's Content payload.
// The capitalised JSON keys are Gitea's, not a typo.
type GiteaFeedCommit struct { type GiteaFeedCommit struct {
Message string `json:"Message"` Message string `json:"Message"`
} }
// Push events' Content is this, as a JSON string; see ParseCommitMessage. // GiteaFeedContent is the shape of the JSON *string* stored in
// 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"`
@@ -37,8 +45,13 @@ type GiteaFeedResponse struct {
Created time.Time `json:"created"` Created time.Time `json:"created"`
} }
// FetchLatestFeed returns (nil, nil) for an empty feed. Unauthenticated: the // FetchLatestFeed returns the single most recent public activity entry for
// public feed needs no token. // user "adamf", or (nil, nil) when the feed is empty — callers must handle
// 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)
@@ -66,8 +79,11 @@ func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
return &items[0], nil return &items[0], nil
} }
// ParseCommitMessage decodes JSON-in-a-string. Non-push events don't parse, // ParseCommitMessage pulls the first commit message out of a feed entry's
// which yields "". // Content field, which Gitea delivers as JSON encoded inside a JSON string
// (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 {
+7 -2
View File
@@ -26,8 +26,13 @@ func InitNotes(config *NotesConfig) *Notes {
} }
} }
// ParsePath appends the separator before the prefix check, so a sibling such // ParsePath resolves a user-supplied request path to an absolute path inside
// as /backend/notes-private can't pass. // the notes directory, or returns an error if it would escape.
//
// 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
@@ -1,44 +0,0 @@
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
@@ -1,67 +0,0 @@
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)
}
})
}
}
+21 -5
View File
@@ -6,28 +6,44 @@ import (
"adam-french.co.uk/backend/models" "adam-french.co.uk/backend/models"
) )
// Grantable per-service permissions for non-admins; admins pass every check. // Per-service permissions: how a non-admin account is let into one gated
// To add one: an entry below, then `import permission_gate <key>` on its // service (the receipt printer, say) without being made an admin.
// route in caddy/routes.caddy. //
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// 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
} }
// Removed keys are inert: the validate endpoint 404s them. // PermissionTypes is the full set of grantable permissions, in display order.
// 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 reads the row, not the token. // HasPermission reports whether user may use the service gated on key. It
// 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)
} }
+1 -1
View File
@@ -19,7 +19,7 @@ func TestValidPermission(t *testing.T) {
} }
} }
// Keys must be URL-path safe: Caddy splices them into /auth/validate/<key>. // Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) { func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{} seen := map[string]bool{}
for _, p := range PermissionTypes { for _, p := range PermissionTypes {
+40 -11
View File
@@ -10,25 +10,49 @@ import (
"time" "time"
) )
// CallPython is how the backend reaches the Python service's /internal/ // Every Claude call the site makes lives in the Python service, behind an
// routes, container to container (Caddy refuses them, and they refuse // /internal/ route. This file is the one way the Go backend reaches those
// proxied requests). // routes. The only caller now is the rowing photo reader
// (handlers/handle_rowing.go); the job posting reader, email classifier and
// lead scorer went with the job tracker to its own repo.
//
// The routes are internal in a specific sense: nginx answers 404 for
// /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.
// Above Python's own worst case (30s Claude timeout, two retries), so a slow // pythonClient bounds the wait on the Python service. Two minutes sits above
// Claude surfaces as Python's error. // that side's own worst case (a 30s Claude timeout, retried twice with
// 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 the `detail` of a 502: one of the route's fixed messages, // PythonError is a failure the Python service reported in words that are safe
// safe to show a user. Every other failure is a plain error, for the log only. // and useful to show a person: the string `detail` of a 502, which is always
// 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 and decodes a 200 into T; anything else is an // CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into
// error. baseURL has no trailing slash. // T. baseURL is the service's address on the Docker network with no trailing
// 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)
@@ -47,8 +71,12 @@ 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 {
// Only a 502's detail is user-facing: a 422's is a list (fails to // FastAPI errors are {"detail": ...}. Only a 502 carries one of the
// decode) and a 503's names an env var. // route's own fixed messages; a 422's detail is a list, which fails
// 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"`
} }
@@ -60,6 +88,7 @@ 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)
} }
+1 -1
View File
@@ -36,7 +36,7 @@ func TestCallPythonRequestAndReply(t *testing.T) {
) )
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) { url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type") method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
// The Python routes treat either header as "came through Caddy" and // The Python routes treat either header as "came through nginx" and
// answer 404, so the helper must never send them. // answer 404, so the helper must never send them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != "" forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil { if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+27 -25
View File
@@ -1,5 +1,7 @@
// Package services holds the backend's stateful collaborators, reached // Package services holds the backend's stateful collaborators: the database
// through handlers.Store. // handle, JWT signing, the chat WebSocket hub, third-party API clients
// (Spotify, Steam, Gitea, Claude) and the email-sync pipeline. Handlers and
// GraphQL resolvers reach them through handlers.Store.
package services package services
import ( import (
@@ -7,15 +9,24 @@ import (
"time" "time"
) )
// RateLimiter is an in-memory sliding window per key, behind Caddy's limits. // RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
// string (in practice the client IP). It is process-local: restarting the
// backend clears every window, and a multi-replica deployment would limit
// per replica rather than globally. Nginx applies its own rate limits in
// 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 map[string][]time.Time // attempts holds the timestamps of recent allowed attempts per key.
max int // Keys are never evicted, so memory grows with the number of distinct
window time.Duration // client IPs seen since start-up; acceptable for a personal site, but
lastSweep time.Time // worth knowing before reusing this elsewhere.
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),
@@ -24,16 +35,21 @@ func NewRateLimiter(max int, window time.Duration) *RateLimiter {
} }
} }
// Allow doesn't record rejected attempts, so hammering doesn't extend a lockout. // Allow records an attempt for key and reports whether it is within the
// 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)
// Filtered in place, reusing the backing array. // Filter in place: slicing to [:0] reuses the existing backing array, so
// 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) {
@@ -49,17 +65,3 @@ 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)
}
}
}
+4 -1
View File
@@ -9,7 +9,10 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// SeedDatabase is dev only: it creates an admin with password "password". // SeedDatabase populates an empty database with demo content for local
// 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.
+15 -14
View File
@@ -8,7 +8,18 @@ import (
"time" "time"
) )
// Expiry uses the real clock, hence the tiny window. // Covered here: the pure logic in ratelimit.go, notes.go and gitea.go —
// 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) {
@@ -58,16 +69,6 @@ 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") {
@@ -162,7 +163,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/stpweb", "html_url": "http://gitea:3000/adamf/stpweb"}, "repo": {"full_name": "adamf/web_server", "html_url": "http://gitea:3000/adamf/web_server"},
"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",
@@ -181,10 +182,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/stpweb" { if got.Repo.FullName != "adamf/web_server" {
t.Errorf("FullName = %q", got.Repo.FullName) t.Errorf("FullName = %q", got.Repo.FullName)
} }
if got.Repo.HTMLURL != "http://gitea:3000/adamf/stpweb" { if got.Repo.HTMLURL != "http://gitea:3000/adamf/web_server" {
t.Errorf("HTMLURL = %q", got.Repo.HTMLURL) t.Errorf("HTMLURL = %q", got.Repo.HTMLURL)
} }
if got.OpType != "commit_repo" { if got.OpType != "commit_repo" {
+39 -8
View File
@@ -13,17 +13,26 @@ 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
} }
// On a mounted volume, so the OAuth dance survives rebuilds. // SPOTIFY_TOKEN_JSON_PATH is inside a Docker volume, so the refresh token
// 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 writes its own struct so the file format doesn't follow // SaveSpotifyToken persists an OAuth token to disk.
// 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"`
@@ -46,9 +55,13 @@ 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 {
@@ -76,8 +89,16 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
return tok, nil return tok, nil
} }
// InitSpotifyAuth never fails startup: with no usable token it returns a nil // InitSpotifyAuth builds the OAuth authenticator and, if a saved token
// client, so every caller must nil-check Store.SpotifyClient. // exists, an authenticated client.
//
// 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),
@@ -90,12 +111,14 @@ 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.")
@@ -105,10 +128,18 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
return auth, client return auth, client
} }
// RefreshClient saves the new token, ignoring write errors. The client's // RefreshClient exchanges a stored token for a fresh one and returns a client
// later automatic refreshes are not persisted. // using it.
//
// 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) {
// The client outlives the request that created it. // context.Background rather than a request context: the resulting client
// 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)
+13 -3
View File
@@ -8,6 +8,10 @@ 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 {
@@ -26,7 +30,10 @@ type SteamRecentGamesResponse struct {
} `json:"response"` } `json:"response"`
} }
// PersonaState > 0 is some kind of online. // SteamPlayerSummary is the subset of GetPlayerSummaries we care about.
// 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"`
} }
@@ -38,8 +45,11 @@ type SteamPlayerSummariesResponse struct {
} `json:"response"` } `json:"response"`
} }
// Steam answers 200 with nothing for a private profile or bad key, so empty // FetchRecentlyPlayedGames returns the three most recently played games.
// 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)
+37 -6
View File
@@ -7,21 +7,42 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// TrafficLogFormatter replaces gin.Logger: heartbeat and forward_auth traffic // This file replaces gin.Logger with a formatter tuned for one reader: the
// is dropped or terse, while external IPs, errors and slow requests stand out. // site owner scanning the log for "who is using my site". Two goals:
//
// 1. Quietness. The log is flooded by traffic that is not a human visit:
// nginx auth_request subrequests (/auth/validate-admin, re-run for every
// 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, // nginx auth_request 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
} }
// The permission gate's subrequests, as for /auth/validate-admin. // logQuietDropPrefix is the permission gate's auth_request subrequest
// (/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 {
@@ -35,6 +56,8 @@ 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"
@@ -42,7 +65,9 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
marker = " !!" marker = " !!"
} }
// Failures on these are still worth seeing. // All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
// 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 ""
} }
@@ -50,6 +75,9 @@ 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 (nginx'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
} }
@@ -57,8 +85,11 @@ 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. nginx 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 {
// The Docker bridge: infrastructure, not a visitor. // Docker's bridge network: nginx's own feet. Not a visitor.
return !startsWith(ip, "172.28.") return !startsWith(ip, "172.28.")
} }
+100 -28
View File
@@ -22,25 +22,51 @@ import (
"github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3"
) )
// Every stored file goes through Uploads.Save. An *UploadError is the // Uploaded files: everything the site stores from a user and serves back at
// uploader's fault and safe to show; any other error is ours. // /uploads/. One entry point for any handler that takes a file:
// Public files go to Garage, falling back to the volume; private files //
// always go to the volume, because Caddy can gate a path but can't sign S3. // url, err := store.Uploads.Save(ctx, fileHeader, private)
//
// 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. nginx
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (nginx.conf.template), so the URL is the same wherever the
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
// the only store.
// Private files (admin-only chat attachments) always go to the volume, under
// /uploads/private/, which nginx gates behind an admin check. nginx can't
// sign S3 requests, so it has no way to gate a bucket.
//
// Everything public is reachable by anyone who has the URL, with no login.
// That is why the type checks below are strict, and why names are random.
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
// disk or the bucket; nginx rate-limits the route as well.
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 {
// Served back as-is, and Caddy sends nosniff, so it must be right. // ContentType is stored with the file and served back with it. Garage
// returns exactly this, and the browser renders by it: nginx adds
// `nosniff`, so a wrong type means the file doesn't display.
ContentType string ContentType string
// What http.DetectContentType must report. Empty skips the check, which // SniffPrefix is what http.DetectContentType must report for the file's
// is unreliable for audio and gif. // first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty
// 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. Never add anything a browser would execute // UploadTypes is the allow-list, keyed by lower-cased extension with its dot.
// or render as markup: these are served from our origin. Mirrored by // Nothing a browser would execute or render as markup (.html, .svg, .js, ...)
// vue/src/uploads.js's ACCEPT. // may ever be added: these files are served from our own origin. The
// 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/"},
@@ -55,6 +81,8 @@ 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 }
@@ -66,17 +94,26 @@ 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; nginx owns both paths.
const ( const (
publicURLPrefix = "/uploads/" publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/" privateURLPrefix = "/uploads/private/"
) )
// NewUploads falls back to the volume alone when S3 is unset or misconfigured. // NewUploads picks the stores. publicDir and privateDir are directories on the
// 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}}
@@ -93,7 +130,9 @@ func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
return u return u
} }
// Save stores one file and returns its URL. Only admins may save private files. // Save validates and stores one uploaded file and returns its URL
// (/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
@@ -111,7 +150,8 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
defer f.Close() defer f.Close()
if kind.SniffPrefix != "" { if kind.SniffPrefix != "" {
// A short read is fine; only an empty file fails. // 512 bytes is all http.DetectContentType looks at. A short read is
// 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 {
@@ -128,8 +168,9 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
} }
} }
// A random name rules out traversal and collisions, and makes the URL // The uploaded name is thrown away for 16 random bytes. That rules out
// unguessable. // path traversal and collisions in one go, and makes the URL 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)
@@ -146,6 +187,7 @@ 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"`
@@ -153,8 +195,16 @@ type StoredFile struct {
Modified time.Time `json:"modified"` Modified time.Time `json:"modified"`
} }
// List returns public uploads, newest first. Admin only: unguessable URLs are // List returns every public upload, newest first. Private files are never
// the only protection for unlinked files. Off-list extensions are dropped. // listed: they live in their own store, which this doesn't touch.
//
// 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 {
@@ -173,17 +223,22 @@ func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
// ---- Stores ---------------------------------------------------------------- // ---- Stores ----------------------------------------------------------------
// FileStore takes a ReadSeeker because S3 hashes the body before sending and // FileStore stores one file under key, and lists what it holds. r is a
// FallbackFileStore rewinds it to retry. List returns top-level files only. // ReadSeeker because the S3 client must hash the body before sending it over
// 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 {
// World-readable so Caddy, in another container, can serve them. // 0755 and 0644 so nginx, a different user, can reach and read the files.
if err := os.MkdirAll(d.Dir, 0755); err != nil { if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err return err
} }
@@ -198,7 +253,9 @@ func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _
return out.Close() return out.Close()
} }
// List skips directories, which keeps private/ out of the listing. // List skips subdirectories, which is what keeps the private/ directory
// (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) {
@@ -221,11 +278,13 @@ 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
@@ -234,7 +293,9 @@ type S3Config struct {
SecretAccessKey string SecretAccessKey string
} }
// Garage is on the same network, so anything near this is a hang. // s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on
// 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 {
@@ -242,9 +303,12 @@ 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 needs path-style addressing. // Garage addresses buckets by path (/bucket/key); virtual-host style
// would need a DNS name per bucket.
UsePathStyle: true, UsePathStyle: true,
// Default CRC32 checksums aren't reliably supported by non-AWS servers. // Recent SDKs add CRC32 checksums to every PUT by default. Only send
// 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,
}) })
@@ -268,7 +332,9 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
return nil return nil
} }
// List skips keys under a prefix: those were put there by hand. // List pages through the whole bucket. Keys containing "/" are skipped: they
// are not uploads (Save never makes one) but something put under a prefix by
// hand, and nginx's /uploads/<name> only ever serves a top-level name anyway.
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()
@@ -291,8 +357,10 @@ func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
return files, nil return files, nil
} }
// FallbackFileStore writes to Fallback when Primary fails. Caddy serves from // FallbackFileStore tries Primary and, if that fails, logs it and writes to
// both, so the URL still works. // Fallback instead. The upload still succeeds and its URL still works (nginx
// 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
@@ -310,7 +378,11 @@ 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 merges both stores, primary first, since Caddy serves from both. // List is the union of both stores, since nginx serves from both: the
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the
// 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 {
+7 -1
View File
@@ -17,7 +17,13 @@ import (
"time" "time"
) )
// A successful Garage write is checked by hand (DEPLOYMENT.md, "Garage"). // Covered here: the type table (the upload trust boundary's data), Save's
// 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.
+75 -56
View File
@@ -1,8 +1,8 @@
package services package services
import ( import (
"log"
"net/http" "net/http"
"net/url"
"sync" "sync"
"time" "time"
@@ -12,58 +12,68 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
// The chat hub behind GET /ws: one process, one room, so package-level state. // This file is the chat hub behind GET /ws. It is deliberately a package-level
// 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.
// History replayed on connect, and rows kept in the database. // maxMessages is both the size of the history replayed to a new client and the
// 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
// CheckOrigin is the only cross-origin defence: browsers send cookies on a // Upgrader turns the HTTP request into a WebSocket.
// WebSocket handshake with no preflight. Gorilla's same-host default would //
// reject the apex/www split and the Vite dev server. // CheckOrigin is the only cross-origin defence on this endpoint: the browser
// 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")
return origin != "" && IsSiteOrigin(origin, allowedDomain) if origin == "" {
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)
// Also serialises write-then-broadcast so all clients see one order. // mu guards clients AND serialises the write-then-broadcast sequence, so
// 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
// Per-process connection number, not a user id; chat is pseudonymous. // nextAuthorID is a per-process counter handed out on connect. It is NOT
// 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-socket flood limit (frames, not requests per IP). // Per-connection flood limit, separate from services.RateLimiter because it
// counts frames on one socket rather than requests from one IP.
const ( const (
rateLimitWindow = time.Second rateLimitWindow = time.Second
rateLimitMaxMsgs = 10 rateLimitMaxMsgs = 10
) )
// The route is public, so frame and field sizes are capped. Writes happen // wsIncoming is the envelope clients send over the socket. A plain chat
// under mu, so a stalled client may hold it for at most writeWait. // message carries text/fileUrl/private; an admin delete carries action+id.
// 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"`
@@ -72,29 +82,37 @@ 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"`
} }
// Sent as one batch so a reconnect replaces the list without blanking it. // wsHistoryEvent is sent once on connect with the recent messages the client
// 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
} }
// isAdmin allows seeing, sending and deleting private messages. // HandleWebSocket serves one chat connection. isAdmin controls whether the
// 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)
// Register and snapshot under one lock, so a concurrent broadcast is // Registration, history read and history send all happen under one lock.
// either in the history or delivered after it, never lost or reordered. // That is the point: it guarantees the client is already in `clients`
// 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++
@@ -105,23 +123,24 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
if !isAdmin { if !isAdmin {
historyQuery = historyQuery.Where("private = ?", false) historyQuery = historyQuery.Where("private = ?", false)
} }
if err := historyQuery.Find(&history).Error; err != nil { historyQuery.Find(&history)
log.Printf("[ws] loading history: %v", err)
}
if err := writeJSON(conn, wsHistoryEvent{Action: "history", Messages: history}); err != nil { if err := conn.WriteJSON(wsHistoryEvent{Action: "history", Messages: history}); err != nil {
delete(clients, conn) delete(clients, conn)
mu.Unlock() mu.Unlock()
return return
} }
mu.Unlock() mu.Unlock()
// Over-limit frames are dropped silently. // Fixed-window flood limit. Over-limit frames are dropped silently with
// 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
} }
@@ -143,35 +162,33 @@ 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,
Private: incoming.Private && isAdmin, // Only admins may mark a message private.
Private: incoming.Private && isAdmin,
} }
mu.Lock() mu.Lock()
if err := wsDB.Create(&msg).Error; err != nil { wsDB.Create(&msg)
mu.Unlock() // Keep only the newest maxMessages rows. This is a soft delete
log.Printf("[ws] saving message: %v", err) // (models.Message has gorm.DeletedAt), so the rows stay in the table
continue // with deleted_at set and GORM filters them out of later reads; the
} // table therefore grows forever even though the chat does not.
// Soft delete, so the table still grows; the chat does not. // The subquery is itself soft-delete filtered, so already-trimmed
if err := wsDB.Where("id NOT IN (?)", // rows are not re-deleted.
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{}).Error; err != nil { ).Delete(&models.Message{})
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 := writeJSON(client, msg); err != nil { if err := client.WriteJSON(msg); err != nil {
client.Close() client.Close()
delete(clients, client) delete(clients, client)
} }
@@ -184,7 +201,9 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
mu.Unlock() mu.Unlock()
} }
// deleteMessage soft-deletes and broadcasts; clients ignore unknown ids. // deleteMessage soft-deletes a message and tells every client to drop it.
// 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()
@@ -196,7 +215,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 := writeJSON(client, event); err != nil { if err := client.WriteJSON(event); err != nil {
client.Close() client.Close()
delete(clients, client) delete(clients, client)
} }
-6
View File
@@ -1,6 +0,0 @@
**/.git
**/.DS_Store
# The certificate store (private keys) is bind-mounted at runtime, never sent
# to the build.
data
edge_test.sh
-229
View File
@@ -1,229 +0,0 @@
# Global options and shared snippets. Routes are in routes.caddy; per-mode
# sites in sites/<CADDY_SITE>.caddy. {$X} is substituted at parse time and
# saved into /config, so secrets are read as {env.X} instead.
{
# No `email`: with EMAIL unset that line is a parse error.
# Count requests before forward_auth asks the backend.
order rate_limit before basic_auth
# Stops `tls internal` trying to edit the container's trust store.
skip_install_trust
servers {
# Trust CF-Connecting-IP only from cloudflared's fixed IP. Trusting the
# subnet would let direct visitors (via the bridge gateway) pick their IP.
trusted_proxies static 172.28.255.250
client_ip_headers CF-Connecting-IP
# 443/udp is not published.
protocols h1 h2
}
# Keep access logs out of the default logger, or bodies print unfiltered.
log default {
exclude http.log.access.payloads
}
# One JSON line per request, body included. A body mentioning a password,
# token or secret is redacted whole: there is no JSON parser here.
log payloads_file {
include http.log.access.payloads
output file /var/log/caddy/payloads.log {
roll_size 50MiB
roll_keep 5
mode 0644
}
format filter {
wrap json
fields {
req_body regexp "(?is)^.*(password|token|secret).*$" "[redacted]"
}
}
}
# One short line per request for `docker logs` and Dozzle.
log payloads_stdout {
include http.log.access.payloads
output stdout
format filter {
wrap console
fields {
req_body delete
request>headers delete
request>tls delete
resp_headers delete
}
}
}
}
# ---- Snippets ----------------------------------------------------------------
# Overwrite X-Forwarded-For rather than append, so upstreams see only the
# visitor, not cloudflared.
(proxy) {
header_up X-Real-IP {client_ip}
header_up X-Forwarded-For {client_ip}
}
# import limit <zone> <events> <window>: sliding window per client IP.
# A zone name is one shared bucket, so it must always get the same numbers.
(limit) {
rate_limit {
zone {args[0]} {
key {client_ip}
events {args[1]}
window {args[2]}
}
}
}
# forward_auth sends no body. orig_uri because strip_prefix runs first; the
# `*` stops redir reading the target as a path matcher.
(admin_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate-admin
@denied status 401 403
handle_response @denied {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
}
}
# import permission_gate <key>. 403 goes to /no-access, not the login page.
# copy_headers drops any client-sent X-Remote-User, so upstreams can trust it.
(permission_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate/{args[0]}
copy_headers X-Auth-User>X-Remote-User
@unauthenticated status 401
handle_response @unauthenticated {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
@forbidden status 403
handle_response @forbidden {
redir * /no-access?path={http.request.orig_uri} 302
}
}
}
# Production only: HSTS on localhost would affect every local project.
(security_headers) {
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Strict-Transport-Security "max-age=63072000; includeSubDomains"
}
}
# Uploads are attacker-supplied bytes on our origin. `>` makes these win over
# Garage's headers.
(upload_headers) {
header {
>X-Content-Type-Options "nosniff"
>Content-Disposition "inline"
>Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'"
-Server
-Via
}
}
# Serves /uploads/ from disk via the :2080 site. A proxy, not file_server,
# because in an error route file_server replies with the error's status.
# Error routes don't inherit deferred headers, hence the import.
(uploads_disk) {
import upload_headers
rewrite * {http.request.orig_uri.path}
reverse_proxy 127.0.0.1:2080
}
(errors) {
# 503, not 429: hotelsStream.js reads 429 as the Python service's own limit.
handle_errors 429 {
respond "Too many requests from your address. Wait a moment and retry." 503
}
# Keyed on vars set by the route, which cannot be spoofed like a path.
handle_errors 502 504 {
@uploads_fallback vars uploads_fallback yes
handle @uploads_fallback {
import uploads_disk
}
@receipt_offline vars receipt_upstream yes
handle @receipt_offline {
respond "The receipt printer machine is offline." 503
}
@radar_offline vars radar_upstream yes
handle @radar_offline {
respond "Partner Radar is offline." 503
}
@garage_offline vars garage_upstream yes
handle @garage_offline {
respond "The Garage admin UI (stpcore) is offline." 503
}
}
}
# Bodies are buffered in memory to log them, so only small non-upload ones.
(logging) {
log payloads
@small_body {
# Spelt out: {1,5} would parse as a placeholder.
header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
}
# `<` must be explicit, or the body is logged a second time, empty.
log_append @small_body <req_body {http.request.body}
}
# Explicit types so streamed responses (ndjson, SSE, audio) are never buffered.
(encode) {
encode zstd gzip {
minimum_length 256
match {
header Content-Type text/html*
header Content-Type text/plain*
header Content-Type text/css*
header Content-Type text/javascript*
header Content-Type application/javascript*
header Content-Type application/json*
header Content-Type application/xml*
header Content-Type image/svg+xml*
}
}
}
(common) {
import logging
import errors
import encode
header {
-Server
-Via
}
}
# ---- Container healthcheck (unlogged) ----------------------------------------
http://127.0.0.1 {
respond /caddy-health 204
respond 404
}
# ---- Uploads disk site (loopback only, unlogged) -----------------------------
# private/ is refused here too, in case the gated route is ever reordered.
http://:2080 {
bind 127.0.0.1
@private path /uploads/private /uploads/private/*
handle @private {
respond 404
}
handle /uploads/* {
root * /srv
file_server
}
respond 404
}
import sites/{$CADDY_SITE:prod}.caddy
-32
View File
@@ -1,32 +0,0 @@
# Caddy plus the Cloudflare DNS and rate-limit plugins. caddy-ratelimit is
# pinned to a commit (no usable release), so Renovate leaves it; bump by hand.
# Builder and runtime tags move together.
# The last RUN validates the config for both modes, so a bad config fails the
# build before any running container is replaced.
FROM caddy:2.11.9-builder AS builder
RUN xcaddy build \
--with github.com/caddy-dns/[email protected] \
--with github.com/mholt/caddy-ratelimit@5625512f24f6f59d6f64fb3aafe5eecff0b286db
FROM caddy:2.11.9
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile routes.caddy /etc/caddy/
COPY sites/ /etc/caddy/sites/
# A log directory that can't be opened stops the config loading.
RUN mkdir -p /var/log/caddy /srv/www /srv/uploads
RUN set -e; \
for site in prod dev; do \
echo "caddy validate (CADDY_SITE=$site)"; \
env XDG_DATA_HOME=/tmp/validate XDG_CONFIG_HOME=/tmp/validate \
CADDY_SITE=$site DOMAIN=example.com EMAIL=[email protected] \
BACKEND_HOST=backend BACKEND_PORT=8080 BACKEND_ENDPOINT=/api \
ICECAST_HOST=icecast2 ICECAST_PORT=8000 \
GITEA_HOST=gitea GITEA_PORT=3000 \
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_PORT=3000 \
PYTHON_HOST=python PYTHON_PORT=8000 \
RECEIPT_WEB_UPSTREAM=127.0.0.1:9 RECEIPT_WEB_TOKEN=validate \
STPPRIV_LAN_IP=192.0.2.1 \
CLOUDFLARE_DNS_API_TOKEN=validate-placeholder-token-0000000000000 \
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile; \
done; \
rm -rf /tmp/validate /var/log/caddy/*
-190
View File
@@ -1,190 +0,0 @@
#!/usr/bin/env bash
# Probes the edge. ok/FAIL lines (privacy denials and gates) set the exit
# status; show/hdr lines depend on data, so diff two runs instead.
# caddy/edge_test.sh <www-origin> [curl options...]
# e.g. https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 (on stpvm)
# https://localhost -k (dev)
# Optional env: EDGE_APEX, EDGE_HTTP, EDGE_COOKIE (admin session),
# EDGE_UPLOAD (an existing upload's name). Read-only: GETs plus one POST that
# the edge refuses.
set -u
if [ $# -lt 1 ]; then
echo "usage: $0 <base-url> [curl options...]" >&2
exit 2
fi
BASE=${1%/}
shift
CURL_OPTS=("$@")
FAILED=0
# The www host, without scheme or port.
BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')
# "<status> <location>"; a redirect to www is shown as its path alone.
probe() {
local url=$1 out
shift
out=$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{redirect_url}' \
"${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null) || out=ERR
printf '%s' "$out" | sed -E "s#^([0-9]+) [a-z]+://$BASE_HOST(:[0-9]+)?/#\\1 /#"
}
# The first value of one response header, or "-".
header_of() {
local name=$1 url=$2 value
shift 2
value=$(curl -sS -o /dev/null -D - --max-time 15 "${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null |
tr -d '\r' | grep -i "^$name:" | head -n 1 | cut -d: -f2- | sed 's/^ //')
printf '%s' "${value:--}"
}
# must <status> <location prefix, or -> <label> <path> [curl options]
must() {
local want_status=$1 want_loc=$2 label=$3 path=$4 got status loc ok=yes
shift 4
got=$(probe "$BASE$path" "$@")
status=${got%% *}
loc=${got#* }
[ "$status" = "$want_status" ] || ok=no
if [ "$want_loc" != "-" ] && [ "${loc#"$want_loc"}" = "$loc" ]; then
ok=no
fi
if [ $ok = yes ]; then
printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got"
else
printf 'FAIL %-12s %-58s %s (want %s %s)\n' "$label" "$path" "$got" "$want_status" "$want_loc"
FAILED=1
fi
}
# not_login <label> <path> [curl options]: anything but a redirect to the login.
not_login() {
local label=$1 path=$2 got
shift 2
got=$(probe "$BASE$path" "$@")
case $got in
ERR | "302 /admin/login"*)
printf 'FAIL %-12s %-58s %s (want: let through)\n' "$label" "$path" "$got"
FAILED=1 ;;
*) printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got" ;;
esac
}
# show <label> <url> [curl options]
show() {
local label=$1 url=$2
shift 2
printf 'show %-12s %-58s %s\n' "$label" "${url#"$BASE"}" "$(probe "$url" "$@")"
}
# hdr <url> <header...>
hdr() {
local url=$1 h
shift
for h in "$@"; do
printf 'hdr %-12s %-58s %s\n' "$h" "${url#"$BASE"}" "$(header_of "$h" "$url")"
done
}
LOGIN="/admin/login?redirect="
echo "# privacy boundary: must be 404"
for p in \
/notes/private/x /notes/Private/x /notes/a/private/x /notes/private \
/notes/templates/t /notes/.fs/private/x.md /notes/.fs/a/private/x.md \
/notes/.fs/.git/HEAD /notes/a/.obsidian/workspace.json /notes/a/.git/config \
/notes/.revisions/x.md /notes/private%2Fx /notes/%70rivate/x; do
must 404 - notes "$p"
done
must 404 - notes /notes/a/../private/x --path-as-is
must 404 - notes /notes/a//private/x --path-as-is
must 404 - py-internal /py/internal/rowing/read -X POST
must 404 - py-internal /py/internal/rowing/read
must 404 - py-internal /py/x/../internal/rowing/read --path-as-is -X POST
must 404 - py-internal /py//internal/rowing/read --path-as-is -X POST
echo "# admin gate, signed out: must redirect to the login, with the original URI"
for p in \
/tracker/ /tracker/dashboard \
/dozzle/ /garage/ /radio/admin/stats.xsl /uploads/private/x.png; do
must 302 "$LOGIN$p" gate "$p"
done
must 302 "${LOGIN}/uploads/x/../private/x.png" gate /uploads/x/../private/x.png --path-as-is
show gate "$BASE/TRACKER/"
must 302 "${LOGIN}/receipt/" permission /receipt/
if [ -n "${EDGE_COOKIE:-}" ]; then
echo "# admin gate, signed in: must be let through"
for p in /tracker/ /dozzle/ /garage/ /radio/admin/stats.xsl \
/receipt/; do
not_login gate "$p" -H "Cookie: $EDGE_COOKIE"
done
fi
echo "# carve-outs and public routes (status depends on the upstream)"
for p in /tracker/api/v1/events \
/tracker/tracker.user.js /tracker/readyz /usaco/ /notes/ /radio/status.xsl \
/py/ /py/docs /api/ /api/me /; do
show public "$BASE$p"
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"
for p in /api /radio /dozzle /garage /notes /py /usaco \
/tracker /receipt /cv/leads "/gitea?x=1"; do
show redirect "$BASE$p"
done
echo "# SPA"
for p in /admin /architecture /some-canvas-page /assets/does-not-exist.js; do
show spa "$BASE$p"
done
hdr "$BASE/" Content-Type Strict-Transport-Security X-Frame-Options \
X-Content-Type-Options Referrer-Policy Content-Security-Policy Server
hdr "$BASE/api/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/assets/does-not-exist.js" Cache-Control
hdr "$BASE/img/stamps/mine.gif" Access-Control-Allow-Origin Cache-Control
echo "# uploads"
show uploads "$BASE/uploads/does-not-exist.png"
hdr "$BASE/uploads/does-not-exist.png" X-Content-Type-Options Content-Security-Policy
if [ -n "${EDGE_UPLOAD:-}" ]; then
show uploads "$BASE/uploads/$EDGE_UPLOAD"
show uploads "$BASE/uploads/$EDGE_UPLOAD" -H "Range: bytes=0-9"
hdr "$BASE/uploads/$EDGE_UPLOAD" Content-Type X-Content-Type-Options \
Content-Disposition Content-Security-Policy Strict-Transport-Security
fi
if [ -n "${EDGE_APEX:-}" ]; then
APEX=${EDGE_APEX%/}
echo "# apex (production)"
show apex "$APEX/x?y=1"
show apex "$APEX/v2/"
hdr "$APEX/x" Strict-Transport-Security
fi
if [ -n "${EDGE_HTTP:-}" ]; then
echo "# plain http (production)"
show http "${EDGE_HTTP%/}/x?y=1"
fi
echo "# result: $([ $FAILED = 0 ] && echo all MUST cases passed || echo SOME MUST CASES FAILED)"
exit $FAILED
-298
View File
@@ -1,298 +0,0 @@
# The route table for both modes, imported inside a `route` block: the first
# matching handle wins, so denials go first and each carve-out precedes the
# prefix it is carved from. `path` is case-insensitive on the cleaned path;
# path_regexp is case-sensitive, hence (?i). caddy/edge_test.sh checks these.
# A gated route that loses its gate import is open to the internet.
# An inner limit cannot raise an outer one, so garage-webui's 2 GB is carved out here.
@body_default not path /garage/*
request_body @body_default {
max_size 50MB
}
# ---- Denials -----------------------------------------------------------------
# Called by the backend over app-network only; spends paid Claude calls.
handle /py/internal/* {
respond 404
}
# SB_SPACE_IGNORE only hides paths from listings, so these block direct
# fetches: private/ or templates/ at any depth, any dot-segment below the
# first (SilverBullet's own endpoints live at the first), and revisions.
# Keep the folder list in step with silverbullet-public's SB_SPACE_IGNORE.
# 404, not 403, so a private path's existence isn't confirmed.
@notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$)
handle @notes_private {
respond 404
}
@notes_dot path_regexp ^/notes/.+/\.
handle @notes_dot {
respond 404
}
handle /notes/.revisions* {
respond 404
}
# ---- Bare prefixes and moved URLs ----------------------------------------------
# Exact paths, so /gitea-something is left to the SPA.
redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301
redir /radio /radio/ 301
redir /dozzle /dozzle/ 301
redir /garage /garage/ 301
redir /gitea https://git.{$DOMAIN}/ 301
redir /notes /notes/ 301
redir /sb https://priv.{$DOMAIN}/sb/ 301
redir /py /py/ 301
redir /jobs https://priv.{$DOMAIN}/jobs/ 301
redir /usaco /usaco/ 301
redir /tracker /tracker/ 301
redir /receipt /receipt/ 301
# Old job tracker URLs; the userscript's old @updateURL finds its update here.
redir /cv/jobs https://priv.{$DOMAIN}/jobs/ 301
redir /cv/leads https://priv.{$DOMAIN}/jobs/leads 301
redir /job-capture.user.js https://priv.{$DOMAIN}/jobs/job-capture.user.js 301
# ---- Backend API ---------------------------------------------------------------
# Not rate limited: a limit would only drop reconnect storms.
handle {$BACKEND_ENDPOINT}/ws* {
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# 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* {
import limit login 5 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/uploads* {
import limit upload 30 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# One GraphQL query can be arbitrarily expensive.
handle {$BACKEND_ENDPOINT}/graphql* {
import limit graphql 10 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/* {
import limit api 30 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# ---- Admin-gated services ------------------------------------------------------
# Docker socket access is root on the host.
handle /dozzle/* {
import admin_gate
reverse_proxy dozzle:8080 {
import proxy
}
}
# garage-webui on stpcore, behind its Caddy, which wants X-Core-Token (header_up
# replaces any client-sent one). Holds Garage's admin token. 2 GB for video
# uploads. A `route` so garage_upstream is set only after the gate passes.
handle /garage/* {
route {
import admin_gate
request_body {
max_size 2GB
}
vars garage_upstream yes
reverse_proxy garage:3909 {
import proxy
header_up X-Core-Token {env.GARAGE_WEBUI_TOKEN}
transport http {
dial_timeout 3s
}
}
}
}
# Station-control UI guarded only by the icecast password.
handle /radio/admin/* {
import admin_gate
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
# The notes editor is on stppriv, behind its admin gate.
handle /sb/* {
redir https://priv.{$DOMAIN}{uri} 301
}
# ---- Public services -----------------------------------------------------------
handle /radio/* {
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
# Gitea is at git.DOMAIN; the registry at /v2/ is still proxied (prod.caddy).
handle_path /gitea/* {
redir https://git.{$DOMAIN}{uri} 301
}
# No prefix strip (SB_URL_PREFIX=/notes).
handle /notes/* {
reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} {
import proxy
}
}
# Minutes-long searches with one slot on the Python side, so the limit is
# really concurrency protection. flush_interval passes NDJSON lines straight on.
@hotels path_regexp ^/py/hotels/(search|scan)
handle @hotels {
import limit hotel_search 3 1m
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
flush_interval -1
}
}
handle /py/* {
import limit api 30 1s
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
}
}
# ---- Job tracker (/jobs/) ----
# On stppriv. A 301 turns a POST into a GET, so capture clients must call
# priv. directly.
handle /jobs/* {
redir https://priv.{$DOMAIN}{uri} 301
}
# ---- USACO (/usaco/) ----
# Not stripped, not gated: the app checks the session for admin edits. The
# Gitea webhook arrives here, signed with USACO_WEBHOOK_SECRET.
handle /usaco/* {
import limit api 30 1s
reverse_proxy usaco:8080 {
import proxy
}
}
# ---- Activity tracker (/tracker/) ----
# The collector API (bearer keys) and the userscript bypass the gate.
# Collectors must use www: the apex 301 turns POSTs into GETs.
handle /tracker/api/v1/* {
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/tracker.user.js {
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/* {
import admin_gate
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
# ---- Receipt printer (/receipt/) ----
# Runs on stppi (it is on the printer's LAN), reached over Tailscale.
# header_up replaces any client-sent X-Receipt-Token. A `route` so the
# receipt_upstream var is set only after the gate passes, so a backend outage
# is not reported as "printer offline". 17 MB: 16 MB uploads plus framing.
handle /receipt/* {
route {
import limit receipt 10 1s
request_body {
max_size 17MB
}
import permission_gate receipt
vars receipt_upstream yes
uri strip_prefix /receipt
reverse_proxy {$RECEIPT_WEB_UPSTREAM} {
import proxy
header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN}
# Fail fast when stppi is off.
transport http {
dial_timeout 3s
}
}
}
}
# ---- Uploads (/uploads/) ----
# Private chat attachments, always on disk. Must precede /uploads/*.
handle /uploads/private/* {
import admin_gate
import upload_headers
root * /srv
file_server
}
# Garage (on stpcore) first, disk second: a 404, 5xx or dial error falls back
# to the volume, so the bucket is the source of truth.
handle /uploads/* {
import upload_headers
vars uploads_fallback yes
uri strip_prefix /uploads
reverse_proxy garage:3902 {
import proxy
header_up Host uploads.web.garage
transport http {
dial_timeout 2s
}
@not_in_bucket status 404 5xx
handle_response @not_in_bucket {
import uploads_disk
}
}
}
-16
View File
@@ -1,16 +0,0 @@
# Dev (CADDY_SITE=dev): `/` goes to Vite, http and https both serve without
# redirects (listing the http:// addresses disables Caddy's), `tls internal`,
# and no security headers or asset caching.
http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} {
tls internal
import common
route {
import ../routes.caddy
handle {
reverse_proxy vue:5173
}
}
}
-129
View File
@@ -1,129 +0,0 @@
# Production. The apex serves only the registry and otherwise redirects, so
# www is the one origin cookies and CORS assume.
# DNS-01 because no ACME server can reach us behind the tunnel. Public
# resolvers because DOMAIN is a Docker alias for this container, which would
# fail the zone lookup ("expected 1 zone, got 0").
(prod_tls) {
tls {
dns cloudflare {env.CLOUDFLARE_DNS_API_TOKEN}
resolvers 1.1.1.1 1.0.0.1
}
}
# Explicit so http://apex is one hop to www, not two.
http://{$DOMAIN}, http://www.{$DOMAIN} {
import logging
header -Server
redir https://www.{$DOMAIN}{uri} 301
}
{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
# Docker clients expect /v2/ (and Gitea's token endpoint) at the apex root
# and don't all follow redirects on blob uploads. No body limit: layers
# are large and stream through.
handle /v2/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
redir https://www.{$DOMAIN}{uri} 301
}
}
www.{$DOMAIN} {
import prod_tls
import common
import security_headers
# ---- Static asset caching ----
# `file` so a 404 for a not-yet-deployed hash is never cached as immutable.
@hashed {
path /assets/*
file {
root /srv/www
}
}
header @hashed Cache-Control "public, max-age=31536000, immutable"
@fonts {
path /fonts/*
file {
root /srv/www
}
}
header @fonts Cache-Control "public, max-age=2592000"
@week {
path /img/* /sound/*
file {
root /srv/www
}
}
header @week Cache-Control "public, max-age=604800"
# A hot-linked web stamp; public and uncredentialed, so `*` is safe.
header /img/stamps/mine.gif Access-Control-Allow-Origin "*"
route {
import ../routes.caddy
# 404 rather than index.html, so a stale asset hash isn't served HTML.
@static path /assets/* /fonts/* /img/* /sound/*
handle @static {
root * /srv/www
file_server
}
# SPA fallback so deep links work on refresh.
handle {
root * /srv/www
try_files {path} {path}/ /index.html
file_server
}
}
}
# ---- Partner Radar (radar.DOMAIN) ----
# The adamf/cto stack's own Caddy. A subdomain because the app assumes it owns
# `/`. No gate (it has its own login) and no security_headers (it sends its
# own, and www's would block the app).
(radar_proxy) {
reverse_proxy {$RADAR_UPSTREAM} {
import proxy
# Fail fast when the stack is down.
transport http {
dial_timeout 3s
}
}
}
radar.{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
import limit radar 30 1s
request_body {
max_size 10MB
}
vars radar_upstream yes
handle /api/auth/login {
route {
import limit radar_login 5 1m
import radar_proxy
}
}
handle {
import radar_proxy
}
}
}

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