diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..97b6da0 --- /dev/null +++ b/.env.example @@ -0,0 +1,154 @@ +# ============================================================================= +# .env.example — template for the real ./.env, which is GITIGNORED. +# +# HOW ENV REACHES THE CONTAINERS — two separate mechanisms, both reading this +# same file, and it is worth knowing which is which: +# 1. ${VAR} interpolation in docker-compose.yml. Done by the compose CLI when +# it parses the file, before any container exists. This is how container +# names, published ports and the Hasura database URL are built. +# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment +# variables inside that container. nginx, backend, db, icecast2, quartz, +# certbot and gitea all do this. +# The `python` service deliberately does neither wholesale — it uses an +# explicit `environment:` allow-list of three variables, so it never sees the +# database password or any API key. +# +# HOW TO USE +# cp .env.example .env then fill in every value. +# Distribute to the Raspberry Pi with ./sync-secrets.sh (newer file wins in +# either direction — see that script's header before editing on both hosts). +# +# CAUTION: an unset variable does not fail loudly. envsubst renders it as an +# empty string, which for a password field means "no password". After editing, +# check `docker compose config` shows what you expect. +# +# NOTHING IN THIS FILE HAS A REAL VALUE. Values are blank or obviously +# placeholder on purpose; never commit a filled-in copy. +# ============================================================================= + +# --- Postgres ---------------------------------------------------------------- +# One instance, two databases: POSTGRES_DB for the Go backend, POSTGRES_GITEA_DB +# for Gitea. Only POSTGRES_DB is auto-created on first init; the Gitea one must +# be created by hand on a fresh volume. +# POSTGRES_HOST doubles as the db container's name. +POSTGRES_USER= +POSTGRES_PASSWORD= +POSTGRES_DB= +POSTGRES_PORT=5432 +POSTGRES_HOST=db + +# --- Gitea ------------------------------------------------------------------- +# GITEA_HOST is the container name AND the nginx upstream host. +# The three secrets below are passed as GITEA__section__KEY overrides so the +# committed app.ini.template can keep those fields blank. Generate each as a +# long random hex string. +GITEA_HOST=gitea +GITEA_PORT=3000 +GITEA_INTERNAL_TOKEN= +GITEA_LFS_JWT_SECRET= +GITEA_OAUTH2_JWT_SECRET= +POSTGRES_GITEA_DB=gitea + +# --- 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 (backend) -------------------------------------------------- +# IMAP_PASSWORD should be an app-specific password, not the account password. +EMAIL_BACKEND= +IMAP_HOST= +IMAP_PORT=993 +IMAP_EMAIL= +IMAP_PASSWORD= +EMAIL_SYNC_INTERVAL= +EMAIL_SYNC_ENABLED= + +# --- 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. +UPTIMEKUMA_HOST= +UPTIMEKUMA_PORT= +WALLABAG_HOST= +WALLABAG_PORT= + +# --- Quartz (notes site at /notes/) ------------------------------------------ +QUARTZ_HOST=quartz +QUARTZ_PORT=8080 + +# --- Go backend -------------------------------------------------------------- +# BACKEND_HOST is the container name and the nginx upstream. +# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then +# strips; the Vue app's GraphQL client assumes /api. +# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs +# everyone out. +BACKEND_PORT=8080 +BACKEND_HOST=backend +BACKEND_SECRET= +BACKEND_ENDPOINT=/api + +# --- Obsidian vault ---------------------------------------------------------- +# HOST path, interpolated straight into two bind mounts: read-write into the +# backend, read-only into quartz. Must be an absolute path that exists on the +# host or the stack will not start. +OBSIDIAN_DIR= + +# --- Spotify ----------------------------------------------------------------- +# The redirect URI must match EXACTLY what is registered in the Spotify +# developer dashboard. The dev override sets its own localhost value. +# The resulting refresh token is persisted to ./backend/token/ so it survives +# rebuilds. +SPOTIFY_CLIENT_ID= +SPOTIFY_CLIENT_SECRET= +SPOTIFY_REDIRECT_URI= +SPOTIFY_AUTH_STATE= + +# --- Icecast / liquidsoap radio ---------------------------------------------- +# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast +# with it, and a live-broadcasting client authenticates to the liquidsoap +# harbor port with it. Anyone holding it can take over the stream. +# LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host. +ICECAST_SOURCE_PASSWORD= +ICECAST_RELAY_PASSWORD= +ICECAST_ADMIN_USER= +ICECAST_ADMIN_PASSWORD= +ICECAST_HOST=icecast2 +ICECAST_PORT=8000 +ICECAST_MOUNT=/stream +LIQUIDSOAP_HARBOR_MOUNT=/live +LIQUIDSOAP_HARBOR_PORT=8001 + +# --- TLS / identity ---------------------------------------------------------- +# DOMAIN is the APEX domain with no scheme and no www; certbot requests both +# it and www.DOMAIN on one certificate, and nginx canonicalises to www. +# EMAIL is the Let's Encrypt account address for expiry notices. +DOMAIN= +EMAIL= + +# --- Third-party API keys (backend) ------------------------------------------ +CLAUDE_API_KEY= +STEAM_API_KEY= +STEAM_ID= + +# --- Hasura (admin-only DB console at /hasura/) ------------------------------ +# Additionally gated by an nginx auth_request against the backend's admin check, +# so the admin secret is not the only barrier. +HASURA_GRAPHQL_ADMIN_SECRET= +HASURA_HOST=hasura +HASURA_PORT=8080 + +# --- Development-only switch ------------------------------------------------- +# Leave EMPTY/false in production. docker-compose.dev.yml sets SEED_DB=true for +# local work; setting it on the Pi would inject test data into the live site. +SEED_DB= + +# --- Python FastAPI service (/py/) ------------------------------------------- +PYTHON_HOST=python +PYTHON_PORT=8000 + +# TfL Unified API key (500 req/min); used by the Python hotel finder +TFL_APP_KEY= diff --git a/CLAUDE.md b/CLAUDE.md index e3b7152..99fd992 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -75,7 +75,25 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi. ## 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. -- **Auth flow**: Login sets `access_token` (24h) and `refresh_token` (365h) as HTTP-only cookies. `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. +- **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. There is no token revocation — logout only clears cookies. +- **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`. - **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts. - **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API. -- **All GORM models use soft delete** (`gorm.DeletedAt` field). +- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows. + +## Further documentation + +Each area has its own README with the detail that doesn't belong here: + +- `backend/README.md` — request lifecycle, auth model, GraphQL-vs-REST split and why each REST endpoint isn't GraphQL, service rundown, gotchas. +- `vue/README.md` — app structure, routing, store/GraphQL data flow, the design-token styling system, and a live-vs-legacy map of the views. +- `python/README.md` — endpoints, the NDJSON streaming contract, the hotel pricing method, and the scraper's fragility points. +- `DEPLOYMENT.md` — service topology and ports, dev vs prod boot paths, TLS first-run and renewal, what persists, env vars, and an ops runbook. +- `.env.example` — every environment variable the stack reads, documented, with blank values. + +## Conventions + +- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them. +- **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating. +- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output. +- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead — e.g. `views/unused/CoverLetters.vue` is actually live on `/cv`. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 0000000..c37262f --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,397 @@ +# Deployment + +How this site is put together and how to operate it. Application code is +documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only +— compose, nginx, TLS, the runner, and the runbook. + +Everything runs on a single Raspberry Pi, as Docker containers on one bridge +network, behind one nginx. + +--- + +## 1. Service topology + +Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on +3000/2222, and the liquidsoap harbor port. Everything else is internal. + +``` + internet + | + :80 :443| :3000 / :2222 :8001 + v v v + +--------------+ +--------+ +-------------+ + | nginx | | gitea | | liquidsoap | + | (TLS, SPA, | | (git + | | harbor | + | reverse | | CI) | | (live DJ) | + | proxy) | +--------+ +------+------+ + +------+-------+ | | + | | | + --------------------------------------------- | (same container + | | | | | | | as icecast2) + v v v v v v | | +/api/ /radio/ /gitea/ /hasura/ /notes/ /py/ | | +backend icecast2 gitea hasura quartz python | | + | ^ | | | + | | | | | + | +------------------|--------------------|---------------+ + | | | + +----------+-----------------+--------------------+ + v + +------+ + | db | postgres:16 + +------+ (app database + gitea database) + + vue one-shot build container -> writes vue_dist volume -> nginx serves it + certbot no ports; shares ./certbot/conf and ./certbot/www with nginx + autoheal no network; watches the docker socket and restarts unhealthy containers +``` + +### Who listens where + +| Service | Container name | Internal port | Public route | Published to host | +|---|---|---|---|---| +| nginx | `nginx` | 80, 443 | — | **80, 443** | +| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no | +| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no | +| hasura | `${HASURA_HOST}` | `${HASURA_PORT}` | `/hasura/` (admin-gated) | no | +| quartz (notes) | `${QUARTZ_HOST}` | `${QUARTZ_PORT}` | `/notes/` (admin-gated) | no | +| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no | +| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** | +| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** | +| vue | `vue` | 5173 (dev only) | `/` (dev only) | no | +| certbot | `certbot` | — | — | no | +| autoheal | `autoheal` | — | — | no | + +Container names come from `.env`, and nginx builds its upstreams from the same +variables. **Renaming a `*_HOST` value renames the container and repoints nginx +in one step — never change one without the other.** + +### Things nginx does that are easy to miss + +- **Canonical host.** `http://` → `https://`, and apex → `www`. The SPA, the + cookies and the CORS rules all assume `www.`. +- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/notes`, `/py` are stripped + by a `rewrite ... break` before proxying; each upstream serves from `/`. +- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with + `resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a + backend down (502s until it appears) instead of refusing to start. +- **Admin gate.** `/hasura/` and `/notes/` are protected by an `auth_request` + subrequest to the backend's `/auth/validate-admin`; a failure redirects to the + SPA login. Neither service has any auth of its own at that path. +- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads` + volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so + user-supplied files cannot execute anything on our origin. +- **Rate limits** — see §6. + +--- + +## 2. Dev vs prod boot paths + +### Production + +``` +docker compose up --build +``` + +1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected). +2. `nginx` starts, runs `nginx/entrypoint.sh`, which: + - is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`; + - renders `nginx.conf.template` if the cert is there, else + `nginx_setup.conf.template`; + - polls up to 120s for `index.html` to appear in `vue_dist`, then starts + nginx either way. +3. `certbot` obtains or confirms the certificate, then loops renewing. +4. Everything else comes up in parallel; `depends_on` here is the plain list + form, which waits only for *start*, not readiness. + +On the Pi this is triggered automatically: `.gitea/workflows/deploy.yaml` runs on +every push to `main`, fetches over `ssh://git@localhost:2222`, hard-resets the +deploy checkout, and runs `docker compose up -d --build --remove-orphans`. + +### Development + +``` +docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build +``` + +The override layer changes five services and disables one: + +- **vue** — `npm run dev` instead of a one-shot build; `./vue` is bind-mounted + for hot reload, with anonymous-volume masks on `/app/node_modules` and + `/app/src/wasm` so the image's installed deps and compiled WASM are not hidden + by the bind mount. You need neither `node_modules` nor a Rust toolchain on the + host. +- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a + `CN=localhost` certificate (once, kept in `certbot/conf`) and render + `nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and + `:443` serve the whole site, no HSTS, no HTTP→HTTPS redirect. +- **backend** — `DEV_MODE`, GraphQL playground and introspection on, a localhost + Spotify redirect URI, and **`SEED_DB=true`**. +- **hasura** — console and dev mode on. +- **python** — `uvicorn --reload` with `python/app` bind-mounted. +- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt + cannot validate localhost anyway. + +Visit `http://localhost`. + +**`SEED_DB`** makes the Go backend populate the database with test posts, users +and messages at startup. It is set only in the dev override and must never be +set on the Pi — it would inject fake content into the live site. + +Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies +`/api`, `/gitea` and `/radio` to locally running services. + +--- + +## 3. TLS: first issuance and renewal + +### The chicken-and-egg + +The production nginx config references +`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that +file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port +80. On a brand-new host neither can go first. + +`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no +upstreams, nothing that can fail to load. It serves +`/.well-known/acme-challenge/` from `/var/www/certbot` and 404s everything else, +so a half-configured site is never partially exposed. + +**First run on a new domain:** + +1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx + config.` +2. certbot runs `certbot certonly --webroot` and writes the certificate into + `./certbot/conf` (bind-mounted into both containers — that sharing is what + makes the whole thing work). +3. **`docker compose restart nginx`.** This step is manual. Nothing watches the + cert directory. On restart the entrypoint re-checks, finds the cert, and + renders the production config. + +### Renewal + +`certbot/entrypoint.sh` loops `certbot renew` every 12 hours. Renewal is a no-op +until the cert is inside its 30-day window, so this is well within Let's Encrypt +rate limits — it just means the window is checked twice a day. Certs are valid 90 +days, so renewal lands around day 60. + +**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container +cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the +certificate at startup and holds it in memory, so **a renewed certificate is not +served until nginx is reloaded or restarted.** In practice pushes to `main` +recreate nginx often enough to hide this. If the site ever serves an expired +cert, `docker compose restart nginx` is the fix. See proposal 1 in §8. + +--- + +## 4. What persists across restarts + +**Named volumes** — survive `docker compose down` and rebuilds; destroyed only by +`docker compose down -v` or `docker volume rm`: + +| Volume | Holds | Losing it means | +|---|---|---| +| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata | +| `uploads` | User-uploaded files (backend writes, nginx serves) | All uploaded images | +| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy | + +**Bind mounts** — live in the repo checkout on the Pi, survive everything short +of deleting the directory: + +| Path | Holds | Notes | +|---|---|---| +| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. | +| `./certbot/www` | ACME challenge webroot | Transient by nature | +| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. | +| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data | +| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea | +| `./logs` | Backend logs | | +| `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git | +| `${OBSIDIAN_DIR}` | The Obsidian vault | Read-write to backend, **read-only** to quartz | + +**Ephemeral:** anything else inside a container. Notably the Vue build, the +rendered nginx/icecast/quartz configs, and the Gitea runner's downloaded binary +are all regenerated. + +--- + +## 5. Environment variables + +All configuration lives in **`./.env`** at the repo root, which is gitignored. +`.env.example` documents every variable with blank values — start from that. + +Two distinct mechanisms read it, and services use both: + +- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse + time. Builds container names, published ports, the Hasura database URL. +- **`env_file: ./.env`** — injects the whole file into the container. Used by + nginx, backend, db, icecast2, quartz, certbot. + +`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own +convention for overriding `app.ini` keys), and `python` receives an explicit +three-variable allow-list, so it never sees the database password or any API key. + +**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two +things between this checkout and `adamf@stppi.local:~/deploy/web_server`: +`.env`, and `icecast2/fallback_music/*.mp3`. The sync is **bidirectional and +resolved by modification time — newer wins, with no merge.** Editing `.env` on +both machines silently loses one side's edits. Run it before and after editing. + +An unset variable is not an error: `envsubst` renders it as an empty string, +which for a password field means *no password*. After editing `.env`, confirm +with `docker compose config`. + +--- + +## 6. Rate limits + +Defined once per config in the `http` block, applied per location. Keyed on +`$binary_remote_addr` — the client IP in packed form, so each entry is ~64 bytes +and a `10m` zone holds roughly 160k IPs. `10m` is a safe round number, not a +tuned value. + +`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one +request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead +of that drip, and `nodelay` (used everywhere here) serves those N immediately. +So the effective behaviour is *"N instant requests, then throttled to the drip +rate"*. Anything beyond the burst gets an immediate **503**. + +| Zone | Rate | Burst | Applied to | Why | +|---|---|---|---|---| +| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. | +| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. | +| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. | +| `upload` | 5/min | 3 | `/api/messages/upload` | Uploads can be 50MB and hit disk; bounds how fast one IP fills the volume. | +| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. | + +The WebSocket endpoint is deliberately unlimited: a socket is one long-lived +request, and a limit there would drop reconnect storms rather than abuse. + +These zones key on the direct client IP, which is correct because nginx is the +sole edge. **If a CDN or proxy is ever put in front, they must switch to a +trusted `X-Forwarded-For` or every visitor shares one bucket.** + +--- + +## 7. Runbook + +All commands run from the deploy checkout on the Pi +(`~/deploy/web_server`) unless stated. + +**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does +it. By hand: + +``` +git pull && docker compose up -d --build --remove-orphans +``` + +**Rebuild one service** (e.g. after changing only the backend): + +``` +docker compose up -d --build backend +``` + +Note: editing `certbot/entrypoint.sh` needs no rebuild (it is bind-mounted over +the stock image's entrypoint) — just `docker compose restart certbot`. Editing +an nginx **template** does need a rebuild, since templates are `COPY`'d into the +image. + +**Apply a new nginx config / pick up a renewed certificate:** + +``` +docker compose up -d --build nginx # template changed +docker compose restart nginx # certificate changed +``` + +**Renew certificates manually** (then restart nginx so it is actually served): + +``` +docker compose exec certbot certbot renew --webroot -w /var/www/certbot +docker compose restart nginx +``` + +Add `--dry-run` to test without burning rate limit. + +**Check logs:** + +``` +docker compose logs -f nginx # follow one service +docker compose logs --tail=200 backend +docker compose ps # note: `vue` Exited(0) is correct +docker compose logs certbot # issuance / renewal outcomes +``` + +**Reset the database** — destructive; wipes the app database **and Gitea's**: + +``` +docker compose down +docker volume rm web_server_dbdata # confirm the name with `docker volume ls` +docker compose up -d +``` + +The app schema is recreated by GORM auto-migration on backend start (there are no +migration files). **Gitea's database is not auto-created** — the Postgres image +only creates `POSTGRES_DB` on first init, so create `${POSTGRES_GITEA_DB}` +manually before Gitea will start: + +``` +docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB" +``` + +**Sync secrets / fallback music** (from the laptop checkout, not the Pi): + +``` +./sync-secrets.sh +``` + +**Set up the CI runner on a fresh Pi:** + +``` +cd gitea-runner +bash download.sh # pulls the arm64 binary +# mint a registration token: Gitea -> Site Administration -> Actions -> Runners +GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises +``` + +The runner lives **outside** Docker on purpose: it runs `docker compose up` +against this stack, so it cannot be a container in it. Registration is one-shot — +`.runner` is the lasting credential; re-registering needs that file deleted *and* +a fresh token. + +**Go live on the radio:** point a broadcasting client (e.g. butt) at the Pi on +`${LIQUIDSOAP_HARBOR_PORT}` with mount `${LIQUIDSOAP_HARBOR_MOUNT}` and the +icecast source password. liquidsoap pre-empts the fallback playlist immediately +(`track_sensitive=false`). Disconnect and it falls back to the playlist, then to +silence. Adding MP3s to `icecast2/fallback_music/` is picked up live +(`reload_mode="watch"`) with no restart. + +**Unhealthy containers** are restarted automatically by `autoheal`, which polls +the docker socket every 30s. Only `backend` and `python` define healthchecks, so +only they are covered. + +--- + +## 8. Known rough edges + +Documented, not fixed — each would change deploy behaviour. + +1. **Renewed certificates are not served until nginx restarts.** No + `--deploy-hook` in `certbot/entrypoint.sh`. Fix: add + `--deploy-hook "touch /var/www/certbot/.reloadme"` plus a watcher, or give + certbot the docker socket to send nginx a `HUP`. +2. **First TLS issuance needs a manual `docker compose restart nginx`.** The + entrypoint only re-evaluates cert presence at container start. +3. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be + mounted to the same in-container path as the real wrapper. It is currently + shadowed by an explicit file mount — fragile. Deleting it would be safe but + is a file removal. +4. **The dev nginx template duplicates its `:80` and `:443` server blocks** + almost verbatim (~190 lines), so a routing fix must be made twice. +5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing + only our own origin**, which defeats the point of having the header at all. +6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert + today (neither contains whitespace) but a latent quoting bug. +7. **`UPTIMEKUMA_*` and `WALLABAG_*` are substituted by nginx but no compose + service provides them** — leftovers from removed services. +8. **`autoheal` mounts the docker socket**, which is effectively root on the + host, and uses the `:latest` tag. diff --git a/backend/Dockerfile b/backend/Dockerfile index 6389717..44bda79 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,3 +1,32 @@ +# ============================================================================= +# 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 WORKDIR /backend diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..83ac309 --- /dev/null +++ b/backend/README.md @@ -0,0 +1,186 @@ +# Backend + +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 +by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea, Anthropic). + +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 +sees it. + +## Layout + +``` +main.go wiring: env -> services -> Store -> routes +models/models.go GORM entities, which are ALSO the GraphQL object types +handlers/ REST endpoints + the shared Store dependency container + store.go Store: DB, service handles, and the third-party caches + handle_*.go one file per domain +services/ stateful collaborators (DB, auth, chat hub, API clients) +graph/ GraphQL layer + schema/*.graphql source of truth for the schema + *.resolvers.go resolver implementations, one per schema file + *_helpers.go hand-written mapping helpers (never regenerated) + context.go reading identity out of the resolver context + middleware.go putting it in + doc.go package overview — read this before touching resolvers + generated.go GENERATED, do not edit + model/models_gen.go GENERATED, do not edit +``` + +## Request lifecycle + +1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and + proxies to this service. +2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so + that `ClientIP()` — which the login rate limiter keys on — cannot be + spoofed via `X-Forwarded-For`. +3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a + valid access token and stashes the claims in the Gin context; + `AdminMiddleware` then requires `admin: true` in those claims. A handler + reached through the `admin` group can assume both. +4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only + *annotates* the request context with the Gin context and, if a valid access + token is present, the JWT claims — and then lets everything through. Each + resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`. + **A resolver that forgets to check is public.** +5. Handlers and resolvers both reach the database and the caches through the + single `handlers.Store` built in `main`. + +## Auth + +- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets + two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`: + - `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary + requests authorise without a database hit; + - `refresh_token` (365 days) carries only `id`. +- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh + 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) + and will transparently refresh, so returning admins are recognised without a + visible re-login. +- Tokens are stateless. **Logout only clears the browser's cookies**; nothing + is revoked server-side, and a token that has already been issued stays valid + until it expires. The same is true of demoting an admin: it takes effect on + their next refresh, not immediately. + +The two implementations (REST in `handlers/handle_auth.go`, GraphQL in +`graph/auth.resolvers.go`) are parallel by design, since the front end uses +both. They share `services.Auth` and the rate limiter, but each has its own +cookie-writing helper — change one and you must change the other. + +## GraphQL vs REST + +GraphQL is the default and covers essentially all the site's data. REST exists +for the things GraphQL cannot do: + +| REST endpoint | why it is not GraphQL | +| --- | --- | +| `/auth/*` | cookie handling and the status-code-only admin probe | +| `/spotify/callback`, `/email/callback` | OAuth providers redirect a *browser* here | +| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads | +| `/notes/*path` | streams a file download, not JSON | +| `/ws` | WebSocket upgrade | +| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working | + +## Services + +Everything is constructed in `main` from environment variables and handed to +`handlers.Store`. Nothing here fails start-up: a missing Spotify token, an +unconfigured mailbox or an absent Steam key all just leave that feature +dormant, which is why callers nil-check `Store.SpotifyClient` and friends. + +- **database.go** — Postgres via GORM. There are no migration files: + `AutoMigrate` is the whole schema story, so it adds tables/columns but never + drops or renames, and a new model must be listed there to get a table. +- **auth.go** — HS256 JWT minting and verification. +- **ratelimit.go** — in-memory per-IP sliding window (5 logins/minute). + Process-local and never evicts keys. +- **websocket.go** — the chat hub. A package-level singleton: one connection + set, one mutex, one DB handle. Public, with admin connections additionally + able to see/send private messages and delete. +- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are + cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min + (Steam). +- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch + recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter + it, ask Claude to extract structured data, create or advance a + `JobApplication`. Runs on a timer and can be triggered by an admin. +- **claude.go** — the shared Anthropic client, used by the email pipeline and + by the rowing photo reader. +- **notes.go** — path-traversal-safe file lookup for the notes directory. +- **seed.go** — dev-only test data. Creates an admin with the password + `password`, so it must never run in production (`SEED_DB=true` is set only + in `docker-compose.dev.yml`). + +## Regenerating gqlgen + +The `.graphql` files are the source of truth. + +``` +cd backend && go run github.com/99designs/gqlgen generate +``` + +This rewrites `graph/generated.go` and `graph/model/models_gen.go` and adds +stubs for new fields to the matching `*.resolvers.go`. Existing resolver bodies +are preserved, but hand-written code in a regenerated file can be relocated to +the end of it — which is why shared helpers live in `*_helpers.go` instead. + +`gqlgen.yml` maps most GraphQL object types directly onto the GORM structs in +`models/`, so `graph/model/` holds only input and payload types. Adding a type +to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh +generated struct rather than the model you expected. + +## Gotchas + +- **Soft delete everywhere.** Every model except `ProcessedEmail` has a + `gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the + row out. Rows are never actually removed, and a `uniqueIndex` still collides + with deleted rows — a soft-deleted username cannot be reused. +- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it; + there is no error to tell you why the field came back null. +- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type + has a hand-written `ID` resolver doing `int(obj.ID)`. +- **`Message.AuthorID` is not a user id.** It is a per-process counter handed + out by the chat hub on connect, meaningless across restarts. +- **The chat table is capped.** Every insert soft-deletes all but the newest + 50 messages. +- **Store's caches are unsynchronised** and shared by all requests. The races + are benign (at worst a duplicate upstream fetch), but do not add a field + there that would be unsafe to tear. +- **Claude output is parsed as JSON** after stripping a possible markdown code + fence, in both `handle_rowing.go` and `email_sync.go`. +- **The email pipeline never retries.** A failed email is recorded with action + `"error"` so the next sync skips it. +- **Authenticating email after start-up does not start the scheduler**, which + only checks readiness once — restart, or trigger syncs by hand. +- **Introspection and the playground are off** unless `DEV_MODE=true` *and* + `GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set. +- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored; + the container is simply killed. + +## Environment + +| var | purpose | +| --- | --- | +| `POSTGRES_USER` / `_PASSWORD` / `_DB` / `_HOST` / `_PORT` | database connection | +| `BACKEND_PORT` | listen port | +| `BACKEND_SECRET` | JWT signing secret | +| `BACKEND_ENDPOINT` | this service's public base URL | +| `DOMAIN` | auth cookie domain and WebSocket origin allow-list | +| `DEV_MODE` | release vs debug Gin; gates the two GraphQL dev flags | +| `SEED_DB` | seed dev test data (never in production) | +| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras | +| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth | +| `CLAUDE_API_KEY` | Anthropic API | +| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed | +| `STEAM_API_KEY` / `STEAM_ID` | Steam presence | +| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) | +| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend | +| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend | + +Paths baked into the code, all inside mounted volumes so they survive a +container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`, +`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph +OAuth tokens). diff --git a/backend/graph/activity.resolvers.go b/backend/graph/activity.resolvers.go index f3e3c61..0a67a07 100644 --- a/backend/graph/activity.resolvers.go +++ b/backend/graph/activity.resolvers.go @@ -20,6 +20,7 @@ func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, e // CreateActivity is the resolver for the createActivity field. func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) { + // No middleware guards GraphQL, so each mutation checks for itself. if !IsAdminFromCtx(ctx) { return nil, fmt.Errorf("admin access required") } @@ -38,6 +39,9 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &activities[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.Activity, len(activities)) for i := range activities { result[i] = &activities[i] diff --git a/backend/graph/auth.resolvers.go b/backend/graph/auth.resolvers.go index 6ad9acb..a06377a 100644 --- a/backend/graph/auth.resolvers.go +++ b/backend/graph/auth.resolvers.go @@ -17,6 +17,12 @@ import ( // Login is the resolver for the login field. func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) { + // The Gin context is needed for two things GraphQL cannot express: the + // 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) if gc == nil { return nil, fmt.Errorf("could not get gin context") @@ -26,6 +32,8 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (* 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 if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil { return nil, fmt.Errorf("invalid credentials") @@ -40,24 +48,10 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (* return nil, fmt.Errorf("failed to generate tokens") } - gc.SetSameSite(http.SameSiteLaxMode) - gc.SetCookie( - "access_token", - tokens.AccessToken, - int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()), - "/", - r.Store.Auth.Config.Domain, - true, true, - ) - gc.SetCookie( - "refresh_token", - tokens.RefreshToken, - int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()), - "/", - r.Store.Auth.Config.Domain, - true, true, - ) + setAuthCookies(gc, r.Store.Auth.Config, tokens) + // 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 } @@ -68,6 +62,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) { return false, fmt.Errorf("could not get gin context") } + // Max-age -1 tells the browser to drop the cookies. Nothing is + // invalidated server-side, so a token captured beforehand still works + // until it expires. gc.SetSameSite(http.SameSiteLaxMode) gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true) gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true) @@ -97,6 +94,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload return nil, fmt.Errorf("invalid token claims") } + // Setting the primary key and calling First with no condition makes GORM + // look the row up by that key. Admin status is re-read from the database + // here, which is what lets a revoked admin flag take effect on refresh. var user models.User user.ID = uint(userIDF) if err := r.Store.DB.First(&user).Error; err != nil { @@ -108,23 +108,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload return nil, fmt.Errorf("failed to generate tokens") } - gc.SetSameSite(http.SameSiteLaxMode) - gc.SetCookie( - "access_token", - tokens.AccessToken, - int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()), - "/", - r.Store.Auth.Config.Domain, - true, true, - ) - gc.SetCookie( - "refresh_token", - tokens.RefreshToken, - int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()), - "/", - r.Store.Auth.Config.Domain, - true, true, - ) + setAuthCookies(gc, r.Store.Auth.Config, tokens) return &model.AuthPayload{User: &user}, nil } @@ -136,6 +120,8 @@ func (r *queryResolver) Me(ctx context.Context) (*models.User, error) { 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 user.ID = userID if err := r.Store.DB.First(&user).Error; err != nil { diff --git a/backend/graph/auth_helpers.go b/backend/graph/auth_helpers.go new file mode 100644 index 0000000..1b3d387 --- /dev/null +++ b/backend/graph/auth_helpers.go @@ -0,0 +1,43 @@ +package graph + +import ( + "net/http" + + "adam-french.co.uk/backend/services" + "github.com/gin-gonic/gin" +) + +// setAuthCookies writes the access/refresh cookie pair on a GraphQL response. +// +// This mirrors handlers.Store.setAuthCookies — the two cannot be shared +// because importing graph from handlers would be a cycle, so any change to +// cookie attributes has to be made in both places or login via REST and login +// via GraphQL will disagree. +// +// 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 max-age mirrors the +// lifetime baked into the token itself. +// +// It lives in its own file rather than in auth.resolvers.go because gqlgen may +// relocate hand-written code in the files it regenerates. +func setAuthCookies(gc *gin.Context, config *services.AuthConfig, tokens *services.Tokens) { + gc.SetSameSite(http.SameSiteLaxMode) + gc.SetCookie( + "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, + ) +} diff --git a/backend/graph/bookmark.resolvers.go b/backend/graph/bookmark.resolvers.go index dc1c117..17e9fc4 100644 --- a/backend/graph/bookmark.resolvers.go +++ b/backend/graph/bookmark.resolvers.go @@ -35,6 +35,9 @@ func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models. if !IsAdminFromCtx(ctx) { return nil, fmt.Errorf("admin access required") } + // 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 if err := r.Store.DB.First(&bookmark, id).Error; err != nil { return nil, err @@ -51,6 +54,9 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &bookmarks[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.Bookmark, len(bookmarks)) for i := range bookmarks { result[i] = &bookmarks[i] diff --git a/backend/graph/context.go b/backend/graph/context.go index 45c8a12..e67b823 100644 --- a/backend/graph/context.go +++ b/backend/graph/context.go @@ -7,6 +7,17 @@ import ( "github.com/golang-jwt/jwt/v5" ) +// This file is the bridge between Gin's request handling and gqlgen's +// 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. + +// 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 const ( @@ -14,6 +25,9 @@ const ( ginContextKey contextKey = "ginContext" ) +// UserClaimsFromCtx returns the verified JWT claims, or nil when the request +// is anonymous. nil means "not authenticated": a missing or invalid token is +// not an error here, because many queries are public. func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims { claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims) if !ok { @@ -22,6 +36,8 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims { 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. func UserIDFromCtx(ctx context.Context) (uint, bool) { claims := UserClaimsFromCtx(ctx) if claims == nil { @@ -34,6 +50,11 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) { return uint(idF), true } +// IsAdminFromCtx reports whether the request carries an admin token. This is +// the authorisation check for nearly every mutation — there is no middleware +// in front of the GraphQL endpoint, so a resolver that forgets to call this +// is public. 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 { claims := UserClaimsFromCtx(ctx) if claims == nil { @@ -43,6 +64,10 @@ func IsAdminFromCtx(ctx context.Context) bool { return ok && admin } +// 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 { gc, ok := ctx.Value(ginContextKey).(*gin.Context) if !ok { diff --git a/backend/graph/doc.go b/backend/graph/doc.go new file mode 100644 index 0000000..475f01e --- /dev/null +++ b/backend/graph/doc.go @@ -0,0 +1,32 @@ +// Package graph is the GraphQL layer: the single POST /graphql endpoint that +// serves most of the site's data. +// +// How the pieces fit: +// +// - graph/schema/*.graphql is the source of truth. Running +// `go run github.com/99designs/gqlgen generate` regenerates generated.go +// and model/models_gen.go, and adds stubs for any new field to the +// matching *.resolvers.go. Never edit those two generated files. +// - gqlgen.yml maps most GraphQL object types straight onto the GORM +// structs in backend/models, so model/ holds only input and payload +// types. That is also why almost every type has a hand-written ID +// resolver: model IDs are uint, GraphQL's Int is a Go int. +// - Resolvers reach the database and the third-party caches through +// Resolver.Store, the same handlers.Store the REST endpoints use. +// - context.go and middleware.go carry the caller's identity from Gin into +// the plain context.Context a resolver receives. +// +// Authorisation, which is the thing most likely to catch out a newcomer: +// there is NO middleware guarding this endpoint. AuthContextMiddleware only +// annotates the context and lets everything through, so each resolver checks +// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that +// check is fully public. The rule of thumb in this schema is that queries are +// public and mutations are admin-only, with these exceptions: the job +// application and job reference queries are admin-only (they are private +// data), the places mutations need only a signed-in user, and the messages +// query hides private messages from non-admins rather than refusing. +// +// 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 diff --git a/backend/graph/favorite.resolvers.go b/backend/graph/favorite.resolvers.go index 79e7010..16cefc6 100644 --- a/backend/graph/favorite.resolvers.go +++ b/backend/graph/favorite.resolvers.go @@ -38,6 +38,9 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &favorites[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.Favorite, len(favorites)) for i := range favorites { result[i] = &favorites[i] diff --git a/backend/graph/gitea.resolvers.go b/backend/graph/gitea.resolvers.go index 37a5b42..249ed5d 100644 --- a/backend/graph/gitea.resolvers.go +++ b/backend/graph/gitea.resolvers.go @@ -15,6 +15,8 @@ import ( // GiteaFeed is the resolver for the giteaFeed field. func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) { + // One-minute cache on the Store, shared by every visitor, so a busy home + // page does not hammer the Gitea container. if r.Store.GiteaFeedFresh() { return mapGiteaFeed(r.Store.GiteaFeed), nil } @@ -23,6 +25,10 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er if err != nil { return nil, err } + // 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 { return nil, nil } diff --git a/backend/graph/gitea_helpers.go b/backend/graph/gitea_helpers.go index 95fad87..58fa22d 100644 --- a/backend/graph/gitea_helpers.go +++ b/backend/graph/gitea_helpers.go @@ -5,6 +5,10 @@ import ( "adam-french.co.uk/backend/services" ) +// 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 { return &model.GiteaFeedItem{ AvatarURL: feed.ActUser.AvatarURL, diff --git a/backend/graph/job_app_reference.resolvers.go b/backend/graph/job_app_reference.resolvers.go index 3c951f6..0c77cf0 100644 --- a/backend/graph/job_app_reference.resolvers.go +++ b/backend/graph/job_app_reference.resolvers.go @@ -81,6 +81,8 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR return nil, fmt.Errorf("admin access required") } var refs []*models.JobAppReference + // created_at is the final tie-break so entries sharing a sort_order (the + // default 0) keep a stable, insertion-ordered sequence. if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil { return nil, err } diff --git a/backend/graph/job_application.resolvers.go b/backend/graph/job_application.resolvers.go index ecf7d13..6f83080 100644 --- a/backend/graph/job_application.resolvers.go +++ b/backend/graph/job_application.resolvers.go @@ -43,6 +43,10 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp if !IsAdminFromCtx(ctx) { return nil, fmt.Errorf("admin access required") } + // Partial update: every input field is a pointer so that "not supplied" + // is distinguishable from "set to empty". A nil field is left untouched; + // note this also means a nullable column can never be cleared back to + // null through this mutation. var app models.JobApplication if err := r.Store.DB.First(&app, id).Error; err != nil { return nil, err @@ -79,6 +83,8 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo if !IsAdminFromCtx(ctx) { return false, fmt.Errorf("admin access required") } + // Soft delete straight by id, without loading first — so deleting an id + // that does not exist still returns true. if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil { return false, err } @@ -87,9 +93,12 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo // JobApplications is the resolver for the jobApplications field. func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) { + // Admin-only even though it is a query: job applications are private. if !IsAdminFromCtx(ctx) { return nil, fmt.Errorf("admin access required") } + // Find can populate a slice of pointers directly, avoiding the + // copy-to-pointers loop the other list resolvers need. var apps []*models.JobApplication if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil { return nil, err diff --git a/backend/graph/message.resolvers.go b/backend/graph/message.resolvers.go index 26be7b9..5709cf7 100644 --- a/backend/graph/message.resolvers.go +++ b/backend/graph/message.resolvers.go @@ -17,12 +17,21 @@ func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, err } // AuthorID is the resolver for the authorId field. +// 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) { return int(obj.AuthorID), nil } // Messages is the resolver for the messages field. func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) { + // Non-admins get the public subset rather than an error, so the chat + // 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 query := r.Store.DB.Order("created_at DESC") if !IsAdminFromCtx(ctx) { @@ -31,6 +40,9 @@ func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) if err := query.Find(&messages).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &messages[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.Message, len(messages)) for i := range messages { result[i] = &messages[i] diff --git a/backend/graph/middleware.go b/backend/graph/middleware.go index 808f96c..e24d37a 100644 --- a/backend/graph/middleware.go +++ b/backend/graph/middleware.go @@ -7,6 +7,18 @@ import ( "github.com/gin-gonic/gin" ) +// AuthContextMiddleware prepares the request context for the GraphQL handler. +// +// 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 pushes every authorisation decision +// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify +// errors are swallowed for exactly that reason. +// +// 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) gin.HandlerFunc { return func(c *gin.Context) { ctx := context.WithValue(c.Request.Context(), ginContextKey, c) @@ -19,6 +31,8 @@ func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc { } } + // 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.Next() } diff --git a/backend/graph/place.resolvers.go b/backend/graph/place.resolvers.go index f539d36..df48fdd 100644 --- a/backend/graph/place.resolvers.go +++ b/backend/graph/place.resolvers.go @@ -15,6 +15,9 @@ import ( // CreatePlace is the resolver for the createPlace field. func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) { + // Any signed-in user, not just an admin — places are the one shared, + // collaboratively edited list on the site. There is no per-user + // ownership, so any signed-in user can edit or delete any place. if _, ok := UserIDFromCtx(ctx); !ok { return nil, fmt.Errorf("authentication required") } @@ -43,6 +46,8 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model. if _, ok := UserIDFromCtx(ctx); !ok { return nil, fmt.Errorf("authentication required") } + // Partial update, same pointer-means-supplied convention as job + // applications: nil fields are left as they are. var place models.Place if err := r.Store.DB.First(&place, id).Error; err != nil { return nil, err diff --git a/backend/graph/post.resolvers.go b/backend/graph/post.resolvers.go index fe2588f..fc4eac5 100644 --- a/backend/graph/post.resolvers.go +++ b/backend/graph/post.resolvers.go @@ -48,10 +48,14 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U return nil, fmt.Errorf("post not found") } + // Admin alone is not enough: a post may only be edited by its author, so + // one admin cannot rewrite another's posts. if post.AuthorID != userID { return nil, fmt.Errorf("you can only update your own posts") } + // Both fields are non-pointer in the input, so this is a full replace — + // omitting one in the mutation blanks it rather than leaving it alone. post.Title = input.Title post.Content = input.Content if err := r.Store.DB.Save(&post).Error; err != nil { @@ -81,6 +85,8 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post return nil, fmt.Errorf("you can only delete your own posts") } + // Soft delete; the error is dropped, so a failed delete still reports + // success to the client. r.Store.DB.Delete(&post) return &post, nil } @@ -92,10 +98,16 @@ func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) { // Posts is the resolver for the posts field. func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) { + // 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 if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &posts[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.Post, len(posts)) for i := range posts { result[i] = &posts[i] diff --git a/backend/graph/resolver.go b/backend/graph/resolver.go index 02bf9ba..36ea60b 100644 --- a/backend/graph/resolver.go +++ b/backend/graph/resolver.go @@ -7,6 +7,15 @@ import "adam-french.co.uk/backend/handlers" // It serves as dependency injection for your app, add any dependencies you require // here. +// 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 +// (queryResolver, mutationResolver, postResolver, ...), which is why those +// one-line `struct{ *Resolver }` declarations appear at the bottom of each +// resolvers file. type Resolver struct { Store *handlers.Store } diff --git a/backend/graph/rowing.resolvers.go b/backend/graph/rowing.resolvers.go index 83fc66b..5e0557e 100644 --- a/backend/graph/rowing.resolvers.go +++ b/backend/graph/rowing.resolvers.go @@ -17,6 +17,9 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &rows[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.Rowing, len(rows)) for i := range rows { result[i] = &rows[i] @@ -30,6 +33,8 @@ func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error } // 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) { return int(obj.Time), nil } diff --git a/backend/graph/schema/gitea.graphql b/backend/graph/schema/gitea.graphql index 71eb382..e06d3c9 100644 --- a/backend/graph/schema/gitea.graphql +++ b/backend/graph/schema/gitea.graphql @@ -1,3 +1,6 @@ +# Latest activity from the self-hosted Gitea instance, proxied and cached for +# one minute by the backend. Resolves to null when the feed is empty. + type GiteaFeedItem { avatarUrl: String! repoUrl: String! diff --git a/backend/graph/schema/job_application.graphql b/backend/graph/schema/job_application.graphql index 41aaff8..9f731cb 100644 --- a/backend/graph/schema/job_application.graphql +++ b/backend/graph/schema/job_application.graphql @@ -1,3 +1,11 @@ +# Job application tracker. Rows come from these mutations or automatically +# from the email sync pipeline (backend/services/email_sync.go). These are +# private data, so the queries here are admin-only as well as the mutations. +# +# status is a free-form String, but only the values ranked in +# services.statusOrder can be advanced automatically by the email pipeline: +# applied, screening, assessment, interviewing, offer, rejected, withdrawn. + type JobApplication { id: ID! createdAt: Time! diff --git a/backend/graph/schema/message.graphql b/backend/graph/schema/message.graphql index e7fdc03..f710897 100644 --- a/backend/graph/schema/message.graphql +++ b/backend/graph/schema/message.graphql @@ -1,3 +1,10 @@ +# Chat history. The live chat runs over the WebSocket at /ws, not GraphQL; +# this query is the initial page load. +# +# Two gotchas: authorId is a per-connection counter from the chat hub, not a +# User id, and private messages are silently filtered out for non-admins +# rather than causing an error. + type Message { id: ID! content: String! diff --git a/backend/graph/schema/place.graphql b/backend/graph/schema/place.graphql index 2f5a2dd..71a68ad 100644 --- a/backend/graph/schema/place.graphql +++ b/backend/graph/schema/place.graphql @@ -1,3 +1,6 @@ +# Places to go. Unlike most mutations these require only a signed-in user, +# not an admin, and there is no per-user ownership: the list is shared. + type Place { id: ID! createdAt: Time! diff --git a/backend/graph/schema/schema.graphql b/backend/graph/schema/schema.graphql index bd56abb..395a840 100644 --- a/backend/graph/schema/schema.graphql +++ b/backend/graph/schema/schema.graphql @@ -1,3 +1,19 @@ +# Root of the GraphQL schema. +# +# 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 type Query diff --git a/backend/graph/schema/spotify.graphql b/backend/graph/schema/spotify.graphql index e101fce..7289da0 100644 --- a/backend/graph/schema/spotify.graphql +++ b/backend/graph/schema/spotify.graphql @@ -1,3 +1,7 @@ +# Spotify "now playing" / "recently played" for the home page. Both resolve to +# null / an empty list when the backend has never completed the Spotify OAuth +# flow, so the page degrades rather than erroring. + type SpotifyArtist { name: String! } diff --git a/backend/graph/schema/steam.graphql b/backend/graph/schema/steam.graphql index 9198266..4b7d940 100644 --- a/backend/graph/schema/steam.graphql +++ b/backend/graph/schema/steam.graphql @@ -1,3 +1,6 @@ +# Steam presence and recent games for the home page, cached for five minutes. +# headerImage is built from the app id rather than returned by Steam's API. + type SteamGame { appId: Int! name: String! diff --git a/backend/graph/spotify.resolvers.go b/backend/graph/spotify.resolvers.go index 29cad95..3107700 100644 --- a/backend/graph/spotify.resolvers.go +++ b/backend/graph/spotify.resolvers.go @@ -15,6 +15,8 @@ import ( // SpotifyListening is the resolver for the spotifyListening field. func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) { + // A nil client means the OAuth flow has never been completed. Report that + // as null rather than an error so the home page renders without it. if r.Store.SpotifyClient == nil { return nil, nil } @@ -38,6 +40,8 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece return []*model.SpotifyRecentItem{}, nil } + // One-minute cache. This resolver is the only writer of that cache; the + // REST /spotify/recent endpoint reads it but never fills it. if r.Store.RecentSongsFresh() { return mapRecentItems(*r.Store.RecentSongs), nil } diff --git a/backend/graph/spotify_helpers.go b/backend/graph/spotify_helpers.go index 3841f79..566ce44 100644 --- a/backend/graph/spotify_helpers.go +++ b/backend/graph/spotify_helpers.go @@ -5,6 +5,11 @@ import ( "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. func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage { result := make([]*model.SpotifyImage, len(images)) for i, img := range images { @@ -13,6 +18,7 @@ func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage { return result } +// mapSpotifyTrack converts a currently-playing track. func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack { artists := make([]*model.SpotifyArtist, len(track.Artists)) for i, a := range track.Artists { @@ -28,6 +34,11 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack { } } +// mapRecentItems converts recently played history entries. +// +// 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 { result := make([]*model.SpotifyRecentItem, len(items)) for i, item := range items { diff --git a/backend/graph/steam.resolvers.go b/backend/graph/steam.resolvers.go index 8e45152..531931e 100644 --- a/backend/graph/steam.resolvers.go +++ b/backend/graph/steam.resolvers.go @@ -19,6 +19,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er return nil, nil } + // Five-minute cache across both Steam calls, which are made together and + // expire together. if r.Store.SteamFresh() { return &model.SteamStatus{ Online: r.Store.SteamOnline, @@ -36,6 +38,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er return nil, err } + // PersonaState 0 is offline; every higher value is some flavour of + // online. A nil summary (private profile) reads as offline. online := false if summary != nil { online = summary.PersonaState > 0 diff --git a/backend/graph/steam_helpers.go b/backend/graph/steam_helpers.go index 33ac21f..8a9b927 100644 --- a/backend/graph/steam_helpers.go +++ b/backend/graph/steam_helpers.go @@ -7,6 +7,11 @@ import ( "adam-french.co.uk/backend/services" ) +// mapSteamGames converts Steam API games into the GraphQL shape. +// +// 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 { result := make([]*model.SteamGame, len(games)) for i, g := range games { diff --git a/backend/graph/user.resolvers.go b/backend/graph/user.resolvers.go index 61eff4b..12f4a0b 100644 --- a/backend/graph/user.resolvers.go +++ b/backend/graph/user.resolvers.go @@ -20,6 +20,8 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse return nil, fmt.Errorf("admin access required") } + // Only an existing admin can create accounts — there is no public + // sign-up. New users are created non-admin; setUserAdmin promotes them. hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) if err != nil { return nil, err @@ -62,6 +64,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) return nil, fmt.Errorf("unauthorized") } + // Guards against the last admin demoting themselves and locking everyone + // out of the admin UI. if uint(id) == callerID { return nil, fmt.Errorf("cannot change your own admin status") } @@ -88,6 +92,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) { if err := r.Store.DB.Find(&users).Error; err != nil { return nil, err } + // Copy to a slice of pointers because the schema returns a list of + // nullable objects. Taking &users[i] is safe: the slice is never + // appended to after this point, so the backing array cannot move. result := make([]*models.User, len(users)) for i := range users { result[i] = &users[i] diff --git a/backend/handlers/handle_auth.go b/backend/handlers/handle_auth.go index bfe77ab..fd894d1 100644 --- a/backend/handlers/handle_auth.go +++ b/backend/handlers/handle_auth.go @@ -5,16 +5,38 @@ import ( "net/http" "adam-french.co.uk/backend/models" + "adam-french.co.uk/backend/services" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" "golang.org/x/crypto/bcrypt" ) +// This file holds the REST authentication endpoints and the Gin middleware +// 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 { Username string `json:"username" binding:"required"` Password string `json:"password" binding:"required"` } +// AuthMiddlewear requires a valid access token on a REST route and stashes +// the claims for AdminMiddleware to read. +// +// (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. func (store *Store) AuthMiddlewear(ctx *gin.Context) { access_token, err := ctx.Cookie("access_token") if err != nil { @@ -28,11 +50,20 @@ func (store *Store) AuthMiddlewear(ctx *gin.Context) { return } - // store claims in Gin context + // 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.Next() } +// AdminMiddleware requires the access token to carry admin=true. It must be +// 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) { claims, exists := ctx.Get("userClaims") if !exists { @@ -46,6 +77,8 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) { return } + // 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) if !ok || !admin { ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"}) @@ -55,6 +88,13 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) { ctx.Next() } +// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to +// decide whether to show admin UI. 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) { accessToken, err := ctx.Cookie("access_token") if err != nil { @@ -83,6 +123,16 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) { ctx.Status(http.StatusOK) } +// tryRefreshAndValidateAdmin re-authenticates from the refresh token. +// +// The bool does not mean "is an admin" — it means "this function already +// wrote the response". It returns true both for a successful admin refresh +// (200, new cookies set) and for a valid non-admin (403), 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. +// +// Admin status is re-read from the database here, which is what makes the +// refresh path pick up a revoked admin flag. func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool { refreshToken, err := ctx.Cookie("refresh_token") if err != nil { @@ -99,6 +149,9 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool { return false } + // Pre-setting ID and calling First with no explicit condition makes GORM + // use the primary key already in the struct as the lookup. Soft-deleted + // users are excluded automatically, so a deleted admin fails here. user := models.User{ID: uint(userIDF)} if err := store.DB.First(&user).Error; err != nil { return false @@ -114,6 +167,21 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool { return false } + store.setAuthCookies(ctx, tokens) + + ctx.Status(http.StatusOK) + return true +} + +// setAuthCookies writes the access/refresh cookie pair. +// +// The two trailing booleans of gin's SetCookie are Secure and HttpOnly, both +// true here: the cookies are never sent over plain HTTP and are invisible to +// JavaScript. SameSite=Lax lets them survive 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 (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) { ctx.SetSameSite(http.SameSiteLaxMode) ctx.SetCookie( "access_token", @@ -131,11 +199,12 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool { store.Auth.Config.Domain, true, true, ) - - ctx.Status(http.StatusOK) - return true } +// CheckToken backs GET /auth/check: it returns the current user for a valid +// 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) { access_token, err := ctx.Cookie("access_token") if err != nil { @@ -149,6 +218,8 @@ func (store *Store) CheckToken(ctx *gin.Context) { return } + // JWT claims come back through encoding/json, so every number is a + // float64 regardless of the Go type it was signed from. userIDF, ok := (*claims)["id"].(float64) if !ok { ctx.JSON(401, gin.H{"error": "unauthorized"}) @@ -168,6 +239,11 @@ func (store *Store) CheckToken(ctx *gin.Context) { ctx.JSON(http.StatusOK, user) } +// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token +// for a new cookie pair and returns the user. +// +// Tokens are not rotated in any revocable sense — the old refresh token stays +// valid until it expires, because nothing is tracked server-side. func (store *Store) RefreshToken(ctx *gin.Context) { refreshToken, err := ctx.Cookie("refresh_token") if err != nil { @@ -204,28 +280,18 @@ func (store *Store) RefreshToken(ctx *gin.Context) { return } - ctx.SetSameSite(http.SameSiteLaxMode) - ctx.SetCookie( - "access_token", - tokens.AccessToken, - int(store.Auth.Config.AccessTokenLifetime.Seconds()), - "/", - store.Auth.Config.Domain, - true, true, - ) - ctx.SetCookie( - "refresh_token", - tokens.RefreshToken, - int(store.Auth.Config.RefreshTokenLifetime.Seconds()), - "/", - store.Auth.Config.Domain, - true, true, - ) + store.setAuthCookies(ctx, tokens) 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) { + // Per-IP limit (5/min) on top of nginx's own login rate limit. + // ctx.ClientIP is only trustworthy because main.go pins the trusted + // proxy range, so the X-Forwarded-For header cannot be spoofed by a + // client talking through nginx. if !store.LoginLimiter.Allow(ctx.ClientIP()) { ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"}) return @@ -237,6 +303,9 @@ func (store *Store) Login(ctx *gin.Context) { return } + // 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{} if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil { ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"}) @@ -255,33 +324,23 @@ func (store *Store) Login(ctx *gin.Context) { return } - ctx.SetSameSite(http.SameSiteLaxMode) - ctx.SetCookie( - "access_token", - tokens.AccessToken, - int(store.Auth.Config.AccessTokenLifetime.Seconds()), - "/", - store.Auth.Config.Domain, - true, true, - ) - ctx.SetCookie( - "refresh_token", - tokens.RefreshToken, - int(store.Auth.Config.RefreshTokenLifetime.Seconds()), - "/", - store.Auth.Config.Domain, - true, true, - ) + store.setAuthCookies(ctx, tokens) ctx.JSON(http.StatusAccepted, user) } +// Logout backs POST /auth/logout. It only clears the browser's cookies — +// the tokens themselves stay cryptographically valid until they expire, so a +// copy taken beforehand would still work. func (store *Store) Logout(ctx *gin.Context) { store.removeCookies(ctx) ctx.Status(http.StatusOK) } +// removeCookies expires both auth cookies. The max-age of -1 is what tells +// 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 (store *Store) removeCookies(ctx *gin.Context) { ctx.SetSameSite(http.SameSiteLaxMode) ctx.SetCookie( diff --git a/backend/handlers/handle_email_sync.go b/backend/handlers/handle_email_sync.go index 3842638..34c806e 100644 --- a/backend/handlers/handle_email_sync.go +++ b/backend/handlers/handle_email_sync.go @@ -7,7 +7,16 @@ import ( "github.com/gin-gonic/gin" ) +// REST endpoints for the job-application email pipeline: a manual +// admin-triggered sync, and the OAuth redirect target (which has to be REST +// because Microsoft redirects a browser to it). + +// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync +// synchronously, so the response reflects the result. If the scheduler is +// mid-sync the service refuses via TryLock and this returns 500. func (store *Store) TriggerEmailSync(ctx *gin.Context) { + // A nil HTTPClient is the service's readiness flag — see + // services.EmailSyncService. if store.EmailSync == nil || store.EmailSync.HTTPClient == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"}) return @@ -23,6 +32,13 @@ func (store *Store) TriggerEmailSync(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"}) } +// CompleteEmailAuth handles Microsoft's OAuth redirect to +// GET /email/callback and stores the resulting token. +// +// The route is unauthenticated (Microsoft's redirect carries no site cookie), +// which is safe only because the code is worthless without the app's client +// secret. Note that completing auth here does not start the scheduler, which +// only checks readiness at start-up — a restart is needed for that. func (store *Store) CompleteEmailAuth(ctx *gin.Context) { if store.EmailSync == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"}) diff --git a/backend/handlers/handle_message_upload.go b/backend/handlers/handle_message_upload.go index 85b117a..e299278 100644 --- a/backend/handlers/handle_message_upload.go +++ b/backend/handlers/handle_message_upload.go @@ -12,18 +12,33 @@ import ( "github.com/gin-gonic/gin" ) +// Attachment upload for the chat. Files land in a directory that nginx serves +// directly at /uploads/, so anything written here is publicly reachable by +// URL — which is why the extension and content checks below matter. + +// allowedExtensions is the upload allow-list, keyed by lower-cased extension. var allowedExtensions = map[string]bool{ ".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true, ".mp4": true, ".webm": true, ".mp3": true, ".ogg": true, ".pdf": true, ".txt": true, } +// extensionToMIMEPrefix cross-checks the sniffed content type against the +// claimed extension, to stop e.g. HTML being served from a .png URL. +// +// The audio extensions (.mp3, .ogg) and .gif are deliberately absent: +// http.DetectContentType's answers for them are unreliable enough to reject +// legitimate files, so a missing entry means "extension allowed, content not +// verified". var extensionToMIMEPrefix = map[string]string{ ".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/", ".mp4": "video/", ".webm": "video/", ".pdf": "application/pdf", ".txt": "text/", } +// UploadMessageFile backs POST /messages/upload (login required) and returns +// the public URL of the stored file, which the client then sends over the +// WebSocket as a message's fileUrl. func (store *Store) UploadMessageFile(ctx *gin.Context) { file, err := ctx.FormFile("file") if err != nil { @@ -49,6 +64,10 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"}) return } + // 512 bytes is exactly what http.DetectContentType inspects; reading more + // would be wasted. A single Read may return fewer bytes than asked for, + // which is fine — sniffing works on a short prefix — so only a read that + // produced nothing at all is an error. buf := make([]byte, 512) n, err := f.Read(buf) f.Close() @@ -64,6 +83,10 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) { return } + // The uploaded name is discarded entirely in favour of 16 random bytes + // from crypto/rand. That kills path traversal and collisions in one go, + // and makes the resulting URL unguessable. Only the extension is carried + // over, and it has already been checked against the allow-list. b := make([]byte, 16) if _, err := rand.Read(b); err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"}) @@ -74,6 +97,9 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) { uploadDir := "/backend/uploads/" dest := filepath.Join(uploadDir, filename) + // Reopened rather than rewound: the earlier handle was closed after + // sniffing, and multipart files may be backed by either memory or a temp + // file, so a fresh reader is the simplest correct option. src, err := file.Open() if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"}) diff --git a/backend/handlers/handle_notes.go b/backend/handlers/handle_notes.go index e80fc52..1288150 100644 --- a/backend/handlers/handle_notes.go +++ b/backend/handlers/handle_notes.go @@ -7,9 +7,16 @@ import ( "github.com/gin-gonic/gin" ) +// 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) { path := ctx.Param("path") + // A traversal attempt is reported as 404, not 403, so probing cannot + // distinguish a blocked path from a missing one. path, err := store.Notes.ParsePath(path) if err != nil { ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) @@ -22,6 +29,9 @@ func (store *Store) GetNoteFile(ctx *gin.Context) { return } + // 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("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified") diff --git a/backend/handlers/handle_radio.go b/backend/handlers/handle_radio.go index c7b860a..5913361 100644 --- a/backend/handlers/handle_radio.go +++ b/backend/handlers/handle_radio.go @@ -9,12 +9,27 @@ import ( "github.com/gin-gonic/gin" ) +// Admin management of the radio's fallback music. These handlers only move +// 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" +// 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{ ".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true, } +// UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat +// 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) { file, err := ctx.FormFile("file") if err != nil { @@ -34,16 +49,22 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) { return } + // 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) dest := filepath.Join(fallbackMusicDir, filename) - // Verify the resolved path stays within the music directory + // 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) if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) { ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"}) return } + // 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 { ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"}) return @@ -57,7 +78,11 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) { 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) { + // Declared inside the function because it is purely the JSON shape of + // this one response. type songInfo struct { Name string `json:"name"` Size int64 `json:"size"` @@ -65,6 +90,7 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) { Disabled bool `json:"disabled"` } + // Initialised empty rather than nil so the response is [] and not null. songs := []songInfo{} // Read enabled songs @@ -73,6 +99,8 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"}) return } + // Skipping directories is also what keeps the "disabled" subdirectory out + // of the enabled list; dotfiles skip editor and OS cruft. for _, entry := range entries { if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") { continue @@ -89,7 +117,9 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) { }) } - // Read disabled songs + // 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") disabledEntries, err := os.ReadDir(disabledDir) if err == nil { @@ -113,7 +143,12 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) { 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) { + // 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")) if filename == "." || filename == "/" { ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"}) @@ -141,6 +176,7 @@ func (store *Store) DisableRadioSong(ctx *gin.Context) { 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) { filename := filepath.Base(ctx.Param("filename")) if filename == "." || filename == "/" { @@ -163,6 +199,9 @@ func (store *Store) EnableRadioSong(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"enabled": filename}) } +// 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) { filename := filepath.Base(ctx.Param("filename")) if filename == "." || filename == "/" { diff --git a/backend/handlers/handle_rowing.go b/backend/handlers/handle_rowing.go index 1091572..25f7230 100644 --- a/backend/handlers/handle_rowing.go +++ b/backend/handlers/handle_rowing.go @@ -16,14 +16,25 @@ import ( "github.com/gin-gonic/gin" ) +// Rowing log. The interesting endpoint is CreateRowing: rather than a form, +// 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. + +// ExtractedRowingData is the JSON contract for what Claude reads off the +// display; the keys must match the prompt in CreateRowing. type ExtractedRowingData struct { TimeMinutes uint64 `json:"timeMinutes"` TimeSeconds uint64 `json:"timeSeconds"` Distance uint64 `json:"distance"` } +// GetRowing backs the public GET /rowing with every logged session, newest +// first. func (store *Store) GetRowing(ctx *gin.Context) { var rowing []models.Rowing + // "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) ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"}) @@ -32,6 +43,12 @@ func (store *Store) GetRowing(ctx *gin.Context) { ctx.JSON(http.StatusOK, rowing) } +// CreateRowing backs the admin-only POST /rowing: it takes a photo of the +// rowing machine display, dates it from EXIF, has Claude read the time and +// distance, sanity-checks the result and stores a session. +// +// Note it is admin-gated and calls a paid API once per request, so the +// validation below exists to catch misreadings rather than hostile input. func (store *Store) CreateRowing(ctx *gin.Context) { file, err := ctx.FormFile("image") if err != nil { @@ -46,20 +63,23 @@ func (store *Store) CreateRowing(ctx *gin.Context) { } defer f.Close() - // Get the date taken from the EXIF data - x, err := exif.Decode(f) + // 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) if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"}) return } - dateTaken, err := x.DateTime() + dateTaken, err := exifData.DateTime() if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "no date found in EXIF data"}) return } - // Seek back to start since exif.Decode advanced the cursor + // exif.Decode consumed part of the stream, so rewind before reading the + // bytes to send to Claude. if _, err := f.Seek(0, io.SeekStart); err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"}) return @@ -77,6 +97,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) { "image/gif": true, "image/webp": true, } + // This is the browser's claimed type, not a sniffed one; it is passed + // 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. mediaType := file.Header.Get("Content-Type") if !allowedMediaTypes[mediaType] { ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"}) @@ -84,7 +107,11 @@ func (store *Store) CreateRowing(ctx *gin.Context) { } encoded := base64.StdEncoding.EncodeToString(data) - // Reject duplicates: same EXIF datetime already recorded + // Duplicate guard: two photos of the same session share an EXIF capture + // time to the second. Checked before the Claude call so a re-upload costs + // nothing. Note this reads err == nil as "found" — an actual database + // error is indistinguishable from "no match" here and lets the insert + // proceed. var existing models.Rowing if err := store.DB.Where("date = ?", dateTaken).First(&existing).Error; err == nil { ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"}) @@ -130,6 +157,8 @@ No text, no markdown, no explanation. Just the JSON object.`), return } + // Strip a markdown code fence if the model wrapped its JSON in one + // despite the prompt. Same defensive dance as in services/email_sync.go. extractedData := ExtractedRowingData{} raw := message.Content[0].Text @@ -153,7 +182,10 @@ No text, no markdown, no explanation. Just the JSON object.`), totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds - // Validate for anomalous values + // Sanity bounds on what Claude claims to have read. A misread digit + // 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 ( minDistance = 100 // metres maxDistance = 100000 // metres @@ -177,6 +209,9 @@ No text, no markdown, no explanation. Just the JSON object.`), return } + // Rough calorie estimate from distance alone: roughly 500 kcal per + // 7500 m. Not from the machine and not physiologically derived — it is a + // display figure only. calories := float64(extractedData.Distance) / 7500.0 * 500.0 rowing := models.Rowing{ diff --git a/backend/handlers/handle_spotify.go b/backend/handlers/handle_spotify.go index e36987e..d0ff7e4 100644 --- a/backend/handlers/handle_spotify.go +++ b/backend/handlers/handle_spotify.go @@ -11,11 +11,23 @@ import ( "github.com/zmb3/spotify/v2" ) +// These REST endpoints predate the equivalent GraphQL queries in +// 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 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) { state := ctx.Query("state") + // context.Background, not the request context: the client built below + // outlives this request and would otherwise be cancelled when it ends. c := context.Background() - // code := c.Query("code") + // 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) if err != nil { log.Println(err) @@ -38,6 +50,9 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) { }) } +// 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) { c := ctx.Request.Context() @@ -56,6 +71,12 @@ func (store *Store) ListeningTo(ctx *gin.Context) { ctx.JSON(200, playing) } +// RecentlyPlayed backs GET /spotify/recent. +// +// It reads the cache but never writes it: only the GraphQL spotifyRecent +// resolver populates Store.RecentSongs. So this endpoint serves cached data +// only when a GraphQL query happened to fill the cache in the last minute, +// and otherwise calls Spotify every time. func (store *Store) RecentlyPlayed(ctx *gin.Context) { if store.SpotifyClient == nil { ctx.JSON(500, gin.H{"error": "Spotify not authenticated"}) @@ -79,6 +100,9 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) { ctx.JSON(200, played) } +// RecentSongsFresh reports whether the cached recently-played list is within +// its one-minute TTL. An empty list counts as stale, so an empty listening +// history is re-fetched every time. func (s *Store) RecentSongsFresh() bool { if s.RecentSongs == nil { return false diff --git a/backend/handlers/handle_websocket.go b/backend/handlers/handle_websocket.go index 23499e0..ed88522 100644 --- a/backend/handlers/handle_websocket.go +++ b/backend/handlers/handle_websocket.go @@ -6,6 +6,9 @@ import ( "github.com/gin-gonic/gin" ) +// ConnectWebSocket upgrades GET /ws into a chat connection. The route is +// public: anyone may chat, and admin status only adds the ability to see and +// send private messages and to delete. func (store *Store) ConnectWebSocket(ctx *gin.Context) { // Work out admin status before upgrading: the browser sends the auth // cookies with the upgrade request, but they are not available afterwards. diff --git a/backend/handlers/store.go b/backend/handlers/store.go index ffa3c63..473e9df 100644 --- a/backend/handlers/store.go +++ b/backend/handlers/store.go @@ -10,6 +10,18 @@ import ( "gorm.io/gorm" ) +// Package handlers holds the REST endpoints and the shared Store that every +// 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 cache fields below are read and written by concurrent +// requests without a mutex. The races are benign in practice (worst case two +// requests refresh the same third-party API at once, or one reads a value +// being replaced), but this is a deliberate simplification, not an oversight +// — do not add a field here that would be unsafe to tear. type Store struct { DB *gorm.DB SpotifyAuth *spotifyauth.Authenticator @@ -20,14 +32,19 @@ type Store struct { LoginLimiter *services.RateLimiter EmailSync *services.EmailSyncService + // 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". RecentSongs *[]spotify.RecentlyPlayedItem RecentSongsFetchedAt time.Time + // Cached latest Gitea activity entry, 1 minute TTL. GiteaHost string GiteaPort string GiteaFeed *services.GiteaFeedResponse GiteaFeedFetchedAt time.Time + // Cached Steam status and recent games, 5 minute TTL. SteamAPIKey string SteamID string SteamRecentGames []services.SteamRecentGame @@ -35,6 +52,9 @@ type Store struct { SteamFetchedAt time.Time } +// GiteaFeedFresh reports whether the cached Gitea feed entry is still within +// its one-minute TTL. A nil cache is never fresh, so the first request always +// hits Gitea. func (s *Store) GiteaFeedFresh() bool { if s.GiteaFeed == nil { return false @@ -42,6 +62,10 @@ func (s *Store) GiteaFeedFresh() bool { return time.Since(s.GiteaFeedFetchedAt) < time.Minute } +// SteamFresh reports whether the cached Steam data is still within its +// five-minute TTL. Note it tests only SteamRecentGames: if Steam legitimately +// returns no recent games, the cache never registers as fresh and every +// request re-queries the API. func (s *Store) SteamFresh() bool { if s.SteamRecentGames == nil { return false diff --git a/backend/main.go b/backend/main.go index 97904ea..a01b6a9 100644 --- a/backend/main.go +++ b/backend/main.go @@ -21,7 +21,17 @@ import ( "adam-french.co.uk/backend/services" ) +// Command backend is the Go API for adam-french.co.uk. +// +// 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 does its own per-resolver authorisation +// instead of using middleware. See backend/README.md for the wider picture. 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" logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { @@ -35,6 +45,10 @@ func main() { r := gin.Default() + // Only the Docker network nginx sits on may set X-Forwarded-For. Without + // this pin any client could spoof its IP and defeat the per-IP login rate + // limiter, which keys on ctx.ClientIP(). The CIDR must match the network + // defined in docker-compose.yml. err = r.SetTrustedProxies([]string{"172.28.0.0/16"}) if err != nil { panic(err) @@ -50,10 +64,15 @@ func main() { if err != nil { log.Fatal(err) } + // Dev only; the seeder creates an admin with a known password. if os.Getenv("SEED_DB") == "true" { services.SeedDatabase(db) } + // DOMAIN does double duty: the WebSocket origin allow-list and the auth + // cookie 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) // SPOTIFY @@ -71,6 +90,9 @@ func main() { authSecret := os.Getenv("BACKEND_SECRET") 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 refreshTokenLifetime := 365 * 24 * time.Hour authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint} @@ -87,6 +109,8 @@ func main() { steamID := os.Getenv("STEAM_ID") // EMAIL SYNC + // An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30 + // minute default stands — a typo here fails quietly. emailSyncInterval := 30 * time.Minute if interval := os.Getenv("EMAIL_SYNC_INTERVAL"); interval != "" { if parsed, err := time.ParseDuration(interval); err == nil { @@ -110,10 +134,16 @@ func main() { } emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient) + // 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) store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID} + // Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in + // the Gin context, so the order in the admin group matters. + // + // Paths below have no /api prefix: nginx strips it before proxying. protected := r.Group("/", store.AuthMiddlewear) admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware) @@ -146,6 +176,8 @@ func main() { admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong) // 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) protected.POST("/messages/upload", store.UploadMessageFile) @@ -153,6 +185,12 @@ func main() { admin.GET("/notes/*path", store.GetNoteFile) // GRAPHQL + // GraphQL is assembled by hand rather than with handler.NewDefaultServer + // so the transports and extensions below are explicit. + // + // Note the whole API is one POST route with no middleware guard: + // authorisation happens per resolver via IsAdminFromCtx / UserIDFromCtx, + // so a new resolver is PUBLIC until it checks for itself. gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{ Resolvers: &graph.Resolver{Store: &store}, })) @@ -160,12 +198,20 @@ func main() { gqlSrv.AddTransport(transport.Options{}) gqlSrv.AddTransport(transport.POST{}) gqlSrv.AddTransport(transport.MultipartForm{}) + // Caches parsed query documents so repeated queries skip parsing. 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)) + // 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" if devMode && os.Getenv("GQL_INTROSPECTION") == "true" { 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), func(c *gin.Context) { gqlSrv.ServeHTTP(c.Writer, c.Request) }) @@ -180,11 +226,15 @@ func main() { c.JSON(200, gin.H{"message": "Hello World"}) }) - // Launch email sync scheduler + // The scheduler runs until ctx is cancelled, which in practice only + // happens if r.Run returns — there is no signal handling or graceful + // shutdown, so the container is simply killed. ctx, cancel := context.WithCancel(context.Background()) defer cancel() go store.EmailSync.StartScheduler(ctx) port := os.Getenv("BACKEND_PORT") + // Blocks forever; its error is not checked, so a failure to bind the port + // exits main silently with status 0. r.Run(fmt.Sprintf(":%s", port)) } diff --git a/backend/models/models.go b/backend/models/models.go index 1d1cede..57b5ec8 100644 --- a/backend/models/models.go +++ b/backend/models/models.go @@ -6,16 +6,42 @@ import ( "gorm.io/gorm" ) +// Package models holds the GORM entities, which are also the GraphQL object +// 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 in Go but Int in GraphQL, which is why nearly every type +// has a hand-written ID resolver doing int(obj.ID). + +// 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 { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` Username string `gorm:"uniqueIndex" json:"username"` - Password []byte `json:"-"` - Admin bool `json:"admin"` + // 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:"-"` + // 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"` } +// 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 { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -27,16 +53,27 @@ type Post struct { Content string `json:"content"` } +// Message is one chat message. The table is capped at 50 rows by the +// 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 { - ID uint `gorm:"primarykey" json:"id"` - Content string `json:"text"` - AuthorID uint `json:"authorId"` - FileURL string `json:"fileUrl,omitempty"` + ID uint `gorm:"primarykey" json:"id"` + Content string `json:"text"` + AuthorID uint `json:"authorId"` + FileURL string `json:"fileUrl,omitempty"` + // 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"` CreatedAt time.Time `json:"createdAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` } +// 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 { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -47,6 +84,7 @@ type Activity struct { Link *string `json:"link"` } +// Favorite is a "currently enjoying" entry on the home page. type Favorite struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -57,6 +95,13 @@ type Favorite struct { Link *string `json:"link"` } +// Rowing is one rowing machine session, created by uploading a photo of the +// display (see handlers.CreateRowing). +// +// 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 { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -68,6 +113,7 @@ type Rowing struct { Calories float64 `json:"calories"` } +// Bookmark is a link on the bookmarks page, grouped by Category. type Bookmark struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -78,6 +124,9 @@ type Bookmark struct { Link string `gorm:"not null" json:"link"` } +// JobAppReference is a reusable snippet for filling in job application forms +// (a stock answer, a profile link, and so on), grouped by Category and +// ordered within it by SortOrder. type JobAppReference struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -89,15 +138,31 @@ type JobAppReference struct { SortOrder int `gorm:"default:0" json:"sortOrder"` } +// ProcessedEmail records that the email pipeline has already looked at a +// message, so it is never classified twice. +// +// Unlike every other model it has no DeletedAt and so is NOT soft deleted — +// the dedup check must see every historical row. Its CreatedAt also drives +// the next sync's time window, so the most recent row here is effectively the +// pipeline's cursor. A row is written even when classification failed, with +// Action "error", which means failures are never retried. type ProcessedEmail struct { - ID uint `gorm:"primarykey" json:"id"` - CreatedAt time.Time `json:"createdAt"` - GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"` - Subject string `gorm:"not null" json:"subject"` - Action string `gorm:"not null" json:"action"` - JobAppID *uint `json:"jobAppId"` + ID uint `gorm:"primarykey" json:"id"` + CreatedAt time.Time `json:"createdAt"` + // The provider's message id: Microsoft Graph's id on the Graph backend, + // the RFC822 Message-ID header on IMAP. Unique, which is what makes the + // dedup check safe against a concurrent sync. + GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"` + Subject string `gorm:"not null" json:"subject"` + Action string `gorm:"not null" json:"action"` + // The application this email created or updated, if any. A plain nullable + // column, not a GORM association — nothing preloads it. + JobAppID *uint `json:"jobAppId"` } +// 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 { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` @@ -113,6 +178,14 @@ type Place struct { Done bool `gorm:"default:false" json:"done"` } +// JobApplication is a tracked job application. Rows are created by hand +// through GraphQL or automatically by the email pipeline. +// +// Status is a free-form string, but only the values ranked in +// services.statusOrder ("applied", "screening", "assessment", +// "interviewing", "offer", "rejected", "withdrawn") can be advanced +// automatically; the pipeline matches an existing application on +// (Company, JobTitle) compared case-insensitively. type JobApplication struct { ID uint `gorm:"primarykey" json:"id"` CreatedAt time.Time `json:"createdAt"` diff --git a/backend/services/auth.go b/backend/services/auth.go index c3a411a..5d96836 100644 --- a/backend/services/auth.go +++ b/backend/services/auth.go @@ -8,10 +8,16 @@ import ( "github.com/golang-jwt/jwt/v5" ) +// Auth mints and verifies the HS256 JWTs that back the site's login. Tokens +// are handed to the browser as HTTP-only cookies (see handlers.Store.Login); +// there is no server-side session or token blacklist, so a token stays valid +// until it expires even after logout. type Auth struct { Config *AuthConfig } +// 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 { Secret []byte Domain string @@ -20,17 +26,26 @@ type AuthConfig struct { Endpoint string } +// Tokens is a freshly minted access/refresh token pair, both already signed. type Tokens struct { AccessToken string RefreshToken string } +// InitAuth builds the Auth service from config. func InitAuth(config *AuthConfig) *Auth { auth := Auth{Config: config} return &auth } +// GenerateJWT issues an access/refresh pair for user. +// +// 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: 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. func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) { accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "username": user.Username, @@ -57,10 +72,20 @@ func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) { return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil } +// keyFunc supplies the HMAC secret to the JWT parser. The token argument is +// 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) { return auth.Config.Secret, nil } +// 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) { token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()})) if err != nil { diff --git a/backend/services/claude.go b/backend/services/claude.go index cb13dcc..5be1695 100644 --- a/backend/services/claude.go +++ b/backend/services/claude.go @@ -5,11 +5,20 @@ import ( "github.com/anthropics/anthropic-sdk-go/option" ) +// ClaudeConfig holds the Anthropic API credentials. type ClaudeConfig struct { APIKey string } +// InitClaude builds the shared Anthropic client. It is used in two places: +// reading a rowing machine display from a photo (handlers.CreateRowing) and +// classifying job-application emails (EmailSyncService.processEmail). +// +// No validation happens here: with an empty or wrong API key construction +// still succeeds and the failure only surfaces on the first request. func InitClaude(config *ClaudeConfig) *anthropic.Client { + // anthropic.NewClient returns a value, not a pointer, so take its address + // to share one client across every caller. client := anthropic.NewClient(option.WithAPIKey(config.APIKey)) return &client } diff --git a/backend/services/database.go b/backend/services/database.go index e8b1f28..cd3ebec 100644 --- a/backend/services/database.go +++ b/backend/services/database.go @@ -8,6 +8,8 @@ import ( "gorm.io/gorm" ) +// SQLConfig holds the PostgreSQL connection parameters, all read from the +// environment in main. type SQLConfig struct { User string Password string @@ -16,6 +18,9 @@ type SQLConfig struct { Port string } +// 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) { dsn := fmt.Sprintf( "user=%s password=%s dbname=%s host=%s port=%s sslmode=disable", @@ -30,6 +35,12 @@ func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) { return db, nil } +// migrateDatabase brings the schema up to date. This project has no +// 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 { err := db.AutoMigrate( &models.User{}, @@ -51,6 +62,7 @@ func migrateDatabase(db *gorm.DB) error { return nil } +// InitDatabase connects to Postgres and runs the auto-migration. func InitDatabase(config *SQLConfig) (*gorm.DB, error) { db, err := connectToPostgreSQL(config) if err != nil { diff --git a/backend/services/email_imap.go b/backend/services/email_imap.go index a891860..117477f 100644 --- a/backend/services/email_imap.go +++ b/backend/services/email_imap.go @@ -15,6 +15,17 @@ import ( "time" ) +// This file is a hand-rolled IMAP client, used as an alternative mail source +// to Microsoft Graph. It exists because the Graph path needs an Azure app +// registration and admin consent, while IMAP needs only an app password. +// +// It implements the bare minimum of RFC 3501 — LOGIN, SELECT, SEARCH, FETCH, +// LOGOUT — by matching on string prefixes rather than parsing IMAP's grammar +// properly. It works against Outlook and similar servers with the response +// shapes seen in practice; it is not a general-purpose IMAP client. + +// IMAPConfig holds the mailbox credentials. Password is an app password, not +// an account password. type IMAPConfig struct { Host string Port string @@ -27,9 +38,15 @@ type IMAPConfig struct { type imapClient struct { conn net.Conn reader *bufio.Reader - tag atomic.Int64 + // tag numbers the commands. IMAP allows several in flight at once + // identified by tag; this client never does that, so the atomic is + // belt-and-braces rather than load-bearing. + tag atomic.Int64 } +// imapDial opens an implicit-TLS IMAP connection (port 993 style, TLS from the +// first byte — there is no STARTTLS support here) and consumes the server +// greeting, which arrives unsolicited before any command. func imapDial(addr string) (*imapClient, error) { conn, err := tls.Dial("tcp", addr, nil) if err != nil { @@ -47,21 +64,31 @@ func imapDial(addr string) (*imapClient, error) { return c, nil } +// Close drops the TCP connection. Callers normally send LOGOUT first. func (c *imapClient) Close() error { return c.conn.Close() } +// nextTag returns the next command tag, e.g. "A0001". The width is cosmetic: +// past 9999 the tags simply get longer, and they stay unique. func (c *imapClient) nextTag() string { return fmt.Sprintf("A%04d", c.tag.Add(1)) } +// readLine reads one CRLF-terminated protocol line with the terminator +// stripped. There is no read deadline anywhere in this client, so an +// unresponsive server can block a sync until the TCP connection itself fails. func (c *imapClient) readLine() (string, error) { line, err := c.reader.ReadString('\n') return strings.TrimRight(line, "\r\n"), err } -// sendCommand sends a tagged command and reads lines until the tagged response. -// Returns all untagged response lines and the final tagged status line. +// sendCommand sends a tagged command and reads lines until the line beginning +// with that tag, which is the server's final status for the command. +// Everything before it is an untagged ("* ...") response and is returned. +// +// This must not be used for FETCH: it reads line by line and would mistake the +// bytes of a literal for protocol lines. Use sendFetch instead. func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) { tag := c.nextTag() _, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd) @@ -87,7 +114,8 @@ func (c *imapClient) sendCommandOK(cmd string) ([]string, error) { if err != nil { return untagged, err } - // Status line is like: A0001 OK ... or A0001 NO ... + // Status line is " OK ..." on success, " NO ..." or + // " BAD ..." otherwise; only the second field matters. parts := strings.SplitN(status, " ", 3) if len(parts) < 2 || parts[1] != "OK" { return untagged, fmt.Errorf("command %q failed: %s", cmd, status) @@ -95,7 +123,10 @@ func (c *imapClient) sendCommandOK(cmd string) ([]string, error) { return untagged, nil } -// fetchLiteral reads an IMAP literal {N}\r\n followed by N bytes. +// readLiteral reads exactly size bytes of an IMAP literal, i.e. the payload +// announced by a trailing "{N}" on the preceding line. It must read by byte +// count rather than by line because the payload is arbitrary binary data that +// will itself contain CRLFs. func (c *imapClient) readLiteral(size int) (string, error) { buf := make([]byte, size) _, err := io.ReadFull(c.reader, buf) @@ -105,8 +136,15 @@ func (c *imapClient) readLiteral(size int) (string, error) { return string(buf), nil } -// sendFetch sends a FETCH command and collects the full response including literals. -// Returns raw response lines (with literals inlined after their header lines). +// sendFetch sends a FETCH and collects its response, handling literals. +// +// The returned slice interleaves protocol lines with literal payloads: when a +// line ends in "{N}" the next entry is the N bytes that followed it. The +// caller (fetchEmailsIMAP) relies on that pairing. +// +// The literal is detected with LastIndex("{") plus a "}" suffix rather than a +// real parse, so a line whose text merely ends in braces could be misread — +// tolerable because only FETCH responses reach this code. func (c *imapClient) sendFetch(cmd string) ([]string, error) { tag := c.nextTag() _, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd) @@ -158,7 +196,11 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err } defer c.Close() - // Quote the password to handle special characters + // %q wraps the password in double quotes and backslash-escapes any quote + // or backslash inside it, which happens to be exactly IMAP's quoted-string + // syntax. The username is NOT quoted: an address needs no escaping. + // Note this sends the password in a LOGIN command, so it is only safe + // because the connection is TLS from the first byte. quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password) if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil { return nil, fmt.Errorf("IMAP login: %w", err) @@ -168,14 +210,19 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err return nil, fmt.Errorf("IMAP select INBOX: %w", err) } - // SEARCH SINCE uses date only (no time), per IMAP spec + // SEARCH SINCE has day granularity only — the time of day is not + // expressible — so this always over-fetches back to midnight of `since`. + // Harmless: SyncEmails deduplicates by message id. The date must be in + // IMAP's dd-Mon-yyyy form, hence this exact layout string. dateStr := since.UTC().Format("02-Jan-2006") untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr)) if err != nil { return nil, fmt.Errorf("IMAP search: %w", err) } - // Parse sequence numbers from "* SEARCH 1 2 3 ..." + // Parse sequence numbers from "* SEARCH 1 2 3 ...". parts[2:] skips the + // "*" and "SEARCH" tokens; a bare "* SEARCH" (no matches) has len 2 and + // is skipped by the length test. var seqNums []string for _, line := range untagged { if strings.HasPrefix(line, "* SEARCH") { @@ -194,13 +241,18 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr) + // Every matching message is fetched in one command with a comma-separated + // sequence set, and each full body is held in memory. A mailbox with a + // very busy day could make this large — there is no batching. seqSet := strings.Join(seqNums, ",") fetchLines, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet)) if err != nil { return nil, fmt.Errorf("IMAP fetch: %w", err) } - // Parse fetched messages - literals contain the raw RFC822 message + // Pair each "... BODY[] {N}" header line with the literal that sendFetch + // stored immediately after it. A message that fails to parse is logged and + // skipped rather than failing the whole sync. var messages []graphMessage for i := 0; i < len(fetchLines); i++ { line := fetchLines[i] @@ -208,7 +260,11 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err if strings.Contains(line, "BODY[]") && strings.HasSuffix(line, "}") { if i+1 < len(fetchLines) { raw := fetchLines[i+1] - i++ // skip the literal + // Advance past the literal so its contents are never + // examined as a protocol line. Note this is a C-style loop + // precisely so i can be advanced here; a range loop could + // not do it. + i++ gm, err := parseRawEmail(raw) if err != nil { log.Printf("[EmailSync/IMAP] Error parsing email: %v", err) @@ -219,11 +275,16 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err } } + // LOGOUT errors are ignored: the emails are already in hand and the + // deferred Close will drop the connection regardless. c.sendCommand("LOGOUT") return messages, nil } -// parseRawEmail parses an RFC822 email into a graphMessage. +// parseRawEmail parses a raw RFC822 message into the same graphMessage struct +// the Graph API path produces, so everything downstream is source-agnostic. +// An unparseable Date falls back to now, and a missing From leaves both name +// and address empty rather than failing. func parseRawEmail(raw string) (graphMessage, error) { msg, err := mail.ReadMessage(strings.NewReader(raw)) if err != nil { @@ -266,7 +327,16 @@ func parseRawEmail(raw string) (graphMessage, error) { }, nil } -// extractTextBody pulls the text/plain or text/html content from a message body. +// extractTextBody pulls readable content out of a message body, preferring +// text/plain and falling back to text/html. +// +// It recurses into nested multipart parts by re-wrapping the part's bytes in a +// synthetic mail.Header carrying just its Content-Type — a shortcut that works +// because this function only ever reads Content-Type. +// +// Quoted-printable and base64 transfer encodings are NOT decoded, so a +// base64-encoded body reaches Claude as base64. Read errors on a part are +// swallowed and the part is skipped. func extractTextBody(header mail.Header, body io.Reader) string { contentType := header.Get("Content-Type") if contentType == "" { @@ -326,7 +396,9 @@ func extractTextBody(header mail.Header, body io.Reader) string { return string(b) } -// decodeHeader decodes RFC 2047 encoded header values. +// decodeHeader decodes RFC 2047 encoded-words (the "=?UTF-8?Q?...?=" form +// used for non-ASCII subjects), returning the input unchanged if it is not +// encoded or cannot be decoded. func decodeHeader(s string) string { dec := new(mime.WordDecoder) decoded, err := dec.DecodeHeader(s) diff --git a/backend/services/email_sync.go b/backend/services/email_sync.go index 1d3189a..685ef21 100644 --- a/backend/services/email_sync.go +++ b/backend/services/email_sync.go @@ -21,8 +21,18 @@ import ( "gorm.io/gorm" ) +// This file is the job-application email pipeline. On a timer it fetches +// recent mail (via Microsoft Graph or plain IMAP), keeps the ones that look +// recruitment-related, asks Claude to turn each into structured data, and +// creates or advances a models.JobApplication row. Every email it has looked +// at is recorded as a models.ProcessedEmail so it is never handled twice. + +// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token +// survives restarts, exactly like the Spotify token. const MSGRAPH_TOKEN_JSON_PATH = "/backend/token/msgraph_token.json" +// EmailSyncConfig configures the pipeline. Backend picks the mail source; +// anything other than "graph" or "imap" leaves the service permanently idle. type EmailSyncConfig struct { Backend string // "graph" or "imap" ClientID string @@ -34,22 +44,38 @@ type EmailSyncConfig struct { Enabled bool } +// EmailSyncService owns the sync pipeline. type EmailSyncService struct { - Config *EmailSyncConfig - OAuthConfig *oauth2.Config + Config *EmailSyncConfig + OAuthConfig *oauth2.Config + // HTTPClient doubles as the readiness flag: nil means "not configured or + // not yet authenticated", and both the scheduler and the manual-trigger + // handler refuse to run while it is nil. On the Graph backend it is a + // real token-injecting client; on the IMAP backend it is set to + // http.DefaultClient purely so this check passes (IMAP never uses it). HTTPClient *http.Client DB *gorm.DB ClaudeClient *anthropic.Client - mu sync.Mutex + // mu is used with TryLock, not Lock: it makes a sync a no-op while + // another one is running rather than queueing behind it, so the manual + // admin trigger cannot pile up on top of the scheduled run. + mu sync.Mutex } // Microsoft Graph API response types +// Microsoft Graph API response types. The IMAP backend parses raw RFC822 +// messages into these same structs (see parseRawEmail) so that everything +// downstream of fetchEmails is backend-agnostic. + +// graphMessagesResponse is one page of /me/messages; NextLink is Graph's +// cursor for the next page and is empty on the last one. type graphMessagesResponse struct { Value []graphMessage `json:"value"` NextLink string `json:"@odata.nextLink"` } +// graphMessage is a single email. type graphMessage struct { ID string `json:"id"` Subject string `json:"subject"` @@ -59,15 +85,18 @@ type graphMessage struct { BodyPreview string `json:"bodyPreview"` } +// graphFrom wraps the sender, which Graph nests one level deep. type graphFrom struct { EmailAddress graphEmailAddress `json:"emailAddress"` } +// graphEmailAddress is a display name plus address. type graphEmailAddress struct { Name string `json:"name"` Address string `json:"address"` } +// graphBody is the message body; ContentType is "html" or "text". type graphBody struct { ContentType string `json:"contentType"` Content string `json:"content"` @@ -75,6 +104,9 @@ type graphBody struct { // Claude response type +// EmailAnalysis is the JSON contract Claude is asked to return; the keys here +// must stay in step with emailClassificationPrompt at the bottom of this file. +// Pointer fields are the ones Claude is allowed to answer null for. type EmailAnalysis struct { IsJobEmail bool `json:"isJobEmail"` Action string `json:"action"` @@ -89,6 +121,12 @@ type EmailAnalysis struct { // Email filtering config +// Cheap pre-filter, applied before any Claude call so that the bulk of a +// mailbox never costs an API request. It is intentionally over-inclusive: +// false positives are cheap (Claude rejects them), false negatives are not +// (the email is never looked at again once its window has passed). + +// subjectKeywords match case-insensitively anywhere in the subject line. var subjectKeywords = []string{ "application", "interview", "offer", "rejected", "assessment", "applied", "candidate", "position", "role", "hiring", @@ -96,6 +134,8 @@ var subjectKeywords = []string{ "next steps", "coding challenge", "take-home", } +// senderDomains are applicant-tracking systems; mail from any of them is +// considered job-related whatever the subject says. var senderDomains = []string{ "greenhouse.io", "lever.co", "workday.com", "myworkday.com", "ashbyhq.com", "smartrecruiters.com", "icims.com", @@ -105,6 +145,11 @@ var senderDomains = []string{ // Status progression order +// statusOrder ranks the application lifecycle so updates can only move an +// application forwards (see updateJobApplication). A status missing from this +// map is treated as unknown and never applied. Note that "rejected" and +// "withdrawn" sit at the top, so once an application reaches them nothing can +// move it back. var statusOrder = map[string]int{ "applied": 0, "screening": 1, @@ -117,6 +162,9 @@ var statusOrder = map[string]int{ // Token persistence +// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions. +// Like the Spotify equivalent it copies into a local struct so the on-disk +// shape does not depend on the oauth2 package's own JSON tags. func SaveMSGraphToken(path string, tok *oauth2.Token) error { data := struct { AccessToken string `json:"access_token"` @@ -142,6 +190,8 @@ func SaveMSGraphToken(path string, tok *oauth2.Token) error { return os.WriteFile(path, jsonBytes, 0600) } +// LoadMSGraphToken reads a token written by SaveMSGraphToken. A missing file +// is reported as an error and means "not yet authenticated". func LoadMSGraphToken(path string) (*oauth2.Token, error) { data, err := os.ReadFile(path) if err != nil { @@ -174,6 +224,18 @@ type persistingTokenSource struct { lastToken *oauth2.Token } +// Token returns a valid token, refreshing through the wrapped source when +// needed and writing any new token back to disk. +// +// Without this wrapper the oauth2 client would refresh happily in memory but +// the file on disk would keep the original refresh token; Microsoft rotates +// refresh tokens, so after the original expired the service would have to be +// re-authorised by hand on the next restart. +// +// There is no mutex here even though oauth2's client may call Token from +// several goroutines. In practice syncs are serialised by EmailSyncService.mu +// so concurrent calls do not arise; the worst case if they ever did is a +// duplicate write of the same token. func (p *persistingTokenSource) Token() (*oauth2.Token, error) { tok, err := p.base.Token() if err != nil { @@ -189,6 +251,12 @@ func (p *persistingTokenSource) Token() (*oauth2.Token, error) { return tok, nil } +// InitEmailSync builds the service and, for the Graph backend, restores a +// saved OAuth session. It never fails: a misconfigured or unauthenticated +// service is returned with a nil HTTPClient, which leaves the pipeline idle +// while the rest of the backend starts normally. For Graph, the authorisation +// URL is printed to the container log for a one-off manual sign-in that +// lands on GET /email/callback. func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService { svc := &EmailSyncService{ Config: config, @@ -264,7 +332,13 @@ func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error return nil } -// StartScheduler runs SyncEmails on a recurring interval. +// StartScheduler runs SyncEmails immediately and then on every tick until ctx +// is cancelled. It is meant to be run in its own goroutine and returns +// straight away when the service is disabled or unauthenticated. +// +// Because readiness is only checked once here, authenticating later via +// /email/callback does NOT start the scheduler; the backend has to be +// restarted, or syncs triggered by hand through POST /email/sync. func (s *EmailSyncService) StartScheduler(ctx context.Context) { if !s.Config.Enabled { log.Println("[EmailSync] Disabled, skipping scheduler") @@ -300,11 +374,17 @@ func (s *EmailSyncService) StartScheduler(ctx context.Context) { // SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update. func (s *EmailSyncService) SyncEmails(ctx context.Context) error { + // TryLock, so a manual trigger during a scheduled run is rejected + // immediately instead of blocking a request for minutes. if !s.mu.TryLock() { return fmt.Errorf("sync already in progress") } defer s.mu.Unlock() + // Registered after the unlock defer, therefore it runs BEFORE it: the + // panic is absorbed here and the mutex is still released afterwards. + // A recovered panic makes SyncEmails return nil, so the caller sees a + // successful sync — the log line is the only evidence. defer func() { if r := recover(); r != nil { log.Printf("[EmailSync] PANIC recovered: %v", r) @@ -313,7 +393,13 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { log.Println("[EmailSync] Starting sync...") - // Determine the time window: use the most recent ProcessedEmail timestamp, or default to 24h ago + // Window start = when the last email was *processed*, not when it was + // received. Those differ by up to one sync interval, which is deliberate: + // it overlaps the windows so nothing that arrived mid-sync is missed. The + // overlap re-fetches a few emails, and the ProcessedEmail dedup below is + // what stops them being handled twice. On a cold database (no processed + // emails at all) it falls back to the last 24 hours, so the pipeline + // never tries to ingest an entire mailbox. since := time.Now().Add(-24 * time.Hour) var latest models.ProcessedEmail if err := s.DB.Order("created_at DESC").First(&latest).Error; err == nil { @@ -342,7 +428,10 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { continue } - // Process this email + // A failed email is still recorded (with action "error") so the next + // sync skips it rather than retrying — and, importantly, so it does + // not hold the window open. The trade-off is that a transient Claude + // outage permanently drops those emails. action, jobAppID, processErr := s.processEmail(ctx, email) if processErr != nil { log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr) @@ -379,7 +468,8 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error { return nil } -// fetchEmails retrieves emails since the given time using the configured backend. +// fetchEmails retrieves emails since the given time using the configured +// backend, normalising both into []graphMessage. func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) { if s.Config.Backend == "imap" { return s.fetchEmailsIMAP(since) @@ -399,6 +489,8 @@ func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time "$orderby": {"receivedDateTime asc"}, } + // Graph paginates with @odata.nextLink, which already carries every query + // parameter, so the loop below only builds this first URL by hand. nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode()) for nextURL != "" { @@ -415,6 +507,8 @@ func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time body, err := io.ReadAll(resp.Body) resp.Body.Close() + // Status is checked before the read error so that a non-200 reports + // Graph's own error body rather than a generic read failure. if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body)) } @@ -446,6 +540,9 @@ func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage { return matched } +// matchesFilter reports whether an email looks job-related on subject or +// sender alone. See subjectKeywords for why this errs towards including too +// much. func (s *EmailSyncService) matchesFilter(email graphMessage) bool { subjectLower := strings.ToLower(email.Subject) for _, kw := range subjectKeywords { @@ -498,6 +595,10 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) return "", nil, fmt.Errorf("empty response from Claude") } + // Only the first content block is read, and the prompt asks for bare JSON, + // but models still wrap output in a markdown fence often enough that it is + // stripped defensively here. The two TrimPrefix calls are ordered so that + // "```json" is removed first and a plain "```" otherwise. raw := message.Content[0].Text raw = strings.TrimSpace(raw) raw = strings.TrimPrefix(raw, "```json") @@ -518,7 +619,11 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) return "skipped", nil, nil } - // Try to find an existing job application + // Applications are identified by (company, job title) compared + // case-insensitively — there is no external id to match on. Claude + // wording the same role slightly differently therefore creates a second + // application rather than updating the first. The most recent match wins + // when there are several. var existing models.JobApplication found := s.DB.Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", analysis.Company, analysis.JobTitle). @@ -537,6 +642,7 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) return "skipped", &existing.ID, nil } +// createJobApplication inserts a new application from Claude's analysis. func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) { app := models.JobApplication{ Company: analysis.Company, @@ -547,6 +653,8 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string Notes: analysis.Notes, } + // The prompt asks for YYYY-MM-DD but full RFC3339 comes back often enough + // to be worth trying first; an unparseable date is dropped silently. if analysis.AppliedAt != nil { if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil { app.AppliedAt = &t @@ -567,6 +675,10 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string return "created", &app.ID, nil } +// updateJobApplication advances an existing application's status, but only +// ever forwards through statusOrder. Emails commonly arrive out of order (a +// delayed "thanks for applying" after an interview invite), and this is what +// stops a stale email dragging an application backwards. func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) { newOrder, newExists := statusOrder[analysis.Status] currentOrder, currentExists := statusOrder[existing.Status] @@ -596,7 +708,13 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, return "updated", &existing.ID, nil } -// cleanEmailBody strips HTML and truncates the email body for Claude. +// cleanEmailBody reduces an email body to plain-ish text before it is sent to +// Claude, cutting token cost and noise. +// +// The HTML handling is a regex tag-strip, not a parser: fine for extracting +// prose, but it would mangle inline diff --git a/vue/src/components/Footer.vue b/vue/src/components/Footer.vue index 554b484..5e763b6 100644 --- a/vue/src/components/Footer.vue +++ b/vue/src/components/Footer.vue @@ -1,4 +1,10 @@