From 810d3118b3c1a7a9ab6d62c5cd7b9174bcbd1446 Mon Sep 17 00:00:00 2001 From: Adam French Date: Mon, 12 Oct 2026 14:39:19 +0100 Subject: [PATCH] Document make check, schema-level auth and the Python Claude routes Bring CLAUDE.md, README.md and DEPLOYMENT.md in line with the CI gate, the GraphQL directives, the shared nginx routes partial and the move of every Claude call to the Python service. CLAUDE.md also said there was no token revocation; logout and password changes bump TokenVersion. Co-Authored-By: Claude Opus 5.5 --- .env.example | 6 +++--- CLAUDE.md | 30 +++++++++++++++++++++-------- DEPLOYMENT.md | 48 +++++++++++++++++++++++++++++++++++++--------- README.md | 14 ++++++++++++-- docker-compose.yml | 2 +- 5 files changed, 77 insertions(+), 23 deletions(-) diff --git a/.env.example b/.env.example index 6393d66..b18f51c 100644 --- a/.env.example +++ b/.env.example @@ -164,9 +164,9 @@ DOMAIN= EMAIL= # --- Third-party API keys (backend) ------------------------------------------ -# CLAUDE_API_KEY is also passed to the python service, which makes the Claude -# calls for the rowing photo reader and the job posting reader; the backend -# uses it for the email pipeline. +# CLAUDE_API_KEY is used by the python service, which makes every Claude call +# in the stack: the rowing photo reader, the job posting reader and the email +# pipeline's classifier. The backend no longer calls Claude itself. CLAUDE_API_KEY= STEAM_API_KEY= STEAM_ID= diff --git a/CLAUDE.md b/CLAUDE.md index 2366c7c..f2d9ec7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,6 +4,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Build & Run Commands +### Check everything + +``` +make check +``` + +Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. + ### Full stack (dev mode, HTTP only) ``` @@ -24,7 +32,7 @@ docker compose up --build cd vue && npm run dev ``` -Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`. +Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets default to `localhost:8080`, `:3000`, `:8000` and `:8000` and are overridden with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (shell or `vue/.env.local`). Compose publishes none of the backend, Python or Icecast ports to the host, and `/py` and `/radio` share a default, so set these to wherever the services really are — see the comment in `vue/vite.config.js`. ### Frontend build @@ -32,6 +40,8 @@ Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000` cd vue && npm run build ``` +`npm run build` compiles the Rust crate first and needs `wasm-pack`. `npm run build:js` (plain `vite build`) is the check to use when only the JS changed and `src/wasm/` already exists. + ### Regenerate GraphQL (after editing schema files) ``` @@ -48,9 +58,9 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi. **Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode). -**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. Two routes are internal — `/internal/rowing/read` (the Claude call behind `POST /api/rowing`) and `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`): the Go backend calls them directly over the Docker network and nginx 404s `/py/internal/`. +**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **Every Claude call in the stack lives here**, behind three internal routes: `/internal/rowing/read` (behind `POST /api/rowing`), `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`) and `/internal/email/classify` (behind the email sync). The Go backend calls them directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. Adding another is a short recipe in `python/README.md` ("Internal routes"). -**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). +**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. ## Backend Structure @@ -62,12 +72,14 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi. - `graph/generated.go` — auto-generated by gqlgen, do not edit - `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit - `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing) -- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, Claude client, DB seeding +- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns) +- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), job status vocabulary (`job_status.go`), DB seeding. There is no Claude client in Go any more ## Frontend Structure - `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`) -- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData +- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status +- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, jobApplications, jobAppReferences. `createCrudStore.js` is the factory behind the last three; `createMirrorStore.js` is the one behind the home-page slices - `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines) - `src/components/` — reusable UI components - `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`. @@ -75,11 +87,13 @@ 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` (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`. +- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded). +- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`. +- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`. +- **Job status is one vocabulary.** `enum JobStatus` in `graph/schema/job_application.graphql` is what GraphQL accepts, and a test ties it to `services.statusOrder`. Three copies are *not* checked and must be edited by hand with it: the classifier prompt in `python/app/email_classify.py`, `vue/src/views/CV/jobStatus.js`, and `STATUS_LABELS` in the userscript. - **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts. - **Job capture**: `vue/public/job-capture.user.js` is a Violentmonkey userscript, served by the site and installed from `/cv/jobs`, that adds the posting open in the browser to the tracker. It calls the three `/api/jobs/capture` REST routes with a bearer token because cookies do not travel from other origins. The token is generated on the admin panel and stored hashed in `backend/token/job_capture_token.json`; there is no env var for it. Bump its `@version` on every edit or installed copies will not update. See "Job capture" in `backend/README.md`. -- **Environment tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it), with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`. +- **Environment tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it); a variable the Python service reads must also be added to the `python` service's explicit `environment:` list in `docker-compose.yml`, which a second test checks against the registry, with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`. - **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API. - **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. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index e99c831..77d93ea 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -85,8 +85,8 @@ in one step — never change one without the other.** nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its file *list*; direct `/.fs/` fetches and server-rendered page URLs still serve them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without - adding it to the deny regex in both nginx templates publishes it. See the - comment above `location /notes/` in `nginx.conf.template`. + adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the + comment above `location /notes/` in `nginx_routes.conf.template`. - **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. @@ -113,9 +113,30 @@ docker compose up --build 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`. +On the Pi this is triggered automatically by `.gitea/workflows/deploy.yaml`, +which has two jobs: + +- **`test`** runs on every push to any branch. It exports the pushed commit + (never the deploy checkout) and runs the backend's `go vet` + `go test` in + `golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build is + not repeated here: the image build in the deploy step does it, and a failed + build leaves the old containers running. +- **`deploy`** runs only on `main`, only after `test` passes, and only if the + tested commit is still the tip of `main` (so an older run cannot deploy a + newer, untested commit). It fetches over `ssh://git@localhost:2222`, + hard-resets the deploy checkout, and runs + `docker compose up -d --build --remove-orphans` under the + `env-apply/run/lock` flock. + +The test job keeps state on the Pi outside the deploy checkout: a bare +repository cache at `/home/adamf/.cache/web_server-ci/` and three named +volumes (`web_server_ci_gomod`, `web_server_ci_gobuild`, `web_server_ci_pip`). +The weekly maintenance workflow's `docker image prune -af` removes the two +toolchain images, so the first run after it pulls them again; the volumes +survive. Maintenance takes the same flock around its compose steps. + +`make check` runs the same checks locally, plus the Vue build and compose +validation — run it before pushing, since a red `test` job blocks the deploy. ### Development @@ -239,8 +260,13 @@ Two distinct mechanisms read it, and services use both: `gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own convention for overriding `app.ini` keys), and `python` receives an explicit allow-list, so it never sees the database password or any API key other than -the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY` for the rowing photo and -job posting readers). +the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`). The Python service +makes every Claude call in the stack — rowing photo reader, job posting reader +and email classifier — so it is the only container that reads `CLAUDE_API_KEY`; +the backend receives it through `env_file` but no longer uses it. A new +variable for the Python service has to be added to that allow-list as well as +`.env.example` and `backend/services/env_registry.json`; backend tests fail if +the three disagree. **`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two things between this checkout and `adamf@stppi.local:~/deploy/web_server`: @@ -445,8 +471,12 @@ Documented, not fixed — each would change deploy behaviour. 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. +4. **The two `/uploads/` location blocks are still written twice** — once in + `nginx.conf.template` and once in `nginx_dev_common.conf.template` — + because production adds security headers inside an auth-gated block. Every + other proxied route lives once in `nginx_routes.conf.template`, which both + configs include; the `auth_request` lines on `/uploads/private/` are the + one thing that must be kept in step by hand. 5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing only our own origin**, which defeats the point of having the header at all. 6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert diff --git a/README.md b/README.md index 78fed61..8434da8 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,7 @@ Create a `.env` file in the project root. All services read from this file. | `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) | | `DOMAIN` | Production domain name | | `EMAIL` | Email for Let's Encrypt registration | -| `CLAUDE_API_KEY` | Anthropic Claude API key | +| `CLAUDE_API_KEY` | Anthropic Claude API key (read by the Python service, which makes every Claude call) | | `STEAM_API_KEY` | Steam Web API key | | `STEAM_ID` | Steam user ID | | `PYTHON_HOST` | Python API hostname (defaults to `python`) | @@ -321,7 +321,17 @@ Visit `http://localhost` to test. cd vue && npm run dev ``` -Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`. +Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets default to `localhost:8080`, `:3000`, `:8000` and `:8000`; override them with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (see the comment in `vue/vite.config.js` — compose does not publish the backend, Python or Icecast ports to the host). + +### Checks + +```sh +make check +``` + +Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`. + +The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass. ## Untracked Files diff --git a/docker-compose.yml b/docker-compose.yml index 730dcb9..f71ce8c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -349,7 +349,7 @@ services: SB_REVISIONS: disabled # Newline separated (commas are silently ignored). Gitignore semantics, # so these match at any depth. Must match the folder list in the - # /notes/ deny regex in BOTH nginx templates, or a new entry here is + # /notes/ deny regex in nginx/nginx_routes.conf.template, or a new entry here is # hidden from the list but still publicly fetchable. SB_SPACE_IGNORE: | private/