Files
stpweb/CLAUDE.md
T
adamfandClaude Opus 5.5 3139e8e239
Test and deploy / test (push) Successful in 1m40s
Test and deploy / deploy (push) Successful in 4s
CI: run tests and Renovate on the build VM
The test job and Renovate move to stpbuild's runner (label `build`), a
new Proxmox VM; deploy and maintenance stay on stpvm (`self-hosted`).
test fetches over HTTP with the job's own GITEA_TOKEN. DEPLOYMENT.md
gains a "Build VM" section, and CLAUDE.md says where each job runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:00:13 +00:00

18 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

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, docker compose config for both compose files, and the Caddy image build, which validates caddy/ for both modes. Each part is also its own target (check-backend, check-python, check-vue, check-compose, check-caddy); make help lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and main only deploys if they pass — so run make check before pushing. Dependency-update PRs come from Renovate (renovate.json5, run weekly by .gitea/workflows/renovate.yaml), since Dependabot is GitHub-only; that test job skips the Vue build, so run make check-vue on an npm PR before merging it.

Full stack (dev mode, HTTP only)

cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build

.env.dev is committed and every value in it is a dummy: local-only passwords, fake third-party keys, DOMAIN=localhost, background jobs that touch real accounts switched off. It has to be copied to .env because several services read env_file: ./.env directly. Never put a real credential in it. Dev mode seeds the database with test data (SEED_DB=true) and serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. Visit http://localhost. Uploads stay on disk unless a dev stpcore is also running (from that repo, with LAN_BIND=172.17.0.1 and the same dummy keys as .env.dev), which GARAGE_UPSTREAM=host-gateway reaches.

Full stack (production, HTTPS)

docker compose up --build

Frontend only (hot reload)

cd vue && npm run dev

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

cd vue && npm run build

npm run build is a plain vite build.

Regenerate GraphQL (after editing schema files)

cd backend && go run github.com/99designs/gqlgen generate

This regenerates graph/generated.go and graph/model/models_gen.go. Resolver implementations in *.resolvers.go files are preserved.

Architecture

Dockerized multi-service personal website self-hosted on stpvm (an x86-64 Ubuntu VM; formerly a Raspberry Pi).

Backend (backend/): Go with Gin router. GraphQL API via gqlgen at POST /api/graphql. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.

Frontend (vue/): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served by Caddy (production) or proxied to Vite dev server (dev mode).

Python API (python/): FastAPI app served by uvicorn on port 8000. Caddy proxies /py/ to it and strips the prefix, so routes in python/app/main.py are written relative to /. Swagger UI at /py/docs. Dev mode mounts python/app and runs uvicorn with --reload. The site's Claude call lives here, behind an internal route: /internal/rowing/read (behind POST /api/rowing). The Go backend calls it directly over the Docker network through services.CallPython, and Caddy 404s /py/internal/. The model is one setting, CLAUDE_MODEL (default claude-sonnet-5-5), set in .env; python/app/claude.py shapes the request per model. Adding another route is a short recipe in python/README.md ("Internal routes").

Job tracker and notes editor (on stppriv): the job tracker (adamf/job-tracker) and the SilverBullet editor run on their own LXC, from the adamf/stppriv repo, at priv.<DOMAIN>. stppriv's Caddy gates them with this site's admin session (the cookie is set for the parent domain), asking /api/auth/validate-admin over the LAN; requests from STPPRIV_LAN_IP to that path skip the api rate limit. Caddy here 301s /sb/, /jobs/ and the old /cv/jobs, /cv/leads and userscript URLs there. stppriv is the notes vault's only writer; silverbullet-git here runs with SYNC_MODE=pull and feeds /notes/.

Gitea (own repo, adamf/stpgit): git, Actions and the image registry (<DOMAIN>/adamf/...) run in their own Proxmox LXC since 2026-11-24, from the adamf/stpgit repo (this repo's gitea/ directory until then) with their own Postgres (gitea-db) and .env, deployed by hand there and never by CI. Everything on stpvm reaches it as GITEA_HOST (git.<DOMAIN>, :3000 HTTP and :2222 SSH), pinned to the LXC's LAN IP (GITEA_UPSTREAM) by extra_hosts in containers and /etc/hosts on the host; public DNS for that name is Cloudflare, which carries only HTTPS. There is no Gitea container or forwarder in this stack since 2026-11-24. stpvm keeps an act_runner (label self-hosted) for the jobs that touch the stack (deploys, maintenance); tests, image builds and Renovate run on the build VM stpbuild (Proxmox VM 123, 192.168.178.240, label build) since 2026-11-26, which fetches over HTTP with each job's own GITEA_TOKEN. See "Build VM" in DEPLOYMENT.md §7. Runbook: that repo's README, summarised in "Gitea LXC" in DEPLOYMENT.md §7.

Uploads / Garage (Garage itself on stpcore): every stored file goes through one path. Frontend: vue/src/uploads.js (uploadFile(file) → URL, plus ACCEPT for pickers, kindOf, isUploadUrl, tagFor). Backend: POST /api/uploads (handlers/handle_upload.go), a thin wrapper over services.Uploads.Save (services/uploads.go), which owns the type table (UploadTypes), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. GET /api/uploads (admin only, Uploads.List, listUploads()) lists what is stored, bucket and disk merged, for components/util/UploadPicker.vue, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in Garage (the uploads volume when S3_ENDPOINT is unset, or when Garage refuses a write). Garage and garage-webui are not in this stack: they run on the stpcore LXC, from the adamf/stpcore repo (the shared core other stacks depend on; its README is the runbook, including garage/bootstrap.sh), and the name garage is pinned to its LAN IP (GARAGE_UPSTREAM) by extra_hosts in caddy, backend and usaco. Caddy serves /uploads/ from Garage's anonymous website endpoint (garage:3902) first and the volume second, so the bucket is the source of truth and a Garage or stpcore outage only affects bucket-only files. Private attachments (/uploads/private/) always stay on disk. /garage/ (admin-gated) proxies to stpcore's Caddy on garage:3909, adding X-Core-Token (GARAGE_WEBUI_TOKEN), which that Caddy requires before it forwards to garage-webui. A new consumer of the store gets its own key and bucket on stpcore and the same extra_hosts pin. "Garage" in DEPLOYMENT.md §7 covers this side.

Caddy (caddy/): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into ./caddy/data), so there is no certbot. caddy/Caddyfile holds the global options and the shared snippets (proxy, limit, admin_gate, permission_gate, the upload headers, logging); caddy/routes.caddy is the one route table both modes use — add a new route there, in the right place, because inside its route block the first matching handle wins; caddy/sites/prod.caddy and sites/dev.caddy hold what differs (TLS, security headers, the apex, static caching, /), picked by CADDY_SITE. Every variable the config reads goes through the caddy service's explicit environment: list. The image build runs caddy validate, so make check-caddy (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (import limit <zone> <events> <window>) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to logs/caddy/payloads.log. The traffic container tails that file so it shows up in Dozzle, which is served at /dozzle/ behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (http://127.0.0.1/caddy-health); the autoheal container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea is not proxied any more: it lives at git.<DOMAIN> (its own tunnel, from the stpgit repo) and /gitea/* 301s there; only the registry at the apex's /v2/ still goes through Caddy. caddy/edge_test.sh checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in .deprecated/nginx/ and .deprecated/certbot/, kept for the rollback in DEPLOYMENT.md §7.

Backend Structure

  • main.go — entry point: wires up DB, services, router
  • handlers/store.go — Store struct holds DB, SpotifyAuth, Auth, Notes, etc. Passed to all handlers
  • handlers/handle_*.go — REST handlers grouped by domain
  • graph/schema/*.graphql — GraphQL schema files (source of truth)
  • graph/*.resolvers.go — resolver implementations (one per schema file, follow-schema layout)
  • 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, Bookmark, Place, Box, Page, Background, Layout, Component, CoverLetter, CoverSnippet)
  • 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), uploads (uploads.go: validation, naming, Garage bucket with disk fallback), 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/api.js — thin REST client for the /api JSON endpoints; failures become an ApiError carrying the backend's error message and the status
  • src/uploads.js — storing and showing uploaded files: uploadFile(file) → public /uploads/... URL, ACCEPT for file pickers, kindOf/tagFor/isUploadUrl/mediaSize. Every upload goes through it
  • src/stores/ — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components, coverLetters, coverSnippets. createCrudStore.js is the factory behind places, boxes and pages; createMirrorStore.js is the one behind the home-page slices
  • src/views/ — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the Box GraphQL type, drawn by views/home3/BoxCanvas.vue per page key: the landing page (/, key index) is one, and admin-created Pages (e.g. shrines, and /stp, the Page with slug stp) are served at /<slug> by the router's catch-all, views/canvas/CanvasPage.vue. A Layout is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). A Component is a saved, named HTML box: "+ New box" places copies of it, and the canvas's Components button also places it linked (Box.componentId), so the box shows the component's HTML and editing it edits every linked box; the built-in starters in templates.js become components through that panel's "Import built-ins". Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional Background, set from the canvas's Background button and painted by DefaultLayout. See "The /stp canvas" in vue/README.md
  • 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.

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. 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.
  • Per-service permissions: a non-admin account can be granted individual gated services (today only receipt, for /receipt/) in the admin panel's Manage Users tab. The keys are the registry services.PermissionTypes (backend/services/permissions.go), stored in User.Permissions; admins hold them all. Caddy's permission gate (import permission_gate <key> in a route, see caddy/routes.caddy and the snippet in caddy/Caddyfile) asks GET /auth/validate/<key>, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its route from import admin_gate to import permission_gate <key>. /auth/validate-admin and the admin gate are unchanged.
  • Spotify tokens: Persisted to /backend/token/spotify_token.json inside the container, surviving restarts.
  • Environment variables: every variable goes in .env.example, and a dummy value for it in .env.dev. One the Python service reads must also be added to the python service's explicit environment: list in docker-compose.yml, or the container never receives it. .env is edited by hand on the host; there is no admin-panel editor.
  • Gitea feed: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
  • All GORM models use soft delete (gorm.DeletedAt field). 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

  • Keep comments rare and short. Code should explain itself through names and structure. Comment only a non-obvious why (a security boundary, an upstream quirk, an ordering constraint), in a line or two. No history, dates, migration notes or narration of what the code does: those belong in commit messages and the READMEs. If you change behaviour a comment describes, update or delete it.
  • Resolver commentary lives inside function bodies, because gqlgen relocates or strips anything above the signature when regenerating.
  • Schema files use # comments, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
  • Legacy views are kept, not deleted. vue/src/views/unused/, Intro.vue, Gym.vue, the unlisted CV templates and similar carry a STATUS: header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in views/unused/ is not proof.