Author SHA1 Message Date
renovate 386ff76bff Update alpine/git Docker tag to v2.54.0
renovate/stability-days Updates have met minimum release age requirement
Test and deploy / test (push) Successful in 9m44s
Test and deploy / deploy (push) Has been skipped
2026-11-16 04:05:14 +00:00
adamfandClaude Opus 5.5 89aaf8d79e Save cover letters, split them into draggable sections, add a paragraph bank
Test and deploy / deploy (push) Successful in 13m45s
Test and deploy / test (push) Successful in 2m17s
Weekly Maintenance / maintenance (push) Successful in 14m27s
Renovate / renovate (push) Successful in 5m54s
The /cv Cover Letter tab kept nothing across a refresh and was one flat list
of paragraphs. Letters are now saved as CoverLetter rows (body is the
frontend's JSON, checked only for being an object of sane size), split into
named sections whose paragraphs drag within and between them, with a bank of
reusable CoverSnippet paragraphs beside the page to drag in as copies.
Everything stored is @admin; visitors still get the blank template, and
section titles never print.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 16:03:48 +00:00
adamfandClaude Opus 5.5 0022429541 Add Renovate for weekly dependency-update PRs
Test and deploy / test (push) Successful in 1m19s
Test and deploy / deploy (push) Successful in 9s
Renovate / renovate (push) Successful in 6m21s
Weekly Maintenance / maintenance (push) Successful in 5m32s
Dependabot only runs on GitHub, so Renovate does the job against Gitea:
a Monday 04:00 workflow on the existing runner, configured by
renovate.json5. Non-major updates are grouped per ecosystem, the Go and
Python toolchains move with the CI test images, our own images and
Postgres majors are skipped, and nothing automerges since merging deploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 17:21:28 +00:00
adamfandClaude Opus 5.5 372f12dbca Split chat into public and private widgets, Places out of Collage, hide stamp scrollbars
Test and deploy / test (push) Successful in 2m9s
Test and deploy / deploy (push) Successful in 35s
Chat.vue (public) and PrivateChat.vue (admins only) are now separate canvas
widgets over a shared ChatPanel.vue, replacing the tabbed widget. The messages
store counts connect()/disconnect() so both can share one socket, and reopens
it on an admin change itself so two mounted chats reconnect once.

Places is its own widget (views/home/Places.vue); Collage is just the
slideshow. The stamp wall hides its scrollbars.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 17:02:57 +00:00
adamfandClaude Opus 5.5 79a9011212 Fix the tunnel's error 1000 and notes sync, move maintenance to 05:00
Test and deploy / test (push) Successful in 11m8s
Test and deploy / deploy (push) Successful in 8m25s
Weekly Maintenance / maintenance (push) Successful in 46s
nginx's network aliases for the public names vanish while it is stopped,
so cloudflared fell through to public DNS, got Cloudflare's own IPs and
visitors saw error 1000 on every deploy. nginx now has a fixed address and
cloudflared pins both names to it, so a stopped nginx is a plain 502.

The same aliases sent silverbullet-git's pushes to ssh://DOMAIN:2222 to
nginx, which has no 2222: nothing has pushed since 2026-10-15. It now maps
DOMAIN to the host gateway, where gitea publishes that port.

The weekly maintenance restarts dockerd and every container; at 01:00 it
kept catching late-night SilverBullet saves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 01:17:31 +00:00
adamfandClaude Opus 5.5 8bf70c98e8 Add a customisable shadow to canvas boxes
Test and deploy / test (push) Successful in 2m11s
Test and deploy / deploy (push) Successful in 1m21s
Weekly Maintenance / maintenance (push) Successful in 6m55s
A box can now cast a shadow, independent of its frame: ticking "Shadow" in
the box editor gives a hard offset shadow, and Hard/Soft/Glow presets or any
typed CSS box-shadow value customise it. The value is stored on Box and
Component and carried through duplicates, components and layouts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 23:18:35 +01:00
adamfandClaude Opus 5.5 e764078aaf Snap canvas boxes to each other's edges and centres, with guides
Test and deploy / test (push) Successful in 1m31s
Test and deploy / deploy (push) Successful in 39s
Dragging a box snaps its edges and centre to other boxes' and to the
canvas's sides, centre and top within 6 screen px, and draws a guide
along each shared line; a resize snaps the dragged edge. The 5px grid
still applies elsewhere. An "Align" button in the edit bar turns it off
(kept per browser), and Ctrl/Cmd mid-drag skips it once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:53:27 +01:00
adamfandClaude Opus 5.5 7969859955 Add saved components: reusable HTML boxes, placed as copies or linked
Test and deploy / test (push) Successful in 2m13s
Test and deploy / deploy (push) Successful in 1m23s
A component (models.Component, component.graphql) is a named HTML box.
"+ New box" now lists components and places a copy, as it did with the
hard-coded starters; the canvas's new Components button (ComponentPanel)
can also place one linked. A linked box has Box.componentId, its row's
html is nil, and the resolvers fill in the component's html before
answering (fillLinked), so saving the html in the box editor saves the
component and every linked box on every page changes. Only the html is
shared: title, geometry, frame and visibility stay each box's own.

The box editor gains "Save as component" (makes one from an html box and
links it) and, on a linked box, a banner with Detach (gives the box its
own copy). updateBox refuses html on a linked box. Deleting a component
detaches its boxes first, so no page changes. Layouts store the link and
the html; loading relinks only if the component still exists.

The built-in starters in templates.js are no longer listed directly:
"Import built-ins" in the panel creates them as components (skipping
names already taken), so they can be edited and deleted like the rest.
The html helpers there are unchanged. Everything is @admin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:32:40 +01:00
adamfandClaude Opus 5.5 263e16b70d usaco: let running jobs finish on stop, add a Claude budget
Test and deploy / test (push) Successful in 1m20s
Test and deploy / deploy (push) Successful in 1m12s
The site now waits up to 5 minutes on SIGTERM for running Claude jobs, so
stop_grace_period must be longer than Docker's 10s default.
USACO_CLAUDE_MONTHLY_BUDGET caps its estimated monthly Claude spend.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:10:08 +01:00
adamfandClaude Opus 5.5 acf21c69c2 Let non-admin accounts be granted single services, starting with /receipt/
Test and deploy / test (push) Successful in 1m57s
Test and deploy / deploy (push) Successful in 1m42s
Access was admin or nothing, so letting a friend print receipts meant making
them a full admin. Users now carry a list of permissions (User.Permissions,
a JSON column), each a key from the registry in services/permissions.go;
admins pass every check. The only key so far is `receipt`.

GET /auth/validate/:permission answers like /auth/validate-admin (200/403/401,
with the same refresh-token fallback, now shared) plus 404 for an unknown key,
and reads the user row rather than the token, so a grant or revoke applies on
the next request. On 200 it returns the username in X-Auth-User.

nginx gets a permission gate beside the admin gate: a location sets
$auth_permission and auth_requests /internal/auth/validate. /receipt/ moves
onto it, forwarding X-Remote-User to the receipt server. 403 now goes to
/no-access rather than back to the login page. The variable must not be given
a server-level default: the subrequest re-runs the server rewrite phase and
would blank it.

The admin panel's Manage Users tab ticks permissions per user
(setUserPermissions, permissionTypes). The login page is no longer
admin-only in wording or destination: a non-admin lands on /account, which
lists the services they can open; /no-access is the same view with a notice.

/auth/validate-admin and every other admin-gated service are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:04:56 +01:00
adamfandClaude Opus 5.5 efd74c1693 Add /receipt/, an admin-gated proxy to the receipt printer on stppi
Test and deploy / deploy (push) Successful in 1m41s
Test and deploy / test (push) Successful in 1m17s
The receipt_maker repo's `receipt serve` runs on stppi, which reaches the
Epson printer over the home LAN, and serves a page for printing a note or
an uploaded image. nginx gates /receipt/ on the admin session like
/tracker/, strips the prefix, adds the shared X-Receipt-Token and proxies
over Tailscale to RECEIPT_WEB_UPSTREAM (the one upstream off this host).
When stppi is unreachable, @receipt_offline answers 503 instead of a bare
502.

Both variables are defaulted in entrypoint.sh, and the token is quoted in
the template, so an unset pair still renders a valid config (/receipt/
then reads "offline"). The admin panel links to the page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 21:20:27 +01:00
adamfandClaude Opus 5.5 e181aa09bd Let the box editor panel be resized and its code scaled
Test and deploy / deploy (push) Successful in 32s
Test and deploy / test (push) Successful in 1m15s
Drag the panel's left edge (double-click to reset, arrow keys when
focused) to change its width; the canvas pads itself by the same width.
A−/A+ in the header, or Ctrl/Cmd +/-/0 in the editor, change the code's
text size. Both are remembered per browser in localStorage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 20:52:17 +01:00
adamfandClaude Opus 5.5 2eacbc2e33 Add saved layouts, and make /stp an ordinary canvas page
Test and deploy / test (push) Successful in 1m51s
Test and deploy / deploy (push) Successful in 1m10s
A layout is a named copy of one canvas page's boxes and background
(models.Layout, layout.graphql), saved from the canvas's new Layouts
button and loaded onto any page from there or from the admin Pages
tab. Loading onto a page with boxes asks whether to replace them or
add on top; a replace first saves the page as a "<page> before
<layout>" layout so it can be undone. Copies, not links: editing a
page never changes a layout or another page. The copying is
server-side in one transaction, and everything is @admin since a
layout keeps admin-only boxes.

/stp loses its static route and becomes a Page with slug "stp",
created once at start-up (ensureStpPage), so it can be renamed,
hidden or deleted like a shrine. Its boxes were already keyed "stp".
Home3.vue is kept as legacy; its starter is now "Old /stp grid" in
pageStarters.js. ConfirmDialog gains an optional second button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 20:33:07 +01:00
adamfandClaude Opus 5.5 8c535b1cc2 Polish the SPA: focus rings, reduced motion, forms that report errors
Test and deploy / test (push) Successful in 1m10s
Test and deploy / deploy (push) Successful in 58s
- Global :focus-visible ring (text fields get a border instead) and a
  prefers-reduced-motion override; the navbar marquee stops for it too.
- Button: disabled state and horizontal padding.
- useCreateForm returns error and submitting, so the create forms show a
  refused save inline and can't double-submit; they, Login, CreatePlace and
  CreateUser are real <form>s so Enter submits from any field.
- Admin: section list wraps on phones, Manage Users is a table with errors,
  Manage Radio confirms before deleting, page delete errors show inline.
- Hard-coded Tailwind colours replaced with tokens; 404 image alt text and
  no forced scrollbars.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 20:11:05 +01:00
adamfandClaude Opus 5.5 3fa456a063 Let the canvas panels choose from files already uploaded
Test and deploy / deploy (push) Has been cancelled
Test and deploy / test (push) Successful in 2m4s
The Background panel, the Box editor and the canvas admin bar could only
take a new upload, so reusing a picture meant uploading it again or
pasting its URL. Each now has a picker (UploadPicker.vue): a grid of the
public uploads, newest first, filterable by name.

It lists through a new admin-only GET /api/uploads (Uploads.List), the
union of the Garage bucket and the disk fallback, since nginx serves
from both; a bucket that can't list falls back to the disk's files.
Admin-only because upload URLs are public but unguessable, and a public
listing would give every one away. Private files and anything off the
UploadTypes allow-list are never listed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 19:59:03 +01:00
adamfandClaude Opus 5.5 1ddaff0690 Update CV: add usaco, job-tracker and rowing_stats, refresh the platform entry
Test and deploy / deploy (push) Successful in 36s
Test and deploy / test (push) Successful in 1m7s
Rewrite the Programming CV around current work: the self-hosted platform
on stpvm (no longer the Pi), the usaco site, the job tracker and the
rowing OCR pipeline. Skills become one-line rows, earlier hospitality
roles are condensed, and Soft Skills is dropped to make room. Both A4
sheets were checked in print preview, since overflow is clipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 20:21:19 +01:00
adamfandClaude Opus 5.5 fce6821f84 Add the usaco site's code runner
Test and deploy / test (push) Successful in 1m13s
Test and deploy / deploy (push) Successful in 18s
usaco-runner compiles, runs and lints solutions for the usaco site's
solve page. It runs submitted code, so it gets no environment, sits
only on usaco-runner-net (internal: no internet, and only the site can
reach it), and runs read-only apart from an exec-able /tmp tmpfs, with
memory, CPU and pids limits, no capabilities and no-new-privileges.
The site joins that network and finds it through RUNNER_URL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:25:47 +01:00
adamfandClaude Opus 5.5 582b190698 Give the usaco site an OpenAI key and a private audio bucket for reviews
Test and deploy / test (push) Successful in 1m7s
Test and deploy / deploy (push) Successful in 56s
The site's new recording reviews transcribe the admin's audio with
OpenAI (USACO_OPENAI_API_KEY) and, when USACO_S3_* is set, keep the
recordings in Garage's private usaco-audio bucket for playback. The
public uploads bucket is never used. The endpoint, region and bucket
are derived from the key, so a blank key leaves all five S3_* blank:
the site refuses to start with only some of them set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 01:57:05 +01:00
adamfandClaude Opus 5.5 289b5a5a1d Add /architecture: diagrams of how the site fits together
Test and deploy / test (push) Successful in 1m11s
Test and deploy / deploy (push) Successful in 31s
Eight hand-drawn SVG diagrams across five sections (infrastructure,
nginx, Go backend, Vue frontend, Python), sharing one diagram kit
(diagram.css, DiagramFigure, DiagramDefs) built on the site's tokens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 20:41:20 +01:00
adamfandClaude Opus 5.5 0e48befbc7 Give the usaco site the Claude key for its Explain button
Test and deploy / test (push) Successful in 1m4s
Test and deploy / deploy (push) Has been cancelled
The usaco site now has an admin Explain button that asks Claude for a
diagrammed explanation of a problem. Pass it CLAUDE_API_KEY, and its own
model setting, USACO_CLAUDE_MODEL (blank is claude-opus-5-5), so the
rowing reader's CLAUDE_MODEL is unaffected. Without the key the button
is off and the rest of the site works.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 20:38:05 +01:00
adamfandClaude Opus 5.5 ece1b654c7 Ignore .gstack/, the QA tooling's local reports
Test and deploy / test (push) Successful in 1m39s
Test and deploy / deploy (push) Successful in 6m19s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 20:07:29 +01:00
adamfandClaude Opus 5.5 1af625f5c3 Add a committed .env.dev with dummy values for the dev stack
Starting the dev stack meant hand-building a .env, and the quick route of
copying production's put real credentials on a dev machine: cookies were
scoped to the live domain (so localhost login failed) and the mail,
job-board and tunnel integrations ran against real accounts.

.env.dev holds a dummy for every variable in .env.example, in whatever
shape each service parses, with DOMAIN=localhost and the background jobs
that touch real accounts switched off. It is copied over .env because
several services read env_file: ./.env directly. OBSIDIAN_DIR points at a
tracked dev/notes/ folder so the bind mount never gets created as root.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 20:04:49 +01:00
adamfandClaude Opus 5.5 14f59a3d28 fix(qa): ISSUE-003 — reject posts without a title
createPost stored whatever it was given, so pressing Upload on the empty
admin Post form published a blank post to the feed. Refuse a blank
title, as createPage already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:55:50 +01:00
adamfandClaude Opus 5.5 ae961c1cd3 fix(qa): ISSUE-002 follow-up — only report rowing uploads done when all succeed
CreateRowing emitted "done" even when every file failed, so the admin
panel's new "Saved." notice sat under the failure rows, and the Gym
widget closed its modal before the errors could be read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:55:17 +01:00
adamfandClaude Opus 5.5 3d504da94c fix(qa): ISSUE-002 — confirm saves and make Cancel work on the admin forms
Admin.vue rendered the create forms without listening for their "done"
and "cancel" events, so a successful save gave no feedback and every
Cancel button did nothing. Show a "Saved." notice on done, and remount
the form on cancel to clear it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:53:19 +01:00
adamfandClaude Opus 5.5 48e18ba67d fix(qa): ISSUE-001 — leave the admin panel after logging out
Logging out on /admin cleared the session but left every admin form on
screen, because the requiresAdmin guard only runs on navigation. Route
to the login page once logOut() settles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:51:29 +01:00
adamfandClaude Opus 5.5 66db14d0c5 Keep nginx serving through a stalled worker, and gate Gitea's crawler targets
Test and deploy / deploy (push) Successful in 37s
Test and deploy / test (push) Successful in 1m13s
On 2026-10-19 nginx's only worker stalled for 4.6 hours. The master kept
the container "Up" and the tunnel stayed connected, so nothing noticed,
while every request timed out in the TLS handshake.

- worker_processes auto in the production and dev configs, so one stuck
  worker no longer takes the whole site down.
- A /nginx-health endpoint on :80 in all three configs, answered by nginx
  and unlogged, and a compose healthcheck on it.
- autoheal is back (retired 2026-10-01), pinned by digest, with no network,
  restarting only containers labelled autoheal=true: just nginx.
- Gitea's commit-pinned views, archives and compare pages go through the
  site admin gate. A swarm of 103k IPs made 129k requests to them in two
  days, 89% in those shapes; the branch views stay public for the CV links.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:15:38 +01:00
jobless e5b19956a2 yay
Test and deploy / deploy (push) Successful in 12s
Test and deploy / test (push) Successful in 2m37s
2026-10-19 12:01:20 +01:00
adamfandClaude Opus 5.5 4533b55da0 Remove the Rust/WASM crate and its build step
Test and deploy / test (push) Successful in 26s
Test and deploy / deploy (push) Successful in 38s
Weekly Maintenance / maintenance (push) Successful in 2m38s
Nothing live used it: main.js awaited the wasm init() on every page load,
but the only consumer, components/util/wasm/AutoScroll.vue, was never
imported. Dropping it removes the rust:slim + wasm-pack stage from the vue
image, the two Vite plugins that existed only for it, and the src/wasm/
guard in `make check-vue`, so a fresh clone builds without a Rust toolchain.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 21:11:09 +01:00
adamfandClaude Opus 5.5 65fddfcfa2 Give uploads one path end to end, and serve /uploads/ from Garage first
Test and deploy / deploy (push) Successful in 3m48s
Test and deploy / test (push) Successful in 37s
Frontend: src/uploads.js is the one way to store or show a file
(uploadFile, ACCEPT, kindOf, isUploadUrl, tagFor, mediaSize). Chat,
the box editor, canvas drops and the background editor all use it;
views/home3/upload.js and the chat store's own axios call are gone.

Backend: POST /api/uploads (was /messages/upload) is a thin wrapper over
services.Uploads.Save, which owns validation, naming and storage. The
three per-extension maps are now one UploadTypes table, and a refused
file is an *UploadError whose message is safe to show.

nginx now fetches /uploads/ from Garage first and falls back to the
volume on a 404 or any 5xx, so the bucket is the source of truth and
deleting a file in garage-webui unpublishes it, while a Garage outage
still only affects bucket-only files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 21:04:37 +01:00
adamfandClaude Opus 5.5 422cde4708 Store public uploads in a Garage S3 bucket, with garage-webui at /garage/
Test and deploy / test (push) Successful in 50s
Test and deploy / deploy (push) Successful in 1m10s
Opt-in and built so Garage can never take the site down:
- the backend writes to the bucket only once S3_ENDPOINT is set, and
  falls back to the uploads volume (with a log line) if a write fails;
- nginx serves /uploads/ from the volume first and Garage's anonymous
  website endpoint second, so every existing URL keeps working and nginx
  boots with no garage container;
- nothing depends_on garage and no variable is required, so a missing
  secret cannot fail a deploy.

Private attachments stay on disk, since nginx cannot gate a bucket.
garage/bootstrap.sh sets up the layout, bucket, key and website access;
the runbook is "Garage" in DEPLOYMENT.md.

Also lifts the body limit on the internal auth subrequest, which 413'd
large uploads to gated locations, and reserves the garage and dozzle
page slugs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 20:42:09 +01:00
adamfandClaude Opus 5.5 0ac3321c41 Gate /jobs/ and /tracker/ behind the nginx admin auth_request, like /sb/
Test and deploy / test (push) Successful in 27s
Test and deploy / deploy (push) Successful in 15s
The bearer-token routes a session cookie never reaches stay public at
nginx and are guarded by the apps: /jobs/api/capture and the job-capture
userscript, /tracker/api/v1/ and tracker.user.js.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 18:57:18 +01:00
adamfandClaude Opus 5.5 45d4aa6eb2 Stop pinning DOCKER_API_VERSION to 1.41 in CI
Test and deploy / deploy (push) Successful in 43s
Test and deploy / test (push) Successful in 27s
The pin let compose talk to the Pi's Docker 20.10. The host now runs
Docker 29 (API 1.56), so it only held compose to an old API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 18:07:35 +01:00
adamfandClaude Opus 5.5 529e80242f Set Gitea's SSH_DOMAIN and DOMAIN from GITEA_SSH_DOMAIN in .env
Test and deploy / test (push) Successful in 30s
Test and deploy / deploy (push) Successful in 34s
Moving hosts meant hand-editing the live app.ini, which the template
cannot reach once it exists. Gitea's environment-to-ini now writes the
value on every start, so a move is a one-line .env change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 17:54:03 +01:00
adamfandClaude Opus 5.5 f5ab1e81be Drop references to the removed sync-secrets.sh
Test and deploy / deploy (push) Successful in 1m33s
Test and deploy / test (push) Successful in 2m56s
The script no longer exists; .env is edited by hand on the host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 17:48:56 +01:00
adamfandClaude Opus 5.5 a244bee184 Move the site from the Pi (stppi) to stpvm
Gitea's SSH_DOMAIN and DOMAIN now name stpvm's tailnet address, and the
docs describe the host generically instead of as a Raspberry Pi.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 17:46:32 +01:00
adamfandClaude Opus 5.5 efbec1006f Use the Pi's real checkout path in the logrotate snippet
Test and deploy / test (push) Successful in 1m29s
Test and deploy / deploy (push) Successful in 1m38s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 15:47:12 +01:00
adamfandClaude Opus 5.5 58880a4e07 Log request bodies at nginx and view logs in Dozzle
Test and deploy / deploy (push) Has been cancelled
Test and deploy / test (push) Has been cancelled
nginx writes one JSON line per request, body included, to
logs/nginx/payloads.log (nginx/payload_log.conf). Bodies mentioning a
password, token or secret are logged as [redacted]. A `traffic` container
tails the file so it shows up as its own stream in Dozzle, which is served
at /dozzle/ behind the admin auth_request.

Dozzle replaces the admin panel's Diagnostics tab, so that tab and the
/admin/logs endpoint behind it are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 15:46:26 +01:00
adamfandClaude Opus 5.5 604ac32028 Remove the admin panel's Environment tab and env-apply
Test and deploy / test (push) Successful in 2m2s
Test and deploy / deploy (push) Successful in 1m35s
.env is edited by hand again. Drops the /admin/env endpoints, EnvManager
and its registry, the host-side apply.py watcher and its install script,
the backend's env-apply bind mount, and the Environment tab.

The deploy and maintenance workflows still serialise docker compose, now
on .compose.lock in the checkout instead of env-apply/run/lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 15:29:55 +01:00
adamfandClaude Opus 5.5 c9d599a371 Correct the /etc/hosts note in the tunnel docs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 14:24:32 +01:00
adamfandClaude Opus 5.5 6d5420fab2 Point the tunnel at the site's own name instead of No TLS Verify
Test and deploy / test (push) Successful in 1m45s
Test and deploy / deploy (push) Successful in 22s
nginx now carries DOMAIN and www.DOMAIN as aliases on app-network, so
cloudflared's origin can be https://www.DOMAIN: it resolves to nginx over
the bridge and the Let's Encrypt certificate verifies, with no TLS
overrides in the Cloudflare dashboard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 14:17:59 +01:00
adamfandClaude Opus 5.5 602aa522d6 Serve the site through a Cloudflare tunnel
Test and deploy / test (push) Successful in 2m9s
Test and deploy / deploy (push) Successful in 1m45s
A cloudflared container dials out to Cloudflare and forwards the site's
hostnames to nginx on :443, so the router's 80/443 forwards can close.
nginx takes the visitor's address from CF-Connecting-IP, trusted only from
cloudflared's fixed IP, so rate limits stay per visitor.

certbot can now validate over DNS-01 through the Cloudflare API when
CLOUDFLARE_DNS_API_TOKEN is set, so renewal needs no inbound port; without
it, it falls back to the webroot as before. DEPLOYMENT.md covers setup and
what stays off the tunnel: registry traffic on the Pi (pin the apex to
127.0.0.1 to dodge the 100 MB body cap), Gitea SSH and the radio harbor
(Tailscale).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 14:03:10 +01:00
adamf 3da49f4b24 Refactor frontend overlays
Test and deploy / test (push) Successful in 1m39s
Test and deploy / deploy (push) Successful in 26s
2026-10-15 12:40:56 +01:00
adamfandClaude Opus 5.5 ca3cd4db30 Autosave box HTML, fix editor selection, make /shrines a canvas page
Test and deploy / test (push) Successful in 1m56s
Test and deploy / deploy (push) Successful in 48s
The HTML editor's selection was invisible: CodeMirror's focused-selection
rule outranked ours and painted #233, and the opaque active line covered
the selection layer. Match its selector and make the active line
translucent.

Unsaved HTML now saves on leaving a box (selecting another, clicking
empty canvas, Done, closing the panel) instead of asking to discard.

/shrines is no longer a hard-coded route but an ordinary canvas page,
with links placed by hand as Link boxes; the backend no longer reserves
the slug. The Shrine starter layout is gone, and the admin Pages tab
gains a "New shrine" form that makes a blank page under shrines/.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 12:27:06 +01:00
adamfandClaude Opus 5.5 e54aaac181 Add per-page backgrounds to canvas pages
Test and deploy / test (push) Successful in 1m56s
Test and deploy / deploy (push) Successful in 1m0s
Each canvas page key (the landing page, /stp, shrines and other admin-made
pages) can have its own background: a colour, an image and how the image
fills the window. Admins set it from a Background button beside Edit layout,
with live preview and image upload or drop; DefaultLayout paints it behind
the whole window and falls back to the halftone.

Backed by a new Background GraphQL type keyed by page key, validated
server-side, hidden with admin-only pages, and moved or deleted along with
its page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:41:19 +01:00
adamfandClaude Opus 5.5 967b464779 Make the landing page a box canvas, and add Link box templates
Test and deploy / test (push) Successful in 1m23s
Test and deploy / deploy (push) Successful in 27s
The fixed bio-and-links page is gone; / is now an editable canvas (page
key "index") like /stp. The old content is kept as boxes in
landingLayout.js behind an "Import old landing page" button, which now
shows on a non-empty canvas too and confirms before adding.

The overlay mode only the landing page used is removed from BoxCanvas.
New "Link" and "Link row" HTML templates give bordered link buttons
that open with target=_top/_blank, since the box is a sandboxed frame.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:10:14 +01:00
adamfandClaude Opus 5.5 a8c55148af Keep the overlay canvas full width while the box editor is open
Test and deploy / test (push) Successful in 1m33s
Test and deploy / deploy (push) Successful in 29s
The editor's padding rescaled the landing page's overlay, pulling its
notes off the content they are pinned over. The fixed panel now just
covers the overlay instead; other canvases still shrink beside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:55:13 +01:00
adamfandClaude Opus 5.5 30918eefaa Raise the upload rate limit to 30/min, burst 20
Test and deploy / test (push) Successful in 1m54s
Test and deploy / deploy (push) Successful in 1m2s
Dropping several pictures onto a canvas page uploads them all at once,
which the old 5/min, burst 3 limit cut off after three. Uploading needs
a signed-in user and accounts are admin-created, so a far higher
ceiling is still safe against filling the volume.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:48:44 +01:00
adamfandClaude Opus 5.5 30e1fb31d8 Fix the landing notes editor, drop-to-upload pictures, retire Demoman
The box editor rendered inside the landing page's overlay canvas, which
is pointer-events: none so the page underneath stays clickable; the
panel inherited it and ignored every click and keystroke. It is now
teleported to <body>.

Image and video files dropped onto a canvas in edit mode are uploaded
and each becomes an unframed box at the drop point, sized to its aspect
ratio. The upload code moves to home3/upload.js, shared with the
editor's "Insert upload".

The hand-written Demoman shrine is unrouted (and its slug unreserved)
so it can be remade as a canvas page. /shrines lists only canvas pages
and keeps the admin-only create form behind a "+ New shrine" button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:47:15 +01:00
adamfandClaude Opus 5.5 bb5fd2bef9 Make the box canvas reusable: canvas pages, admin-only boxes, landing notes
Test and deploy / test (push) Successful in 2m8s
Test and deploy / deploy (push) Successful in 1m8s
The /stp canvas is now BoxCanvas.vue, keyed by a page. Boxes carry a
page ("stp", "index" for the landing page's notes overlay, or a Page
slug) and an adminOnly flag that the boxes resolver filters server-side.

A new Page type lets the admin create canvas pages in the browser,
served at /<slug> by the router's catch-all (CanvasPage.vue), starting
from a Blank, Shrine or Notes-board layout. Slugs that an SPA or nginx
route would answer first are refused. Renaming a page moves its boxes;
deleting it deletes them.

The GTO, Evangelion and Skipskipbenben placeholder routes are dropped
in favour of canvas pages listed on /shrines, which the landing page
now links to. The box editor gains an admin-only toggle and an
upload-and-insert button, and there are Note, Heading, Text, Gallery
and Video templates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 23:36:48 +01:00
adamfandClaude Opus 5.5 44347e40eb Link the job tracker, activity tracker and USACO from the front page
Test and deploy / test (push) Successful in 1m42s
Test and deploy / deploy (push) Successful in 1m11s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 22:45:30 +01:00
adamfandClaude Opus 5.5 c5a722bd1e Add the usaco service and its /usaco/ route
Test and deploy / test (push) Successful in 2m14s
Test and deploy / deploy (push) Successful in 1m36s
The USACO practice log from the usaco repo's site/: one container, git
as its store (a clone in ./usaco-data), behind nginx with the prefix
kept, like /jobs/. Gitea may now deliver webhooks to it by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:49:48 +01:00
adamfandClaude Opus 5.5 1b5c8fc4a9 Document the activity tracker's admin-gated pages
Test and deploy / test (push) Successful in 1m39s
Test and deploy / deploy (push) Successful in 26s
The tracker now gates its dashboard and new setup page on the site's
admin session, as jobs does. Pass it AUTH_VALIDATE_URL built from
BACKEND_HOST/PORT so it follows the backend if that is renamed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:27:02 +01:00
adamf 746f20158e Remove too many stamps
Test and deploy / test (push) Successful in 1m45s
Test and deploy / deploy (push) Successful in 21s
2026-10-14 21:20:02 +01:00
adamfandClaude Opus 5.5 d28524e8c0 Run the activity tracker as its own published image at /tracker/
Test and deploy / test (push) Successful in 2m0s
Test and deploy / deploy (push) Successful in 1m29s
Same shape as jobs: adam-french.co.uk/adamf/activity-tracker, published by
the adamf/ccp repo's CI, with an explicit environment list and its own
database role. nginx strips the /tracker prefix. The env test now covers
the new service's allow-list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 20:39:05 +01:00
adamfandClaude Opus 5.5 e788e16898 Make /stp an admin-editable canvas of boxes
Test and deploy / test (push) Successful in 1m58s
Test and deploy / deploy (push) Successful in 1m18s
/stp is now views/home3/Home3.vue: boxes an admin creates, drags, resizes
and edits in the browser, saved to the database so every visitor sees the
same layout.

- backend: a Box GraphQL type (kind widget|html, x/y/w/h/z in px on a
  1400px design canvas, framed, hideOnMobile). Public `boxes` query;
  create/update/delete are @admin. Geometry is clamped rather than
  rejected. Framed has no gorm default, since GORM would turn an explicit
  false into true on insert.
- vue: widget boxes render the existing widgets from a registry; html
  boxes render in an iframe sandboxed with allow-scripts and no
  allow-same-origin, so admin script can't read cookies or call /api. The
  site tokens and fonts (inlined as data: URLs) are injected into each
  frame. The canvas scales to fit the window; phones get a single column
  in (y, x) order. Edit mode saves geometry on release and has a
  CodeMirror side panel (lazy-loaded) with a live HTML preview. Templates
  cover Clock, Weather (Open-Meteo) and Image/GIF. "Import current layout"
  recreates the old Home.vue grid on an empty canvas.
- Home.vue is kept with a STATUS: legacy header. Docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 18:15:03 +01:00
adamf f66d9c52ee ignore claude
Test and deploy / test (push) Successful in 1m29s
Test and deploy / deploy (push) Successful in 9s
2026-10-14 17:49:18 +01:00
adamfandClaude Opus 5.5 99fe175ebf Delete the old job code now that the tracker runs on its own
Test and deploy / test (push) Successful in 1m9s
Test and deploy / deploy (push) Successful in 1m33s
The job tracker has run from its own image at /jobs/ since 931b02c, so its
old copy here goes: the GraphQL schema, resolvers and models for
applications, references, sources, leads and the search profile; the
capture and email handlers and services; the Python posting reader, lead
scorer and email classifier; the Vue pages, stores and the capture-token
card on the Environment tab; and the userscript (nginx already redirects
its old URL to /jobs/).

The six old tables stay in the stp database: AutoMigrate never drops
anything, and dropping them is a manual step. The env variables stay in
the registry, where they already belong to the jobs service.

Docs (CLAUDE.md, DEPLOYMENT.md and the three READMEs) now describe the
site without the tracker, and DEPLOYMENT.md lists the jobs service and
./jobs-data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 17:35:18 +01:00
adamfandClaude Opus 5.5 931b02c9e4 Run the job tracker as its own container at /jobs/
Test and deploy / test (push) Successful in 2m3s
Test and deploy / deploy (push) Successful in 1m31s
The tracker (applications, leads, email pipeline, capture userscript) now
lives in the adamf/job-tracker repo and runs here from its published image.

- docker-compose.yml: a `jobs` service with an explicit environment list
  (its own database role; none of the site's other secrets), ./jobs-data
  mounted at /data, and nginx waiting for it. The dev override seeds it.
- nginx: /jobs/ proxied to it with the prefix kept, and 301s from
  /cv/jobs, /cv/leads and the old userscript URL.
- env_registry.json and .env.example: the email and job-lead variables now
  belong to the jobs service; CLAUDE_* to python and jobs; new
  POSTGRES_JOBS_* and JOBS_IMAGE_TAG. The compose environment test now
  checks the jobs service's list as well as python's.
- backend: no longer starts the email and job-lead schedulers or serves
  the capture and email routes, since the tracker reads the same settings
  and would otherwise process everything twice. The old job code stays
  until the tracker has run for a while.
- vue: the CV page's Jobs button goes to /jobs/; the old routes are gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 17:08:18 +01:00
adamfandClaude Opus 5.5 148b94959d Show the Tailscale SSH address as Gitea's clone URL
Test and deploy / test (push) Successful in 1m38s
Test and deploy / deploy (push) Successful in 13s
SSH (22 and 2222) is no longer forwarded by the router; it is reached
over the tailnet instead. SSH_DOMAIN only sets the clone URL Gitea
displays. HTTPS clones through nginx at ROOT_URL stay public.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 16:45:49 +01:00
adamfandClaude Opus 5.5 da2ab9fb17 Serve Gitea's container registry at /v2/ on the apex domain
Test and deploy / test (push) Successful in 1m35s
Test and deploy / deploy (push) Successful in 26s
Docker clients always talk to /v2/ at the root of the host, whatever
Gitea's ROOT_URL says, and Gitea advertises its token endpoint at
https://<domain>/v2/token. The apex server block redirected everything to
www, so the registry was unreachable. It now proxies /v2/ to Gitea, without
a body size limit or request buffering, and redirects the rest as before.

Needed to publish the job-tracker image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 16:37:22 +01:00
adamfandClaude Opus 5.5 8b902350ad Add rescoring and a posting-date order to the leads inbox
Test and deploy / test (push) Successful in 1m56s
Test and deploy / deploy (push) Successful in 1m8s
rescoreJobLeads (RescoreAll, "Rescore all" on /cv/leads) scores every
matched inbox lead again, for after the profile or the model has
changed. Scores are not wiped first: a lead keeps its old score until
the new one is saved, and the new scored_at column marks which leads the
job has reached, so a job that dies partway leaves no gaps. Leads that
had used up their attempts get them back.

The inbox can also be ordered by when a posting went up, falling back to
when it was found where the source gave no date.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 15:52:33 +01:00
adamfandClaude Opus 5.5 3764ea9c0b Default to Sonnet 5.5 and make the Claude model an admin setting
Every Claude call used a hard-coded claude-haiku-4-5. The model is now
CLAUDE_MODEL, read by the Python service, defaulting to
claude-sonnet-5-5 and offered on the admin panel's Environment tab as a
choice of Haiku 4.5, Sonnet 5.5 and Opus 5.5.

The request is shaped per model. Sonnet and Opus think by default and
bill that against max_tokens, so they get low effort and 4,000 tokens of
headroom over each caller's reply ceiling; Haiku 4.5 rejects the effort
setting and keeps the plain request. A refusal is logged and reported as
the route's failed message instead of surfacing as an empty reply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 15:52:33 +01:00
adamfandClaude Opus 5.5 299b5f5224 Add a way to score every unscored lead without polling
Test and deploy / test (push) Successful in 2m1s
Test and deploy / deploy (push) Successful in 1m21s
A run caps its scoring at forty leads, so a first poll of several boards
left a backlog that could only be cleared by pressing "Check now"
repeatedly, re-fetching every source each time.

scoreJobLeads (JobLeadService.ScoreAll, "Score unscored" on /cv/leads)
re-applies the keyword filter and then scores every matched, unscored
lead, with no cap on the count and a one-hour limit on the time. A lead
Claude fails on is tried once per press rather than three times, so a
passing failure does not write it off. It shares the run lock and the
polled status with runJobLeadSync, and the page now reloads the leads
while either job is in flight.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 15:36:32 +01:00
adamfandClaude Opus 5.5 af50e6c8ab Add a job leads inbox that finds and scores postings
Test and deploy / test (push) Successful in 1m55s
Test and deploy / deploy (push) Successful in 59s
The tracker recorded applications but could not find jobs. A new
pipeline (services/job_leads.go, job_sources.go) polls a watch list of
sources on a timer or on request, files unseen postings as leads, marks
which pass a keyword and location pre-filter, and has Claude score those
against a single search profile through a fourth internal Python route,
/internal/jobs/score.

Sources are Greenhouse, Lever and Ashby company boards (public JSON) and
Adzuna and Reed keyword searches (API keys). The two search fetchers are
written from the providers' documentation and tested only against stubs.

Leads are their own table, not a job status, and are not soft deleted:
the (source_kind, external_id) index is the dedup, so a dismissed lead
has to remain a row. A lead reaches the tracker only by promotion, which
goes through UpsertJobApplication. That upsert moves from the capture
handler into services so promotion and the fetcher can share it; the
capture endpoint's behaviour is unchanged.

/cv/leads is the page: inbox, watch list and profile form. The timer is
off unless JOB_LEADS_ENABLED=true and never runs at start-up, so a
deploy spends no Claude calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 15:03:46 +01:00
adamfandClaude Opus 5.5 810d3118b3 Document make check, schema-level auth and the Python Claude routes
Test and deploy / test (push) Successful in 5m12s
Test and deploy / deploy (push) Successful in 2m1s
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 <[email protected]>
2026-10-12 14:39:19 +01:00
adamfandClaude Opus 5.5 b832dd68b4 Gate deploys on tests and share the nginx route table
Makefile: make check runs the backend, Python, Vue and compose checks
that previously lived only in local notes.

deploy.yaml: a test job runs the backend and Python suites in containers
on every push, and deploy needs it. Deploy also refuses to run if main
has moved past the tested commit. maintenance.yaml takes the env-apply
lock around its compose steps, as deploy already did.

nginx: the 24 proxied locations that production and dev both carried now
live once in nginx_routes.conf.template, rendered by the entrypoint on
every boot path. The effective config is unchanged for both.

Remove the root package.json and lockfile, which nothing referenced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 14:39:19 +01:00
adamfandClaude Opus 5.5 d3f722d077 Give the job tracker stores and fix the admin route guard
createCrudStore captures the places store's pattern and now backs
places, job applications and job references. JobApplications.vue no
longer calls gql() itself and is split into the applications table, the
references table and the add form, with the status vocabulary in
jobStatus.js.

api.js is a thin REST client that turns failures into an ApiError
carrying the backend's message; the admin views and Listening.vue use it
in place of raw axios and fetch.

The router guard waited on the home query's loaded flag, which is never
set when that query fails, so /admin and /cv/jobs could hang. It now
awaits a standalone me query owned by the auth store, and homeData gains
a settled flag for widgets that only need to know the fetch finished.

The Vite proxy targets are configurable through VITE_PROXY_*, and
build:js runs the Vite build without wasm-pack.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 14:39:19 +01:00
adamfandClaude Opus 5.5 71344a1f8d Declare GraphQL auth in the schema and drop the Go Claude client
Authorisation: @admin and @signedIn schema directives replace the 25
hand-copied resolver checks. A test fails if a mutation has neither and
is not on the public allow-list, so a new mutation cannot ship unguarded.

IDs: uint model IDs bind through graphql.UintID, removing the ten
int(obj.ID) resolvers.

Job status is a GraphQL enum, tied to services.statusOrder by a test.
Input is strict, so the mutations no longer coerce an unknown status to
"applied"; output is lenient so one legacy row cannot fail the list.

deleteJobApplication and deleteJobAppReference now error on a missing id
like the other deletes.

The rowing reader, the job extractor and now the email classifier reach
the Python service through one services.CallPython helper. The email
pipeline's prompt and fence stripping moved to Python, and
anthropic-sdk-go is gone from go.mod.

Fix the auth test fixture, whose 11-byte secret had been panicking the
services test package since InitAuth began requiring 32 bytes. Add a
test that keeps the python service's compose environment list in step
with the env registry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 14:39:19 +01:00
adamfandClaude Opus 5.5 307268fbea Put every Claude call behind one helper in the Python service
rowing.py and jobs.py repeated the same call, error mapping, fence
stripping and validation; that now lives in claude.ask_json, and the
internal routes share one wrapper and one exception handler in main.py.

Add /internal/email/classify, which takes over the email pipeline's
Claude call from the Go backend (prompt ported verbatim, plus a sentence
fencing the email off as data).

The internal-only guard is now a dependency, so a request that came
through nginx gets 404 even when its body is invalid, where it used to
get 422.

requirements-dev.txt adds pytest and httpx on top of requirements.txt so
the tests run on a host; the image still installs only requirements.txt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 14:39:18 +01:00
adamfandClaude Opus 5.5 2786bce022 Manage .env from the admin panel
Add an Environment tab to /admin that lists every variable in .env.example
and lets keys, OAuth settings, email settings and generated secrets be
changed without SSH. Secrets are write-only; infrastructure variables are
shown read-only.

The backend never writes .env or touches Docker. It validates an edit and
queues it in env-apply/run/request.json; env-apply/apply.py, run on the host
by a systemd path unit (env-apply/install.sh), rewrites .env atomically,
keeps .env.bak, and recreates only the services that read the change.

backend/services/env_registry.json is the single list of variables, shared
by the backend and the host script; a test keeps it in step with
.env.example. It replaces the drifted checklist in handle_admin.go. The job
capture token card moves to the new tab.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 14:02:28 +01:00
adamfandClaude Opus 5.5 26f312e307 Generate the job capture token from the admin panel
Deploy with Docker Compose / deploy (push) Successful in 52s
The userscript's bearer token was an env var, JOB_CAPTURE_TOKEN, so rotating
it meant editing .env and redeploying. It is now minted on the admin
diagnostics panel instead, and the env var is gone.

- services.CaptureToken keeps only a SHA-256 of the token, in
  backend/token/job_capture_token.json beside the OAuth tokens, so it
  survives rebuilds and cannot be read back. The token is shown once.
- GET/POST/DELETE /admin/capture-token report, generate (replacing any
  existing token) and revoke it, behind the cookie-authenticated admin group.
- With no token generated the capture routes still answer 503.
- Userscript bumped to 1.0.1 for the changed prompt text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 13:40:30 +01:00
adamfandClaude Opus 5.5 b8670246a8 Add browser job capture to the job tracker
Deploy with Docker Compose / deploy (push) Successful in 1m31s
A Violentmonkey userscript, served by the site and installed from /cv/jobs,
adds the posting open in the browser (LinkedIn, an ATS, any company page) to
the tracker. Claude reads the title, company and location off the page text.

- Three token-guarded REST routes under /api/jobs/capture (status, extract,
  upsert). They take a bearer token, JOB_CAPTURE_TOKEN, because the auth
  cookies are SameSite=Lax and never sent from another origin. An unset token
  switches the routes off.
- The upsert matches on a canonical posting URL, then (company, job title),
  so a capture and the email pipeline do not make two rows for one job.
- The Claude call is a new internal Python route, /internal/jobs/extract,
  alongside the rowing reader; the client and fence stripping they share move
  to python/app/claude.py.
- New "saved" status ranked below "applied", and a description column holding
  the posting text, shown per row on the tracker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 13:33:28 +01:00
adamf 94eaa8e239 Merge branch 'rowing-reader-to-python' into main
Deploy with Docker Compose / deploy (push) Successful in 16m36s
Weekly Maintenance / maintenance (push) Successful in 1m58s
2026-10-09 11:47:56 +01:00
adamfandClaude Opus 5.5 f8d48ba9af Move the rowing photo Claude call to the Python service
POST /rowing in the Go backend no longer calls the Anthropic SDK. It keeps
the admin gate, EXIF date, duplicate check, sanity bounds and insert, and
sends the image to a new internal Python route, POST /internal/rowing/read,
which makes the Claude call and returns the three numbers it read.

The route spends a paid call and has no auth of its own, so nginx 404s
/py/internal/ and the route refuses anything carrying the proxy headers
nginx adds. The python container now receives CLAUDE_API_KEY.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-09 11:46:17 +01:00
adamf 5827fb3ddd Merge pull request 'Make the stamps wall bounce at every page size' (#8) from worktree-stamps-always-bounce into main
Deploy with Docker Compose / deploy (push) Successful in 16s
Weekly Maintenance / maintenance (push) Successful in 13m19s
Reviewed-on: https://www.adam-french.co.uk/gitea/adamf/web_server/pulls/8
2026-10-01 15:20:30 +01:00
adamf 6dd15414e9 Merge pull request 'Improve /stp layout on small screens' (#7) from worktree-small-screen-ui into main
Deploy with Docker Compose / deploy (push) Successful in 28s
Reviewed-on: https://www.adam-french.co.uk/gitea/adamf/web_server/pulls/7
2026-10-01 15:19:02 +01:00
adamfandClaude Opus 5.5 76735f0552 Improve /stp layout on small screens
- Listening and Steam: fit the artwork to the cell instead of scrolling.
  The image is now a flexible item that takes the height left over after
  the text, so a wide/short cell or a wrapped title can no longer overflow.
- Below 1360px the two sidebars collapse into one tabbed panel (Chat,
  Bookmarks, Commits, Steam) under the sheet instead of a long stack of
  individually scrolling boxes. CSS-only: widgets stay mounted once.
- Phone: clamp song/artist to one line and give the grid a minimum
  height so album art stays visible on short screens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 15:15:10 +01:00
adamfandClaude Opus 5.5 d843b0baf1 Make the stamps wall bounce at every page size
The wall was a wrapping flex row with a fixed 4-stamp min-width, so it only
overflowed (and so only bounced) when its cell was narrower than that. At
tablet widths the cell is wider, the wall fitted, and horizontal motion
stopped.

Lay it out as a fixed-track grid whose column and row counts come from the
cell's own size via a ResizeObserver, always one to two stamps larger than
the cell on both axes, cycling the stamps to fill every slot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 15:04:04 +01:00
adamfandClaude Opus 5.5 8d7606bbe8 Retire quartz, hasura and autoheal into .deprecated/
Deploy with Docker Compose / deploy (push) Successful in 1m1s
Quartz was already replaced by silverbullet-public; its build context moves
to .deprecated/quartz. Hasura and autoheal are removed from the stack, with
their compose services (and Hasura's nginx blocks) kept verbatim under
.deprecated/ alongside a README on how to bring each back.

Removes the /hasura/ route from both nginx templates and the envsubst
allow-list, and updates the docs and comments that referred to the three
services. With autoheal gone nothing restarts an unhealthy container; the
healthchecks are now informational only, and the docs say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 14:58:17 +01:00
adamf e25fbbab96 Merge pull request 'Replace Quartz with a read-only SilverBullet for public /notes/' (#6) from silverbullet-public-notes into main
Deploy with Docker Compose / deploy (push) Successful in 29s
Reviewed-on: https://www.adam-french.co.uk/gitea/adamf/web_server/pulls/6
2026-10-01 14:47:54 +01:00
251 changed files with 25433 additions and 10285 deletions
+38
View File
@@ -0,0 +1,38 @@
# .deprecated
STATUS: nothing in here is live. No compose file, nginx template or script
references this directory. It is kept, not deleted, in line with the repo's
"legacy is kept" convention; the full history is also in git.
## quartz/
The static-site build that used to serve `/notes/`. Replaced by the read-only
`silverbullet-public` service (PR #6). Its compose service and nginx route were
removed at that point; only the build context survives here.
## hasura/
Admin-only DB console that was proxied at `/hasura/`.
- `docker-compose.hasura.yml` — the service, verbatim.
- `nginx-locations.conf` — the upstream variable and `location` blocks that
were in both `nginx.conf.template` and `nginx_dev_common.conf.template`.
To bring it back: layer the compose file
(`docker compose -f docker-compose.yml -f .deprecated/hasura/docker-compose.hasura.yml up`),
paste the nginx blocks back into both templates, re-add `${HASURA_HOST}
${HASURA_PORT}` to `ENVSUBST_VARS` in `nginx/entrypoint.sh`, and set
`HASURA_HOST`, `HASURA_PORT` and `HASURA_GRAPHQL_ADMIN_SECRET` in `.env`. Dev
mode additionally set `HASURA_GRAPHQL_ENABLE_CONSOLE` and
`HASURA_GRAPHQL_DEV_MODE` to `"true"`.
## autoheal/
Watchdog that restarted any container docker marked `unhealthy` (only `backend`
and `python` define healthchecks). It mounts the docker socket, which is
effectively root on the host. To bring it back, layer
`docker-compose.autoheal.yml` the same way as above.
Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers
labelled `autoheal=true` (nginx). This copy is the old `all` variant, kept for
reference.
@@ -0,0 +1,27 @@
# STATUS: deprecated — not part of the stack. See ../README.md for how to bring
# it back. Kept verbatim from docker-compose.yml.
services:
# Watchdog: docker itself marks a container `unhealthy` but never acts on it.
# autoheal polls the docker socket and restarts anything that goes unhealthy.
# AUTOHEAL_CONTAINER_LABEL=all means "watch every container that defines a
# healthcheck" (i.e. backend and python) rather than only labelled ones.
# It mounts the docker socket, which is effectively root on the host — that
# is the price of the feature. Because of that the image is pinned BY DIGEST,
# not by a floating tag: `:latest` meant any future push to Docker Hub would
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
# digest below is a multi-arch index (it includes linux/arm64, which is what
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
# time of pinning. To bump it: pull the new tag, `docker image inspect
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
# the digest here — never go back to a bare tag.
# Deliberately NOT on app-network: it talks only to the socket.
autoheal:
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
container_name: autoheal
restart: always
environment:
- AUTOHEAL_CONTAINER_LABEL=all
- AUTOHEAL_INTERVAL=30
- AUTOHEAL_START_PERIOD=60
volumes:
- /var/run/docker.sock:/var/run/docker.sock
@@ -0,0 +1,23 @@
# STATUS: deprecated — not part of the stack. See ../README.md for how to bring
# it back. Kept verbatim from docker-compose.yml, so it still relies on that
# file's `db` service and `app-network`, and must be layered on top of it.
services:
# Admin-only DB browser, reached at /hasura/. Console and dev mode are OFF in
# production (turned on by the dev override). It is additionally gated in
# nginx by an `auth_request` subrequest to the backend's /auth/validate-admin,
# so an admin cookie is required before the request ever reaches Hasura —
# the admin secret alone is not the only line of defence.
hasura:
image: hasura/graphql-engine:v2.44.0
container_name: "${HASURA_HOST}"
restart: always
depends_on:
- db
networks:
- app-network
environment:
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
HASURA_GRAPHQL_DEV_MODE: "false"
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
+21
View File
@@ -0,0 +1,21 @@
# STATUS: deprecated. The /hasura/ blocks removed from nginx.conf.template and
# nginx_dev_common.conf.template (identical in both). See ../README.md.
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
location /hasura {
return 301 /hasura/;
}
location /hasura/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
rewrite ^/hasura/(.*)$ /$1 break;
proxy_pass $upstream_hasura;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
+171
View File
@@ -0,0 +1,171 @@
# =============================================================================
# .env.dev — COMMITTED settings for the local dev stack. EVERY VALUE IS A DUMMY.
#
# Use it by copying it over the gitignored .env, then starting the dev stack:
# cp .env.dev .env
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
# It has to BE .env, not be passed with --env-file: several services declare
# `env_file: ./.env`, which compose reads regardless (see check-compose in the
# Makefile).
#
# Nothing here is secret and nothing here may ever be used in production: the
# passwords and signing keys only guard containers on your own machine, and
# every third-party credential is fake, so those integrations fail at the
# provider instead of reaching a real account. The background jobs that would
# act on real accounts are switched off as well.
#
# Keep it in step with .env.example: a new variable goes in both. Settings that
# are not secrets (hosts, ports, timezone) keep .env.example's defaults; values
# a service parses (Garage's hex secrets, Gitea's base64 JWT keys, the S3 key
# id) are dummies in the exact shape it requires, or that service won't start.
#
# The dummy Postgres credentials only work on a database volume created with
# them: an existing dbdata volume keeps whatever password it was initialised
# with. Only POSTGRES_DB is created on a fresh volume; the gitea, jobs and
# tracker databases and roles still have to be created by hand (.env.example).
# =============================================================================
# --- Postgres ----------------------------------------------------------------
POSTGRES_USER=dev
POSTGRES_PASSWORD=dev-postgres-password
POSTGRES_DB=site
POSTGRES_PORT=5432
POSTGRES_HOST=db
POSTGRES_JOBS_DB=jobs
POSTGRES_JOBS_USER=jobs
POSTGRES_JOBS_PASSWORD=dev-jobs-password
POSTGRES_TRACKER_DB=tracker
POSTGRES_TRACKER_USER=tracker
POSTGRES_TRACKER_PASSWORD=dev-tracker-password
# --- Gitea -------------------------------------------------------------------
# The two JWT secrets must decode as base64url of 32 bytes; these decode to
# the text "dev-only-not-a-secret-0123456789".
GITEA_HOST=gitea
GITEA_PORT=3000
GITEA_INTERNAL_TOKEN=dev-gitea-internal-token
GITEA_LFS_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk
GITEA_OAUTH2_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk
POSTGRES_GITEA_DB=gitea
# Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is not part of the compose stack; nothing in dev reads these.
GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=dev-runner
GITEA_RUNNER_REGISTRATION_TOKEN=dev-dummy-runner-token
# --- Email ingest (job tracker) -----------------------------------------------
# Sync is off; the credentials are fake, so a manual sign-in fails at Microsoft.
EMAIL_BACKEND=graph
MSGRAPH_CLIENT_ID=00000000-0000-0000-0000-000000000000
MSGRAPH_CLIENT_SECRET=dev-dummy-msgraph-secret
MSGRAPH_TENANT_ID=consumers
MSGRAPH_REDIRECT_URI=http://localhost/jobs/api/email/callback
IMAP_HOST=imap.invalid
IMAP_PORT=993
IMAP_EMAIL=[email protected]
IMAP_PASSWORD=dev-dummy-imap-password
EMAIL_SYNC_INTERVAL=
EMAIL_SYNC_ENABLED=false
# --- Job leads (job tracker) --------------------------------------------------
# The timer is off; "Check now" still works for the keyless board sources.
JOB_LEADS_ENABLED=false
JOB_LEADS_INTERVAL=
ADZUNA_APP_ID=dev-dummy-adzuna-id
ADZUNA_APP_KEY=dev-dummy-adzuna-key
REED_API_KEY=dev-dummy-reed-key
# --- SilverBullet (notes) ---------------------------------------------------
SILVERBULLET_HOST=silverbullet
SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public
SILVERBULLET_PUBLIC_PORT=3000
SILVERBULLET_GIT_INTERVAL=300
# --- Go backend --------------------------------------------------------------
# Must be at least 32 bytes or the backend refuses to start.
BACKEND_PORT=8080
BACKEND_HOST=backend
BACKEND_SECRET=dev-only-jwt-signing-secret-not-for-production
BACKEND_ENDPOINT=/api
# --- Obsidian vault ----------------------------------------------------------
# A checked-in, mostly-gitignored folder, so the bind mount always has a
# source owned by you; a missing path would be created by Docker as root and
# SilverBullet (uid 1000) could not write to it. It is not a git repository,
# so silverbullet-git logs that and idles instead of pushing anywhere.
OBSIDIAN_DIR=./dev/notes
# --- Spotify -----------------------------------------------------------------
# docker-compose.dev.yml overrides the redirect URI.
SPOTIFY_CLIENT_ID=dev-dummy-spotify-client-id
SPOTIFY_CLIENT_SECRET=dev-dummy-spotify-client-secret
SPOTIFY_REDIRECT_URI=
SPOTIFY_AUTH_STATE=dev-dummy-spotify-state
# --- Icecast / liquidsoap radio ----------------------------------------------
ICECAST_SOURCE_PASSWORD=dev-icecast-source-password
ICECAST_RELAY_PASSWORD=dev-icecast-relay-password
ICECAST_ADMIN_USER=admin
ICECAST_ADMIN_PASSWORD=dev-icecast-admin-password
ICECAST_HOST=icecast2
ICECAST_PORT=8000
ICECAST_MOUNT=/stream
LIQUIDSOAP_HARBOR_MOUNT=/live
LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ----------------------------------------------------------
# DOMAIN is also the auth cookie's domain, so it must be the host the browser
# is on. certbot is disabled in dev, so EMAIL is never used.
DOMAIN=localhost
EMAIL=[email protected]
# --- Cloudflare Tunnel -------------------------------------------------------
# cloudflared is disabled in dev and certbot with it.
CLOUDFLARE_TUNNEL_TOKEN=dev-dummy-tunnel-token
CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token
# --- Third-party API keys ----------------------------------------------------
# Fake keys: Claude calls (rowing photos, job posting reader) get a 401 from
# Anthropic, and the Steam widget gets nothing back.
CLAUDE_API_KEY=sk-ant-dev-dummy-key
CLAUDE_MODEL=
STEAM_API_KEY=DEVDUMMYSTEAMKEY
STEAM_ID=76561190000000000
# --- Development-only switch -------------------------------------------------
SEED_DB=true
# --- Python FastAPI service (/py/) -------------------------------------------
PYTHON_HOST=python
PYTHON_PORT=8000
# --- Job tracker (/jobs/) -----------------------------------------------------
JOBS_IMAGE_TAG=
# --- USACO site (/usaco/) ------------------------------------------------------
USACO_IMAGE_TAG=
USACO_GIT_TOKEN=dev-dummy-gitea-token
USACO_WEBHOOK_SECRET=dev-dummy-webhook-secret
# --- Activity tracker (/tracker/) --------------------------------------------
ACTIVITY_TRACKER_IMAGE_TAG=
TRACKER_TZ=Europe/London
TFL_APP_KEY=dev-dummy-tfl-key
# --- Garage object store (public /uploads/) -----------------------------------
# Shapes Garage enforces: 64 hex for the RPC secret, "GK" + 24 hex for the key
# id, 64 hex for the secret. Uploads fall back to the `uploads` volume until
# garage/bootstrap.sh has imported this key and created the bucket.
GARAGE_RPC_SECRET=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
GARAGE_ADMIN_TOKEN=dev-garage-admin-token
S3_ACCESS_KEY_ID=GK0123456789abcdef01234567
S3_SECRET_ACCESS_KEY=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210
S3_ENDPOINT=http://garage:3900
S3_REGION=garage
S3_BUCKET=uploads
GARAGE_CAPACITY=1G
+168 -22
View File
@@ -5,18 +5,25 @@
# 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.
# names and published ports are built.
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
# variables inside that container. nginx, backend, db, icecast2,
# 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.
# The `python` and `jobs` services deliberately do neither wholesale — each
# uses an explicit `environment:` allow-list, so neither sees the site's
# database password, the JWT secret, or any key it does not use.
#
# 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).
# On the host, edit .env in place. After changing a value, recreate the
# services that read it:
# docker compose up -d <service>.
#
# ADDING A VARIABLE
# Add it to .env.dev as well, with a dummy value, so the dev stack keeps
# starting. If the python or jobs service reads it, add it to that service's
# `environment:` list in docker-compose.yml too, or the container never
# receives it.
#
# 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,
@@ -27,15 +34,24 @@
# =============================================================================
# --- 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.
# One instance, four databases: POSTGRES_DB for the Go backend,
# POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker and
# POSTGRES_TRACKER_DB for the activity tracker (each of the last two with its
# own role). Only POSTGRES_DB is auto-created on first init; the others must
# be created by hand on a fresh volume (the job-tracker and ccp READMEs have
# the commands).
# POSTGRES_HOST doubles as the db container's name.
POSTGRES_USER=
POSTGRES_PASSWORD=
POSTGRES_DB=
POSTGRES_PORT=5432
POSTGRES_HOST=db
POSTGRES_JOBS_DB=jobs
POSTGRES_JOBS_USER=jobs
POSTGRES_JOBS_PASSWORD=
POSTGRES_TRACKER_DB=tracker
POSTGRES_TRACKER_USER=tracker
POSTGRES_TRACKER_PASSWORD=
# --- Gitea -------------------------------------------------------------------
# GITEA_HOST is the container name AND the nginx upstream host.
@@ -48,6 +64,10 @@ GITEA_INTERNAL_TOKEN=
GITEA_LFS_JWT_SECRET=
GITEA_OAUTH2_JWT_SECRET=
POSTGRES_GITEA_DB=gitea
# The host's Tailscale MagicDNS name (e.g. stpvm.tailf20278.ts.net), shown in
# Gitea's SSH clone URLs. Not the public domain: 2222 is reachable only over
# the tailnet. Becomes Gitea's SSH_DOMAIN and DOMAIN. Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
@@ -58,7 +78,7 @@ GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=pi-runner
GITEA_RUNNER_REGISTRATION_TOKEN=
# --- Email ingest (backend) --------------------------------------------------
# --- Email ingest (job tracker) -----------------------------------------------
# EMAIL_BACKEND selects the mail source: "graph" (Microsoft Graph API, OAuth)
# or "imap" (fallback; Microsoft has retired IMAP basic auth for outlook.com,
# so imap+app-password only works with non-Microsoft providers like Gmail).
@@ -67,11 +87,12 @@ GITEA_RUNNER_REGISTRATION_TOKEN=
# (default tenant = "consumers"); add a delegated Mail.Read permission with
# admin/user consent, and create a client secret. Redirect URI type "Web",
# value must live behind the site's real HTTPS origin, e.g.
# https://<YOUR_DOMAIN>/email/callback (callback route already exists in the
# backend). Backend code exchanges a code there. TenantID must be "consumers"
# for a personal outlook.com account.
# The first sync prints an authorisation URL into the container log; visit it,
# consent, and the refresh token is persisted to backend/token/msgraph_token.json.
# https://<YOUR_DOMAIN>/jobs/api/email/callback (served by the job tracker,
# which exchanges the code there). TenantID must be "consumers" for a personal
# outlook.com account.
# The tracker's Settings page (/jobs/settings) shows the authorisation link
# until you sign in; the refresh token is persisted to
# jobs-data/msgraph_token.json.
# OAuth flow reference: https://learn.microsoft.com/en-us/graph/auth-v2-user
EMAIL_BACKEND=
MSGRAPH_CLIENT_ID=
@@ -87,6 +108,23 @@ IMAP_PASSWORD=
EMAIL_SYNC_INTERVAL=
EMAIL_SYNC_ENABLED=
# --- Job leads (job tracker) --------------------------------------------------
# The lead fetcher polls the sources listed on /jobs/leads and files new
# postings in the leads inbox. JOB_LEADS_ENABLED=true runs it on a timer;
# "Check now" on that page works whether or not it is set. JOB_LEADS_INTERVAL
# is a Go duration (default 6h). Scoring uses CLAUDE_API_KEY, above.
# The board sources (Greenhouse, Lever, Ashby) need no key. The two search
# sources do, both free:
# Adzuna: https://developer.adzuna.com/ (an application id and a key)
# Reed: https://www.reed.co.uk/developers/jobseeker
# A search source whose key is blank reports that on the page; nothing else
# is affected.
JOB_LEADS_ENABLED=
JOB_LEADS_INTERVAL=
ADZUNA_APP_ID=
ADZUNA_APP_KEY=
REED_API_KEY=
# --- Services that nginx substitutes but no longer runs -----------------------
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
# compose service uses them today. Harmless if blank.
@@ -153,18 +191,32 @@ LIQUIDSOAP_HARBOR_PORT=8001
DOMAIN=
EMAIL=
# --- Cloudflare Tunnel -------------------------------------------------------
# Token of the remotely managed tunnel the `cloudflared` container runs
# (Zero Trust -> Networks -> Tunnels -> your tunnel -> the `--token` value in
# the install command). Hostnames and origin settings are configured in the
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
# the container restarting with an error and the site reachable directly.
CLOUDFLARE_TUNNEL_TOKEN=
# Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API
# Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the
# certificate renews without any inbound port, so the router's 80/443
# forwards can close. Blank falls back to HTTP-01 on port 80.
CLOUDFLARE_DNS_API_TOKEN=
# --- Third-party API keys (backend) ------------------------------------------
# CLAUDE_API_KEY is used by the python service, which makes the main site's
# Claude calls: the rowing photo reader, the job posting reader and the email
# pipeline's classifier. The backend no longer calls Claude itself. The jobs
# and usaco containers get the same key for their own calls.
CLAUDE_API_KEY=
# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5
# (the default when blank) or claude-opus-5-5. Recreate the python service
# to apply a change.
CLAUDE_MODEL=
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.
@@ -174,5 +226,99 @@ SEED_DB=
PYTHON_HOST=python
PYTHON_PORT=8000
# --- Job tracker (/jobs/) -----------------------------------------------------
# An image built and published by the job-tracker repo's CI. Blank runs
# :latest; set a commit sha to pin. Changing it needs
# `docker compose pull jobs && docker compose up -d jobs`.
JOBS_IMAGE_TAG=
# --- USACO site (/usaco/) ------------------------------------------------------
# An image built and published by the usaco repo's CI. Blank runs :latest; set
# a commit sha to pin. Changing it needs
# `docker compose pull usaco && docker compose up -d usaco`.
USACO_IMAGE_TAG=
# The same for its code runner (usaco-runner), which the usaco repo's CI
# publishes and rolls alongside it. It takes no other settings: it has no
# secrets by design.
USACO_RUNNER_IMAGE_TAG=
# Gitea access token (repository: read and write on adamf/usaco). The site
# clones with it and pushes the admin's edits back.
USACO_GIT_TOKEN=
# Shared secret of the usaco repo's push webhook in Gitea
# (http://usaco:8080/usaco/api/hooks/gitea). Blank turns the hook off and
# the site only pulls every 10 minutes. Generate with `openssl rand -hex 32`.
USACO_WEBHOOK_SECRET=
# Model for the problem explanations (the admin's Explain button), separate
# from CLAUDE_MODEL because those are long, considered answers rather than
# extraction. Blank means claude-opus-5-5. The key is CLAUDE_API_KEY above;
# without it the button is off and the rest of the site works.
USACO_CLAUDE_MODEL=
# Monthly cap on the USACO site's estimated Claude spend, in dollars (e.g.
# 20). Once a calendar month (UTC) reaches it, new Explain/review/concept/
# evaluate jobs are refused until the 1st. Blank: no cap; the spend is still
# shown on the site's stats page to the admin.
USACO_CLAUDE_MONTHLY_BUDGET=
# Recording reviews (the admin uploads themselves explaining a solution).
# Claude cannot take audio, so this OpenAI key transcribes it (whisper-1,
# about $0.006 a minute). Blank turns reviews off.
USACO_OPENAI_API_KEY=
# Optional: keep the recordings for playback in a PRIVATE Garage bucket,
# never `uploads` (that one is served publicly at /uploads/). Its own key,
# same shapes as S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY above. With the
# key blank the recordings are thrown away once transcribed. One-off setup:
# docker compose exec -T garage /garage bucket create usaco-audio
# docker compose exec -T garage /garage key import -n usaco-site --yes "$USACO_S3_ACCESS_KEY_ID" "$USACO_S3_SECRET_ACCESS_KEY"
# docker compose exec -T garage /garage bucket allow --read --write usaco-audio --key "$USACO_S3_ACCESS_KEY_ID"
USACO_S3_ACCESS_KEY_ID=
USACO_S3_SECRET_ACCESS_KEY=
# --- Activity tracker (/tracker/) --------------------------------------------
# An image built and published by the ccp repo's CI. Blank runs :latest; set a
# commit sha to pin. Changing it needs
# `docker compose pull activity-tracker && docker compose up -d activity-tracker`.
ACTIVITY_TRACKER_IMAGE_TAG=
# IANA timezone that decides where a "day" starts in daily summaries. Blank is UTC.
TRACKER_TZ=Europe/London
# --- Receipt printer (/receipt/) ---------------------------------------------
# Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi,
# which reaches the printer over the home LAN, and nginx proxies to it over
# Tailscale.
# host:port of that server, by Tailscale IP. Blank points nowhere and
# /receipt/ answers "offline".
RECEIPT_WEB_UPSTREAM=100.107.152.119:8765
# Shared secret nginx adds as X-Receipt-Token; the same value as
# RECEIPT_WEB_TOKEN in stppi's ~/.config/receipt-web.env. Generate with
# `openssl rand -hex 32`. Changing it needs `docker compose up -d nginx`.
RECEIPT_WEB_TOKEN=
# TfL Unified API key (500 req/min); used by the Python hotel finder
TFL_APP_KEY=
# --- Garage object store (public /uploads/) -----------------------------------
# See garage/garage.toml and DEPLOYMENT.md ("Garage"). Everything here is
# optional for the site to run: with S3_ENDPOINT blank the backend keeps
# writing uploads to the `uploads` volume exactly as before.
#
# Garage's own secrets, passed to the garage and garage-webui containers.
# Generate each with `openssl rand -hex 32`. The RPC secret must never change
# once the node has data; the admin token unlocks garage-webui's whole API.
GARAGE_RPC_SECRET=
GARAGE_ADMIN_TOKEN=
# The backend's S3 access, imported into Garage by garage/bootstrap.sh.
# Garage only accepts this shape:
# S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12))
# S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32)
S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY=
# Blank keeps uploads on disk. Set to http://garage:3900 (after running
# garage/bootstrap.sh) to store new public uploads in the bucket; recreate the
# backend after changing it. If a write to Garage fails the backend logs it and
# writes to disk instead, and nginx serves the file from there.
S3_ENDPOINT=
# Optional; these defaults match garage.toml and bootstrap.sh.
S3_REGION=garage
S3_BUCKET=uploads
# Optional, bootstrap.sh only: the node's capacity in the layout. With one node
# it only has to be non-zero; it is not a quota. Default 20G.
GARAGE_CAPACITY=
+153 -4
View File
@@ -1,28 +1,177 @@
name: Deploy with Docker Compose
# =============================================================================
# deploy.yaml — test every push; deploy pushes to main that pass.
#
# TWO JOBS
# test runs on every push, to any branch: `go vet` + `go test` for the
# backend and pytest for the Python service. These are the same
# checks as `make check-backend` and `make check-python`.
# deploy runs only for refs/heads/main, and only if `test` passed
# (`needs: test`). Before this gate existed every push to main went
# straight to the live site.
#
# WHERE THIS RUNS, AND WHAT THAT RULES OUT
# A self-hosted act_runner on the Pi itself, in HOST mode (see
# gitea-runner/run.sh): steps are shell commands on the Pi, not in a job
# container. So:
# - No host toolchains are assumed. The Pi is known to have git and docker
# and nothing else; Go and Python run inside `docker run` containers
# pinned to the same base images as backend/Dockerfile (golang:1.26) and
# python/Dockerfile (python:3.12-slim). Bump them together.
# - No `actions/checkout`. It is a JavaScript action and would need Node on
# the host. The source is fetched with plain git instead, from the same
# local Gitea SSH remote the deploy step has always used.
#
# THE LIVE DIRECTORY IS NOT TOUCHED UNTIL TESTS PASS
# The site runs out of /home/adamf/deploy/web_server. The test job never
# goes near it: it fetches into a separate bare cache repo and exports the
# pushed commit to a scratch directory. Only the deploy job, after `test`
# is green, does the `git reset --hard` there.
#
# NOT TESTED HERE: THE VUE BUILD
# Deliberately skipped. `docker compose up --build` in the deploy job
# already runs the full frontend build (npm ci + vite) while building the
# vue image, and a failed image build aborts `up` BEFORE any container is
# replaced, so the old site keeps serving. Building it a second time here
# would cost the Pi several minutes per push to learn nothing new. The same
# reasoning does not hold for Go and Python: their images build fine with
# failing tests, which is exactly why those are gated here.
#
# NO pull_request TRIGGER
# `push` with no branch filter already covers every branch, including the
# head branch of any PR in this repo, so adding pull_request would run the
# suite twice per push on a machine with little CPU to spare.
# =============================================================================
name: Test and deploy
on:
push:
branches: [main]
jobs:
test:
runs-on: self-hosted
env:
# The commit and ref this push delivered. Passed through env rather
# than interpolated into the scripts so a branch name can never be
# parsed as shell.
SHA: ${{ github.sha }}
REF: ${{ github.ref }}
REMOTE: ssh://git@localhost:2222/adamf/web_server.git
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
# Bare repo kept between runs so each fetch is incremental (the
# history is ~140MB; a fresh clone per push would be slow on the
# Pi's SD card). Lives outside the deploy directory on purpose.
CACHE: /home/adamf/.cache/web_server-ci/repo.git
# This run's source tree, exported from the cache and removed in
# the last step. Keyed by commit so two runs cannot share a tree.
SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }}
steps:
- name: Export the pushed commit to a scratch directory
shell: bash
run: |
set -eu
mkdir -p "$(dirname "$CACHE")"
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
# Fetch the pushed ref, then export the exact pushed commit.
# Using $SHA rather than FETCH_HEAD means that if the branch
# has moved on since this run was queued we still test the
# commit this run is about, not a newer one.
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
rm -rf "$SRC"
mkdir -p "$SRC"
# `git archive` gives a clean tree of tracked files only: no
# .git, and nothing left over from an earlier run.
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
# Do not rely on the shell having pipefail: if the archive
# half failed, make sure that is noticed here.
test -f "$SRC/backend/go.mod"
test -f "$SRC/python/requirements-dev.txt"
echo "Exported $SHA ($REF) to $SRC"
# The whole repo is mounted read-only. Tests write only to
# t.TempDir(), and a read-only mount means the container (root)
# cannot leave root-owned files in $SRC that the clean-up step,
# running as the runner user, could not delete.
#
# The two named volumes are the Go module cache and build cache.
# Without them every run would re-download every dependency and
# recompile gorm, gin and gqlgen from scratch — minutes on a Pi.
# They survive `docker image prune` and the weekly maintenance
# job; `docker volume rm web_server_ci_gomod web_server_ci_gobuild`
# resets them if they ever go bad.
- name: Backend - go vet and go test
shell: bash
run: |
set -eu
docker run --rm \
-v "$SRC":/src:ro \
-w /src/backend \
-v web_server_ci_gomod:/go/pkg/mod \
-v web_server_ci_gobuild:/root/.cache/go-build \
golang:1.26 \
sh -c 'go vet ./... && go test ./...'
# requirements-dev.txt pulls in requirements.txt plus pytest. The
# install is repeated every run (the container is thrown away) but
# the pip cache volume means it is unpacking cached wheels, not
# downloading. Read-only source for the same reason as above, so
# bytecode and the pytest cache are switched off rather than left
# to fail noisily.
- name: Python - pytest
shell: bash
run: |
set -eu
docker run --rm \
-v "$SRC":/src:ro \
-w /src/python \
-v web_server_ci_pip:/root/.cache/pip \
-e PYTHONDONTWRITEBYTECODE=1 \
python:3.12-slim \
sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider'
# always(): a failed test must not leave a source tree behind per
# push. The cache repo is kept; only this run's export goes.
- name: Remove the scratch directory
if: always()
shell: bash
run: rm -rf "$SRC"
deploy:
# Both conditions matter: `needs` makes a red test job skip this one,
# and the `if` keeps pushes to other branches from deploying at all.
needs: test
if: github.ref == 'refs/heads/main'
runs-on: self-hosted
steps:
- name: Pull changes
working-directory: /home/adamf/deploy/web_server
env:
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
SHA: ${{ github.sha }}
shell: bash
run: |
set -eu
git config --global --add safe.directory /home/adamf/deploy/web_server
git fetch ssh://git@localhost:2222/adamf/web_server.git main
# Deploy only the commit the test job just passed. If main
# has moved on since this run started, FETCH_HEAD is a newer
# commit that THIS run never tested — stop, and let that
# commit's own run test and deploy it. Failing (rather than
# resetting to $SHA anyway) also means re-running an old run
# can never roll the site back to an old commit.
if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then
echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA."
echo "Not deploying: the run for the newer commit will."
exit 1
fi
git reset --hard FETCH_HEAD
- name: Run docker compose up
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
COMPOSE_BAKE: "false"
run: docker compose up -d --build --remove-orphans
# The lock is shared with maintenance.yaml, so a deploy and the
# weekly rebuild cannot run compose at the same time.
run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker resources
run: docker image prune -f
+15 -7
View File
@@ -2,7 +2,10 @@ name: Weekly Maintenance
on:
schedule:
- cron: "0 1 * * 0"
# 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and
# every container, so it runs when nobody is likely to be mid-edit;
# 01:00 kept catching late-night SilverBullet saves.
- cron: "0 5 * * 0"
workflow_dispatch:
jobs:
@@ -21,17 +24,22 @@ jobs:
- name: Autoremove obsolete packages
run: sudo apt-get -y autoremove --purge
# Both compose steps below take .compose.lock, the same flock
# deploy.yaml holds while it runs compose. Without it this weekly
# job could recreate containers while a deploy is mid-build, and
# two `compose up`s racing over the same project can each recreate
# a container the other just started. flock blocks until the other
# holder finishes, so the job waits rather than fails. The lock is
# taken per step, not across both: nothing needs pull and up to be
# atomic, and holding it for less time keeps a deploy from waiting
# behind a long pull.
- name: Pull latest base images
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
run: docker compose pull
run: flock .compose.lock docker compose pull
- name: Rebuild and restart containers
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
run: docker compose up -d --build --remove-orphans
run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker images
run: docker image prune -af
+71
View File
@@ -0,0 +1,71 @@
# =============================================================================
# renovate.yaml — weekly dependency-update PRs, opened against this repo.
#
# Renovate stands in for Dependabot, which does not exist outside GitHub. What
# it updates is configured in /renovate.json5; this file is only how it runs.
#
# HOW IT RUNS
# The same host-mode act_runner as deploy.yaml, so (as there) nothing but
# git and docker is assumed on the host: Renovate runs from its own image.
# --network host lets the container reach Gitea on localhost:3000, the port
# the runner itself registers against, so this keeps working while nginx or
# the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same reason:
# without it Renovate clones from the URL Gitea advertises, which is
# ROOT_URL — the public https://…/gitea/ path.
#
# WHAT HAPPENS AFTER
# Each update is pushed as a renovate/* branch, which triggers deploy.yaml's
# `test` job like any other push (and never its `deploy` job, which is
# main-only). Nothing is merged automatically: merging is deploying.
# Renovate also keeps a "Dependency Dashboard" issue open listing everything
# pending; ticking a box there is picked up on the next run, so run this
# workflow by hand (workflow_dispatch) to act on it sooner.
#
# THE TOKEN
# RENOVATE_TOKEN is a repo Actions secret: a Gitea access token for the
# account the PRs come from (a dedicated `renovate` user with write access
# to this repo, ideally), scopes read:user, read:organization,
# write:repository, write:issue.
# RENOVATE_GITHUB_COM_TOKEN is optional: any github.com token with no
# scopes. Without it Renovate is rate-limited by GitHub and leaves release
# notes out of the PRs. (Gitea refuses secret names starting GITHUB_, hence
# the prefix.) Both reach the container as `-e NAME` with no value, so they
# are copied from this step's env and never appear in the process list.
#
# The renovate/renovate:44 tag floats within the major (--pull always picks
# up the newest 44.x each week); Renovate itself proposes the next major via
# the regex manager in renovate.json5.
# =============================================================================
name: Renovate
on:
schedule:
# 04:00 UTC Monday: clear of the Sunday 05:00 maintenance rebuild, and
# done before the working week so the PRs are waiting.
- cron: "0 4 * * 1"
workflow_dispatch:
jobs:
renovate:
runs-on: self-hosted
steps:
- name: Run Renovate
shell: bash
env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
GITHUB_COM_TOKEN: ${{ secrets.RENOVATE_GITHUB_COM_TOKEN }}
run: |
set -eu
if [ -z "$RENOVATE_TOKEN" ]; then
echo "The RENOVATE_TOKEN Actions secret is not set (repo Settings -> Actions -> Secrets)."
exit 1
fi
docker run --rm --pull always --network host \
-e RENOVATE_PLATFORM=gitea \
-e RENOVATE_ENDPOINT=http://localhost:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/web_server \
-e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \
renovate/renovate:44
+14 -6
View File
@@ -1,9 +1,16 @@
icecast2/fallback_music/*
.claude/
!icecast2/fallback_music/.gitkeep
certbot/conf
certbot/www
backend/token/
jobs-data/
usaco-data/
.env
.env.bak
# flock taken by the deploy and maintenance workflows around docker compose
.compose.lock
gitea/data/*
gitea/config/app.ini
@@ -13,15 +20,13 @@ gitea-runner/.runner
gitea-runner/act_runner
gitea-runner/nohup.out
# Rust build artifacts
**/target/
# Python bytecode
__pycache__/
*.pyc
.pytest_cache/
# Generated WASM output
vue/src/wasm/
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
/.venv/
# Logs
logs
@@ -64,7 +69,6 @@ __screenshots__/
.deploy
*.xcf
sync-secrets.sh
# Local-only outstanding-work notes, deliberately not published
TODO-NEXT.md
@@ -72,3 +76,7 @@ TODO-NEXT.md
# SilverBullet git deploy key (key material only; the README stays)
silverbullet/ssh/*
!silverbullet/ssh/README.md
# Dev notes vault (OBSIDIAN_DIR in .env.dev); only the README is tracked
dev/notes/*
!dev/notes/README.md
.gstack/
+35 -14
View File
@@ -4,13 +4,22 @@ 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. 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
```
Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
### Full stack (production, HTTPS)
@@ -24,7 +33,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 +41,8 @@ Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`
cd vue && npm run build
```
`npm run build` is a plain `vite build`.
### Regenerate GraphQL (after editing schema files)
```
@@ -42,44 +53,54 @@ This regenerates `graph/generated.go` and `graph/model/models_gen.go`. Resolver
## Architecture
Dockerized multi-service personal website self-hosted on a Raspberry Pi.
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 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`.
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
**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).
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public.
## Backend Structure
- `main.go` — entry point: wires up DB, services, router
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, ClaudeClient, Auth, etc. Passed to all handlers
- `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)
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, Claude client, DB seeding
- `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/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines)
- `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 `Page`s (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. 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`.
- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. nginx's *permission gate* (`set $auth_permission <key>; auth_request /internal/auth/validate;`, see `nginx/nginx_routes.conf.template`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its location from the admin gate to the permission gate. `/auth/validate-admin` and the admin gate are unchanged.
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
- **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor.
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
- **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.
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
## Further documentation
@@ -96,4 +117,4 @@ Each area has its own README with the detail that doesn't belong here:
- **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`.
- **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.
+397 -103
View File
@@ -4,15 +4,19 @@ 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
Everything runs on a single host, `stpvm` (an x86-64 Ubuntu VM on Proxmox,
reached over Tailscale as `stpvm.tailf20278.ts.net`; until 2026-10-15 it was
the Raspberry Pi `stppi`), 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.
Only three things are reachable from outside the host: nginx on 80/443, Gitea on
3000/2222, and the liquidsoap harbor port. Everything else is internal. Web
traffic can also come in through the Cloudflare tunnel (`cloudflared`), which
dials out and publishes no port; see "Cloudflare Tunnel" in §3.
```
internet
@@ -29,13 +33,13 @@ Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
--------------------------------------------- | (same container
| | | | | | | as icecast2)
v v v v v v | |
/api/ /radio/ /gitea/ /hasura/ /notes/ /py/ | |
backend icecast2 gitea hasura sb-pub python | |
| ^ | | |
| | | | |
| +------------------|--------------------|---------------+
| | |
+----------+-----------------+--------------------+
/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | |
backend icecast2 gitea sb sb-pub python | |
| ^ | |
| | | |
| +---------------------------------------|---------------+
| |
+----------+--------------------------------------+
v
+------+
| db | postgres:16
@@ -43,26 +47,32 @@ backend icecast2 gitea hasura sb-pub python | |
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 |
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
| silverbullet-git | n/a | n/a | none (timer loop) | 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 |
| 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 |
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
| silverbullet-git | n/a | n/a | none (timer loop) | no |
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by nginx `auth_request`; capture API and userscript public, bearer-token) | no |
| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by nginx `auth_request`; `/api/v1/` bearer/app-checked) | 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 |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no |
| receipt printer (`receipt serve`, adamf/receipt_maker) | — (runs on **stppi**, not in this stack) | 8765 on stppi's Tailscale IP (`RECEIPT_WEB_UPSTREAM`) | `/receipt/`, prefix stripped (permission-gated on `receipt` by nginx `auth_request`; nginx adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy nginx) | `autoheal` | — (no network) | none; reads the Docker socket | no |
| garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no |
| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by nginx `auth_request`) | 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
@@ -80,19 +90,33 @@ in one step — never change one without the other.**
- **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/`, `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
SPA login. None of these services has any auth of its own at that path.
- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
branch views stay public) are
protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure
redirects to the SPA login. Most of these services have no auth of their own at that path; the
job and activity trackers also check the session themselves. Their carve-outs, which a session
cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps:
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`.
- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead, which also lets in a
non-admin account granted `receipt` in the admin panel's Manage Users tab. Not signed in
redirects to the login; signed in without the grant redirects to `/no-access`. To let a
friend print: create their user (admin panel → User), then tick "Receipt printer" for them
under Manage Users. Revoking is the same tick, and applies on their next request.
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of
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
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`.
- **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.
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: the bucket first, then disk.** `/uploads/<f>` is fetched from
Garage's website endpoint and, if Garage has no such file or is down, from
the shared `uploads` volume (`@uploads_disk`). Both paths add `nosniff`,
`Content-Disposition: inline` and a deny-all CSP, so user-supplied files
cannot execute anything on our origin. The bucket is the source of truth;
a Garage outage only affects files that exist nowhere else. See "Garage"
in §7.
- **Rate limits** — see §6.
---
@@ -107,39 +131,67 @@ 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.
- 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.
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 host 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
`.compose.lock` flock, shared with the weekly maintenance workflow.
The test job keeps state on the host outside the deploy checkout: a bare
repository cache at `/home/adamf/.cache/web_server-ci/` and three named
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
```
cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
`.env.dev` is committed and holds only dummy values, so the stack starts
without any real credential and cannot reach a real account. Features that
need one fail at the provider, which is the point. It must become `.env`
rather than be passed with `--env-file`, because several services read
`env_file: ./.env` directly. Its Postgres passwords only match a `dbdata`
volume created with them, and as in production only `POSTGRES_DB` is created
automatically.
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.
for hot reload, with an anonymous-volume mask on `/app/node_modules` so the
image's installed deps are not hidden by the bind mount. You don't need
`node_modules` 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.
@@ -148,7 +200,7 @@ 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.
set on the host — 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.
@@ -161,8 +213,7 @@ Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
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.
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
@@ -172,7 +223,7 @@ 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.`
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).
@@ -187,6 +238,13 @@ 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.
**Validation method.** With `CLOUDFLARE_DNS_API_TOKEN` set, certbot proves
control of the domain by creating a `_acme-challenge` TXT record through the
Cloudflare API (DNS-01), so renewal needs no inbound port at all. That is
what lets the router's 80/443 forwards close behind the tunnel. Without the
token it uses the webroot (HTTP-01) on port 80, as it always did. Switching
either way takes effect at the next renewal; see `certbot/entrypoint.sh`.
**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
@@ -194,6 +252,104 @@ 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.
### Cloudflare Tunnel
The `cloudflared` container holds an outbound connection to Cloudflare and
forwards requests for the site's hostnames down it to nginx. It is a
_remotely managed_ tunnel: the only thing in this repo is the token
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
origin settings live in the dashboard.
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
terminates the visitor's TLS at its edge, and cloudflared opens a second TLS
connection to nginx. That is deliberate. Pointed at `http://nginx:80`, the
tunnel would hit the HTTP→HTTPS redirect and loop. Going to :443 keeps every
redirect, security header and the `X-Forwarded-Proto: https` the backend's
Secure cookies depend on, and needs no nginx change.
The origin is the public name, not `nginx`, because nginx carries `<DOMAIN>`
and `www.<DOMAIN>` as network aliases on `app-network` (`docker-compose.yml`).
Inside the network those names resolve to the nginx container, so the hop
never leaves the host, and cloudflared verifies the Let's Encrypt certificate
against a name it covers. `https://nginx` would fail that check and need No
TLS Verify. The flip side: **an expired certificate now takes the tunnel down
with a 502**, which is why renewal over DNS-01 (step 5) matters.
An alias only exists while nginx is running, so cloudflared also pins both
names to nginx's fixed address (`172.28.255.251`) with `extra_hosts`. Without
that, while nginx is stopped for a deploy or the weekly maintenance, the name
falls through to public DNS, resolves to Cloudflare itself, and visitors see
Cloudflare error 1000 instead of a 502.
The aliases have a side effect for anything else on `app-network` that uses
the public name for a port nginx does not serve. `silverbullet-git` pushes to
Gitea's SSH on `<DOMAIN>:2222`, so it maps `<DOMAIN>` to the host gateway
instead, where Gitea publishes that port.
Setup, once:
1. Cloudflare dashboard → the domain must be on Cloudflare DNS.
2. Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy the
token from the install command (the long string after `--token`).
3. Put it in `.env` as `CLOUDFLARE_TUNNEL_TOKEN`, then
`docker compose up -d cloudflared`. The tunnel
shows as Healthy in the dashboard.
4. Add a public hostname per name, each with service `HTTPS` and its own
name as the URL, and no other settings:
- `www.<DOMAIN>` → `https://www.<DOMAIN>`: the site.
- `<DOMAIN>` → `https://<DOMAIN>`: nginx redirects it to www, and it serves Gitea's registry
at `/v2/`.
Creating each hostname replaces the existing A record for that name with
a CNAME to the tunnel. **That is the cutover**: until then the tunnel
carries nothing.
5. Create a Cloudflare API token (My Profile → API Tokens → "Edit zone
DNS", this zone only) and set it as `CLOUDFLARE_DNS_API_TOKEN`. certbot
then renews over DNS-01 (see Renewal above) and needs no inbound port.
6. On the host, point the apex at nginx locally (next section).
7. Close the router's 80 and 443 forwards. Once 5 and 6 are done nothing
depends on them.
#### What the tunnel does not carry, and where it goes instead
- **Certificate renewal.** Over DNS-01 with `CLOUDFLARE_DNS_API_TOKEN` set;
without it certbot falls back to HTTP-01, which needs port 80 forwarded.
The certificate matters behind the tunnel: cloudflared verifies it, as
do the registry path below and any direct LAN access. A fresh machine with no
certificate at all boots the setup config (§3), which serves nothing over
443, so the tunnel carries nothing until the first issuance.
- **Registry pushes and pulls on the host.** Cloudflare caps request bodies at
100 MB on the free plan, so a push of a larger image layer through the
tunnel fails. The runner on the host pushes to `<DOMAIN>/adamf/...` and the
stack pulls from it, both through the host's Docker daemon, which resolves
names through the host's `/etc/hosts`. Pin the apex there to the loopback:
```
127.0.0.1 <DOMAIN>
```
so registry traffic goes straight to nginx on :443, with the real
certificate, and never leaves the host. (Without it the name resolves to
Cloudflare once DNS moves there.) Only the apex: www stays on Cloudflare for anything on the host
that wants the public site. Pushing from another machine still goes
through Cloudflare and its cap; use the host's Tailscale name for that.
- **Gitea SSH (2222).** Not HTTP, so not tunnelled. Already Tailscale-only:
`GITEA_SSH_DOMAIN` in `.env` (Gitea's `SSH_DOMAIN`) is the host's MagicDNS name
and 2222 has never been forwarded. Nothing changes.
- **The radio harbor (8001).** Also a raw source protocol, so a DJ client
pointed at `<DOMAIN>:8001` stops connecting once the domain resolves to
Cloudflare. Point it at the host's Tailscale name
(`stpvm.tailf20278.ts.net:8001`) and close the 8001 forward. A guest DJ
off the tailnet would need either a Tailscale share of the host or a
Cloudflare TCP route used with `cloudflared access tcp` on their side.
#### Other limits
- Cloudflare returns a 524 if the origin sends no response bytes for 100
seconds. Streaming endpoints are fine while they keep writing; a long
silent request is not.
- Dev never runs cloudflared (`disabled` profile in `docker-compose.dev.yml`),
so a laptop cannot join the production tunnel.
---
## 4. What persists across restarts
@@ -201,25 +357,28 @@ cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
**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 |
| Volume | Holds | Losing it means |
| ---------- | ----------------------------------------------------- | -------------------------------------------------- |
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
| `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files |
| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) |
| `garage_data` | The bucket's object bytes | Every upload stored in Garage |
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
**Bind mounts** — live in the repo checkout on the Pi, survive everything short
**Bind mounts** — live in the repo checkout on the host, 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 (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
| 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. |
| `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") |
| `./icecast2/fallback_music` | Radio fallback MP3s | Copied to the host by hand, not git |
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
**Ephemeral:** anything else inside a container. Notably the Vue build, the
rendered nginx/icecast configs, and the Gitea runner's downloaded binary
@@ -235,24 +394,36 @@ All configuration lives in **`./.env`** at the repo root, which is gitignored.
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.
time. Builds container names and published ports.
- **`env_file: ./.env`** — injects the whole file into the container. Used by
nginx, backend, db, icecast2, 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.
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`, plus `CLAUDE_MODEL`,
which picks the model). The Python service
makes the site's one Claude call (the rowing photo reader); the `jobs` container
(the job tracker, built from its own repo) makes its own, and gets a similar
allow-list with its own database role. The backend receives `CLAUDE_API_KEY`
through `env_file` but does not use it. A new variable for either service has
to be added to its allow-list as well as
`.env.example`.
**`.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.
**`.env` is edited by hand on the host**, in
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's
`.env` (often with dev values) never reaches production by accident.
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
which for a password field means _no password_. After editing `.env`, confirm
with `docker compose config`.
### Changing a value on the host
Edit `.env` on the host, and recreate only the services that read the variable:
`docker compose up -d <service>`. A plain `up -d` would also restart Postgres,
since nginx, db, icecast2 and certbot load the whole file.
---
## 6. Rate limits
@@ -265,29 +436,32 @@ 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**.
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. |
| 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` | 30/min | 20 | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
| `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.**
These zones key on `$remote_addr`. For tunnel traffic nginx rewrites that
from Cloudflare's `CF-Connecting-IP` header (`set_real_ip_from` /
`real_ip_header` in `nginx.conf.template`), trusting the header only from
cloudflared's fixed address. **If that address changes in
`docker-compose.yml` without the nginx line, every tunnel visitor shares
cloudflared's one bucket**, and the login limit locks everyone out together.
---
## 7. Runbook
All commands run from the deploy checkout on the Pi
All commands run from the deploy checkout on the host
(`~/deploy/web_server`) unless stated.
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
@@ -333,6 +507,40 @@ docker compose ps # note: `vue` Exited(0) is correct
docker compose logs certbot # issuance / renewal outcomes
```
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
login required).
**Incoming request bodies.** nginx writes one JSON line per request, body
included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The
`traffic` container tails it, so in Dozzle pick **traffic** and each request
renders as fields you can search. From a shell:
```
tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")'
jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log
```
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
(that covers every login and the refresh call). Bodies over 64 KB, i.e.
uploads, are logged with an empty `body`, and responses are never logged.
The file is never rotated by the stack. On the host, add
`/etc/logrotate.d/web_server`:
```
/home/adamf/deploy/web_server/logs/nginx/*.log {
weekly
rotate 4
compress
missingok
notifempty
copytruncate
}
```
`copytruncate` because nginx keeps the file open; `tail -F` in `traffic`
follows the truncation.
**Reset the database** — destructive; wipes the app database **and Gitea's**:
```
@@ -350,36 +558,120 @@ 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):
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket,
with the `uploads` volume as a safety net. Nothing breaks while Garage is down
or not set up:
- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to
disk (with a log line) whenever Garage refuses a write;
- nginx serves `/uploads/` from Garage and falls back to the volume when
Garage has no such file or is unreachable, and it boots without the
`garage` container.
Turning it on:
1. Fill in `GARAGE_RPC_SECRET`, `GARAGE_ADMIN_TOKEN`, `S3_ACCESS_KEY_ID` and
`S3_SECRET_ACCESS_KEY` in `.env` **before** the deploy that adds the
containers (otherwise `garage` crash-loops on a blank secret until they
are set; nothing else is affected). `.env.example` says how to generate
each.
2. Deploy, then `garage/bootstrap.sh` (idempotent; it creates the layout, the
`uploads` bucket and the backend's key, and opens the bucket to the
website endpoint).
3. Set `S3_ENDPOINT=http://garage:3900` and `docker compose up -d backend`.
The backend logs `[upload] storing uploads in bucket uploads ...` on start.
4. Check: upload something through a canvas page or chat, then
`docker compose exec garage /garage bucket info uploads` shows the object
count going up, and the returned `/uploads/...` URL loads.
Moving the old files in (so they show in garage-webui, and so the bucket
holds everything):
```
./sync-secrets.sh
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env)
docker run --rm --network web_server_app-network \
-v web_server_uploads:/data:ro \
-e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \
-e AWS_DEFAULT_REGION=garage \
amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \
--endpoint-url http://garage:3900
```
**Set up the CI runner on a fresh Pi:**
The copies left on the volume are then only a fallback for when Garage is
down, and the rollback. One catch: a file deleted in garage-webui is still
served from its disk copy, if it has one. Once the bucket has been trusted for
a while, remove everything but `private/` from the volume.
**Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files
written to the bucket in the meantime stay reachable as long as `garage` runs;
to drop Garage entirely, first copy them back
(`aws s3 sync s3://uploads /data` with the volume mounted read-write).
**Managing files:** garage-webui at `/garage/` (site admin login). Files
uploaded there are public at `/uploads/<path>` and skip the backend's type
checks; keep them under a prefix such as `media/`. Uploads through it are
capped at 2G by nginx.
**Backups:** Garage here is one node on the same disk — it is not a backup.
Back up `garage_meta` and `garage_data` together (meta without data, or the
reverse, is useless); Garage also snapshots its metadata every 6h inside
`garage_meta`.
**Set up the CI runner on a fresh host:**
```
cd gitea-runner
bash download.sh # pulls the arm64 binary
bash download.sh # pulls the binary for this CPU
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises
```
The runner lives **outside** Docker on purpose: it runs `docker compose up`
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*
`.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
**Dependency updates (Renovate).** Dependabot is GitHub-only, so
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday
at 04:00 UTC (or by hand from the Actions tab), configured by
`renovate.json5`. It opens PRs from `renovate/*` branches, which get the
normal `test` job; nothing automerges, because merging to `main` deploys. It
needs a `RENOVATE_TOKEN` repo Actions secret: create a `renovate` Gitea user,
add it to this repo as a collaborator with write access, and mint a token for
it with `read:user`, `read:organization`, `write:repository` and
`write:issue`. `RENOVATE_GITHUB_COM_TOKEN` (any github.com token, no scopes)
is optional and lifts GitHub's rate limit on release-note lookups. The first
run opens a "Dependency Dashboard" issue listing everything pending.
**Go live on the radio:** point a broadcasting client (e.g. butt) at the host's
Tailscale name (not the domain, which resolves to Cloudflare) 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.
**Only nginx is restarted when unhealthy.** Docker marks a container
`unhealthy` but never acts on it; `restart: always` only brings back a process
that exits. The `autoheal` container restarts anything labelled
`autoheal=true`, which today is just nginx (its healthcheck fetches
`/nginx-health` on :80 every 30s; three misses, about 90s, and it is
restarted). `backend` and `python` also define healthchecks, but carry no
label, so for them `unhealthy` is only visible in `docker ps`. Add the label to
cover another service.
**Site down but every container `Up`.** That is what a stalled nginx worker
looks like (2026-10-19: 4.6 hours, every tunnel request a `TLS handshake
timeout` in `docker logs cloudflared`, and the Cloudflare dashboard still
showing the tunnel healthy, since that only covers the tunnel's own link). The
healthcheck should now catch it. If it recurs, capture the stuck worker before
restarting, since a restart destroys the only evidence of why:
```
docker inspect nginx --format '{{.State.Health.Status}}'
docker top nginx -o pid,stat,wchan:30,etime,cmd # what each worker is waiting in
docker compose restart nginx
```
---
@@ -397,13 +689,15 @@ 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 `/uploads/` location blocks (with `@uploads_disk`) 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
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.
+121
View File
@@ -0,0 +1,121 @@
# =============================================================================
# Makefile — one place for the commands that verify and run this repo.
#
# WHY THIS FILE EXISTS
# The stack is four toolchains (Go, Python, Node, Docker) and the command
# that checks each one used to live only in a gitignored notes file. `make
# check` is the single thing to run before pushing; .gitea/workflows/
# deploy.yaml runs the same backend and Python checks (in containers, since
# the Pi runner has no host toolchains) before it deploys.
#
# WHAT IT NEEDS ON THE HOST
# check-backend / generate Go (the version in backend/go.mod)
# check-python python3 with the venv module
# check-vue Node + `npm install` done in vue/
# check-compose / dev Docker with the compose plugin
# Nothing here installs a toolchain; a missing one fails that target only.
#
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
# its own shell, so the directory change cannot leak into the next line.
# =============================================================================
# `make` with no arguments prints the target list rather than running checks.
.DEFAULT_GOAL := help
# Overridable: `make check-python PYTHON=python3.12` to match the image.
PYTHON ?= python3
# The virtualenv for the Python checks. At the repo root rather than inside
# python/, because python/ is a docker build context and a venv there would be
# sent to the daemon on every build. Gitignored (/.venv/).
VENV := .venv
# Written after a successful install. Being a file target that depends on both
# requirements files, it is what makes `check-python` re-install when either
# changes and skip the install otherwise.
VENV_STAMP := $(VENV)/.installed
.PHONY: help check check-backend check-python check-vue check-compose generate dev
help:
@echo "Targets:"
@echo " make check run every check below"
@echo " make check-backend go vet + go test in backend/"
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
@echo " make check-vue vite build of vue/ into a throwaway directory"
@echo " make check-compose validate docker-compose.yml, alone and with the dev override"
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
@echo " make dev build and run the dev stack (http://localhost)"
# Run with `make -k check` to keep going past the first failing area.
check: check-backend check-python check-vue check-compose
check-backend:
cd backend && go vet ./... && go test ./...
# requirements-dev.txt `-r`-includes requirements.txt, so one install covers
# the app's dependencies and pytest. The venv is recreated from scratch
# whenever a requirements file changes: upgrading in place would leave behind
# packages that were removed from the files, and the check would keep passing
# on a dependency the image no longer has.
$(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
rm -rf $(VENV)
$(PYTHON) -m venv $(VENV)
$(VENV)/bin/python -m pip install --quiet --upgrade pip
$(VENV)/bin/python -m pip install --quiet -r python/requirements-dev.txt
touch $@
check-python: $(VENV_STAMP)
cd python && ../$(VENV)/bin/python -m pytest tests -q
# A Vite build is enough to catch a broken import or template; there is no
# test runner or linter for the frontend.
#
# The build goes to a temp directory that is removed afterwards (success or
# failure), so the check never leaves a vue/dist behind or overwrites one.
check-vue:
@test -d vue/node_modules || { \
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
exit 1; }
@out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \
cd vue && npx vite build --outDir "$$out" --emptyOutDir
# Validates the compose files: YAML, schema, and that every ${VAR} they
# interpolate resolves to something usable.
#
# With a real .env present this is simply `docker compose config -q`.
#
# Without one (a CI checkout, a fresh clone) two things break, and
# `--env-file .env.example` fixes neither:
# - several services declare `env_file: ./.env`, and compose refuses to load
# the project if that file does not exist;
# - .env.example has blank values, and OBSIDIAN_DIR is used as a bind-mount
# source, where an empty string is a hard "invalid spec" error.
# So in that case the files are validated against a temporary PROJECT
# DIRECTORY holding a copy of .env.example as its .env, with a placeholder for
# OBSIDIAN_DIR. `config` only resolves paths, it does not need them to exist,
# so the build contexts not being under the temp directory is fine. Nothing is
# written to the repo, and a real .env is never created by accident.
check-compose:
@set -e; \
if [ -f .env ]; then \
pd="."; \
else \
echo "check-compose: no .env, validating against .env.example"; \
pd=$$(mktemp -d); trap 'rm -rf "$$pd"' EXIT; \
cp .env.example "$$pd/.env"; \
echo "OBSIDIAN_DIR=/placeholder/obsidian" >> "$$pd/.env"; \
fi; \
echo "docker compose -f docker-compose.yml config -q"; \
docker compose --project-directory "$$pd" -f docker-compose.yml config -q; \
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
generate:
cd backend && go run github.com/99designs/gqlgen generate
# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx.
dev:
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
+19 -16
View File
@@ -1,3 +1,4 @@
Gay bal;;s
# My Web
![screenshot](vue/public/img/screenshot.png)
@@ -27,14 +28,12 @@ silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0)
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
silverbullet-git ── Commits/pushes notes edits to the notes repo
python (8000) ── Python API (FastAPI)
hasura (8080) ── Hasura GraphQL Engine (Docker profile: hasura)
autoheal ── Auto-restart unhealthy containers
certbot ── SSL Certificate Management (disabled in dev)
```
## Tech Stack
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX)
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
@@ -57,11 +56,10 @@ certbot ── SSL Certificate Management (disabled in dev)
- Printable CV with role-specific sections
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
- Hasura GraphQL console (admin-only)
- Admin-gated routes: `/notes`, `/sb`, `/hasura` require admin JWT via Nginx `auth_request`
- Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request`
- Landing page with animated stamps section
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
- Backend healthcheck with autoheal container for automatic recovery
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
## Pages
@@ -150,7 +148,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
**Protected (auth required)**
| Method | Path | Description |
| --- | --- | --- |
| POST | `/api/messages/upload` | Upload message file (rate limited: 5/min) |
| POST | `/api/messages/upload` | Upload a file for a chat message or a canvas box (rate limited: 30/min, burst 20) |
**Admin (auth + admin required)**
| Method | Path | Description |
@@ -183,13 +181,12 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
| `/api` | backend:8080 | API (rate limited: 30r/s) |
| `/radio` | icecast:8000 | Audio streaming |
| `/gitea` | gitea:3000 | Git service |
| `/hasura` | hasura:8080 | GraphQL console + WebSocket (admin-only) |
| `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) |
| `/sb` | silverbullet:3000 | Obsidian notes editor (admin-only) |
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
| `/uploads` | local alias | User-uploaded files |
`/hasura` and `/sb` are protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
### Deprecated Endpoints
@@ -246,12 +243,9 @@ 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 |
| `HASURA_GRAPHQL_ADMIN_SECRET` | Hasura admin secret |
| `HASURA_HOST` | Hasura hostname (use `hasura` for Docker) |
| `HASURA_PORT` | Hasura port (typically `8080`) |
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
| `PYTHON_PORT` | Python API port (defaults to `8000`) |
| `SEED_DB` | Set to `true` to seed test data on startup |
@@ -309,6 +303,7 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
Run the full stack over plain HTTP without SSL certificates:
```sh
cp .env.dev .env # committed, dummy values only
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
@@ -319,7 +314,6 @@ This:
- Disables certbot
- Seeds the database with test data (`SEED_DB=true`)
- Enables GraphQL playground and introspection
- Enables Hasura console and dev mode
Visit `http://localhost` to test.
@@ -329,7 +323,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
@@ -347,7 +351,6 @@ These files are git-ignored and must be created manually:
## Future Ideas
- More Rust to WASM
- ML for chatboards
- Cache requests
- Design more webpages
+2 -2
View File
@@ -46,8 +46,8 @@ FROM debian:bookworm-slim
# wget is not just for humans: the compose healthcheck probes the server with
# `wget -qO- http://localhost:8080/`, and without it in the image every probe
# fails as "executable file not found" — Docker then marks the container
# unhealthy and autoheal kills it in a ~90s restart loop.
# fails as "executable file not found" and Docker marks the container
# unhealthy.
RUN apt-get update \
&& apt-get install --yes --no-install-recommends ca-certificates wget \
&& rm -rf /var/lib/apt/lists/*
+189 -38
View File
@@ -2,7 +2,8 @@
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).
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
that needs Claude is asked of the Python service, not called from here.
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
@@ -18,9 +19,11 @@ handlers/ REST endpoints + the shared Store dependency container
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
schema/*.graphql source of truth for the schema, including who may call what
*.resolvers.go resolver implementations, one per schema file
*_helpers.go hand-written mapping helpers (never regenerated)
directives.go @admin / @signedIn: the authorisation checks, written once
directives_test.go fails when a mutation is added without one
context.go reading identity out of the resolver context
middleware.go putting it in
doc.go package overview — read this before touching resolvers
@@ -41,9 +44,10 @@ graph/ GraphQL layer
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.**
token is present, the JWT claims — and then lets everything through. A
field is guarded by a directive on it in the schema, `@admin` or
`@signedIn`, which runs before the resolver. **A field with neither is
public.** See [GraphQL authorisation](#graphql-authorisation).
5. Handlers and resolvers both reach the database and the caches through the
single `handlers.Store` built in `main`.
@@ -60,6 +64,16 @@ graph/ GraphQL layer
- `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.
- `GET /auth/validate/:permission` is the same for one named permission
(200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
*permission gate*, which lets a non-admin account into one service — the
receipt printer at `/receipt/` — without making it an admin. Grantable keys
are the registry `services.PermissionTypes` (`services/permissions.go`);
a user's grants are `User.Permissions`, set from the admin panel's Manage
Users tab (`setUserPermissions`). Admins pass every permission check. The
check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which
nginx forwards to the gated service as `X-Remote-User`.
- 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
@@ -70,6 +84,95 @@ The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
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 authorisation
Who may call a field is written in the schema, on the field:
```graphql
extend type Query {
bookmarks: [Bookmark!]! # public
places: [Place!]! @signedIn # any signed-in user
users: [User!]! @admin # admins only
}
```
| directive | passes when | error otherwise |
| --- | --- | --- |
| `@admin` | the access token's `admin` claim is true | `admin access required` |
| `@signedIn` | there is a valid access token at all | `authentication required` |
| *(none)* | always | — |
Both are declared in `graph/schema/schema.graphql`, implemented once in
`graph/directives.go`, and handed to gqlgen in `main.go`
(`graph.Config{Directives: graph.Directives()}`). gqlgen calls the directive
before the resolver; on an error the resolver never runs and the client gets
that message for the field. The two strings are shown as-is by the front end,
so they are part of the API. If the `Directives` line were ever dropped from
`main.go` the guarded fields would all fail (`directive admin is not
implemented`), not open.
This replaced an `if !IsAdminFromCtx(ctx) { return ... }` that was pasted into
the top of every guarded resolver, where leaving it out was invisible. Now a
guarded resolver has no check in it, and the absence of a guard is something a
test can see.
**What is guarded.** Queries are public and mutations are `@admin`, except:
- `login`, `logout`, `refreshToken` — public; they are how a session starts
and ends.
- `createPlace`, `updatePlace`, `deletePlace` and the `places` query —
`@signedIn`. Places are a shared list with no per-user ownership.
- `users`, `user` — queries, but `@admin`: private data.
**What a directive cannot say stays in the resolver**, using `IsAdminFromCtx` /
`UserIDFromCtx` from `graph/context.go`:
- `updatePost` / `deletePost` are `@admin` *and* require the caller to be the
post's author; `setUserAdmin` refuses to change the caller's own flag.
- `me` has no directive: it returns its own `unauthorized` error.
- `messages` has no directive: it filters private messages out for non-admins
instead of refusing.
- `spotifyNeedsReauth` has no directive: it is `false` for non-admins.
**The safety net** is `graph/directives_test.go`, which walks the parsed
schema:
- every `Mutation` field must carry `@admin` or `@signedIn`, unless it is in
the `publicMutations` list in that file (the three above). A new mutation
with no directive fails the build's tests until one or the other is done;
- the `@signedIn` mutations and the guarded queries are pinned by name, so
loosening `@admin` to `@signedIn`, or dropping a guard from a private query,
has to be done in the test as well;
- the directive functions are unit-tested, and a handful of operations are run
through the real executable schema to pin the messages on the wire.
One caveat: the test reads the `.graphql` files, but enforcement is in
`generated.go`. Adding a directive to an existing field does nothing until
gqlgen is re-run.
## Adding an entity
1. **Model** — add the struct to `models/models.go` with `ID uint`
(`gorm:"primarykey"`) and a `gorm.DeletedAt`, and list it in `AutoMigrate`
in `services/database.go`. There are no migration files.
2. **Schema** — add `graph/schema/<name>.graphql` with the type, its inputs,
and `extend type Query` / `extend type Mutation`. Put `@admin` or
`@signedIn` on every mutation, and on any query that is not for the public.
Use `#` comments, not `"""` descriptions.
3. **Binding** — map the type onto the model in `gqlgen.yml`, with
`deletedAt: resolver: false`. Without the entry gqlgen generates a second,
unrelated struct in `graph/model/`.
4. **Generate** — `go run github.com/99designs/gqlgen generate` (below). This
creates `graph/<name>.resolvers.go` with a stub per query and mutation.
5. **Resolvers** — fill the stubs in. Do not write an auth check; the
directive has run. Do not write an `ID` resolver; `ID uint` binds by itself
(see [IDs](#gotchas)). Put commentary inside the function bodies, since
gqlgen rewrites what is above the signature. A delete should load the row
first and return an error for a missing id, as the existing ones do.
6. **Test** — `go test ./...`. `directives_test.go` will tell you if a
mutation was left unguarded; if you added a guarded *query*, add it to the
pinned list there.
## GraphQL vs REST
GraphQL is the default and covers essentially all the site's data. REST exists
@@ -78,17 +181,46 @@ 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 |
| `/spotify/callback` | OAuth providers redirect a *browser* here |
| `/uploads`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
| `/uploads` (GET, admin) | lists the stored files, next to the endpoint that stores them |
| `/notes/*path` | streams a file download, not JSON |
| `/ws` | WebSocket upgrade |
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
## Calling the Python service
Every Claude call the site makes lives in the Python service; this backend has
no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at
`/jobs/` is a separate app with its own Claude calls.) It reaches the
internal routes directly over the Docker network
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
nginx, which answers 404 for `/py/internal/`:
| route | caller | sends | gets back |
| --- | --- | --- | --- |
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
Every route goes through one function, `services.CallPython[T]` in
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
It has the one HTTP client (two-minute timeout, above the Python side's own
worst case of a retried Claude call) and the one rule for failures:
- a **502 whose `detail` is a string** is a message the route wrote for a
person ("failed to parse image data"). It comes back as a
`*services.PythonError`, and the HTTP handler relays it to the browser;
- **anything else** — connection refused, a 422 (its `detail` is a list), a
503 for an unset `CLAUDE_API_KEY`, a reply that will not decode — is an
ordinary error. Callers log it and show something generic.
It lives in `services` so that a background job there could use it as well
as a handler. A new internal route needs only a
request struct, a reply struct and a one-line call.
## 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
`handlers.Store`. Nothing here fails start-up: a missing Spotify token 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:
@@ -103,12 +235,21 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
- **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.
- **python_call.go** — `CallPython`, the one way to reach the Python service's
internal routes. See [Calling the Python service](#calling-the-python-service).
- **uploads.go** — every stored file. `Uploads.Save(ctx, fileHeader, private)`
validates against `UploadTypes` (extension, stored Content-Type, content
sniff) and `MaxUploadSize`, names the file randomly, stores it and returns
its `/uploads/...` URL; an `*UploadError` is the uploader's fault and safe
to show them. Public files go to the Garage bucket wrapped in
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
(nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
first and disk second, so either store's files work at the same URL. A new
handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind
admin-only `GET /uploads`, for the canvas's upload picker) returns the union
of bucket and disk, allow-listed types only, newest first; it is admin-only
because listing would give away every unguessable URL.
- **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
@@ -122,6 +263,10 @@ The `.graphql` files are the source of truth.
cd backend && go run github.com/99designs/gqlgen generate
```
If that stops with `missing go.sum entry ... urfave/cli`, the generator's own
dependencies are not in `go.sum`. `go get github.com/99designs/gqlgen@<the
version in go.mod>` adds them.
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
@@ -132,16 +277,30 @@ the end of it — which is why shared helpers live in `*_helpers.go` instead.
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
generated struct rather than the model you expected.
One scalar-level binding in `gqlgen.yml` is worth knowing about: `ID` lists
both `graphql.IntID` and `graphql.UintID` (see IDs under Gotchas).
If you delete a field or stop needing a resolver, delete the resolver function
by hand before regenerating; otherwise gqlgen keeps it, commented out, in a
warning block at the end of the file.
## Gotchas
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
`gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
- **Soft delete everywhere.** Every model 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)`.
- **IDs.** Models use `uint`; the schema uses `ID`. `gqlgen.yml` binds `ID` to
`graphql.IntID` *and* `graphql.UintID`, so a model's `ID uint` field is
served directly — there are no `ID` resolvers, and a new type does not need
one. `IntID` is listed first, which is why resolver *arguments* are still
`id int`. Both write an id as a quoted decimal string (`"12"`) and accept a
string or a number, so the wire format is the same either way. Other
unsigned fields are not IDs and still have resolvers: `Message.authorId`,
`Rowing.time`, `Rowing.distance`.
- **Deletes error on a missing id.** Every delete mutation loads the row
first, so a wrong id is a `record not found` error.
- **`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
@@ -149,19 +308,10 @@ generated struct rather than the model you expected.
- **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 — via the shared `services.StripMarkdownFence`, used by both
`handle_rowing.go` and `email_sync.go`.
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
A failed email is recorded with action `"error"` and an attempt counter;
while it has attempts left the next sync reprocesses it and updates the same
row. Because the fetch window is anchored to *processing* time, which has
already moved past the failure, the sync also rewinds the window to the
oldest retryable row's `ReceivedAt` — otherwise the email could never be
re-fetched. Once the cap is reached the row is terminal, so an email Claude
can never parse stops costing API calls.
- **Authenticating email after start-up does not start the scheduler**, which
only checks readiness once — restart, or trigger syncs by hand.
- **Claude's output is never parsed here.** Prompts, the markdown-fence
stripping and the JSON parsing are all in the Python service; this side
receives typed JSON or an error (see
[Calling the Python service](#calling-the-python-service)).
- **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;
@@ -180,14 +330,15 @@ generated struct rather than the model you expected.
| `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 |
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
| `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).
`/backend/fallback_music`, `/backend/token/` (the Spotify OAuth token).
`CLAUDE_API_KEY` is not in the table: the backend does not read it. The
`python` and `jobs` containers, the two that use it, get it through their
explicit `environment:` lists in `docker-compose.yml`. The email and job-lead variables still in `.env` belong to the job
tracker (`jobs`), which has its own repo and README.
+12 -5
View File
@@ -4,7 +4,9 @@ go 1.26
require (
github.com/99designs/gqlgen v0.17.95
github.com/anthropics/anthropic-sdk-go v1.26.0
github.com/aws/aws-sdk-go-v2 v1.47.3
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3
github.com/gin-gonic/gin v1.11.0
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/gorilla/websocket v1.5.3
@@ -19,6 +21,15 @@ require (
require (
github.com/agnivade/levenshtein v1.2.1 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
github.com/aws/smithy-go v1.28.5 // indirect
github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
@@ -49,10 +60,6 @@ require (
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect
github.com/sosodev/duration v1.4.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
go.uber.org/mock v0.5.0 // indirect
+24 -16
View File
@@ -37,10 +37,32 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
github.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=
github.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys=
github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k=
github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
@@ -60,8 +82,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
@@ -205,16 +225,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
@@ -522,8 +532,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
+59 -12
View File
@@ -16,9 +16,16 @@ resolver:
filename_template: "{name}.resolvers.go"
models:
# Two bindings, tried in order. IntID comes first, so it is what gqlgen
# picks where it has a free choice — resolver arguments stay `id int`.
# UintID is there so a model's `ID uint` field binds to `id: ID!` directly,
# with no hand-written resolver converting it. Both write an id as a quoted
# decimal string ("12") and read a string or a number, so which one a field
# uses is invisible on the wire.
ID:
model:
- github.com/99designs/gqlgen/graphql.IntID
- github.com/99designs/gqlgen/graphql.UintID
User:
model:
- adam-french.co.uk/backend/models.User
@@ -27,6 +34,10 @@ models:
resolver: false
deletedAt:
resolver: false
# Not a database model: the fixed registry in services/permissions.go.
PermissionType:
model:
- adam-french.co.uk/backend/services.PermissionType
Post:
model:
- adam-french.co.uk/backend/models.Post
@@ -63,21 +74,57 @@ models:
fields:
deletedAt:
resolver: false
JobApplication:
model:
- adam-french.co.uk/backend/models.JobApplication
fields:
deletedAt:
resolver: false
JobAppReference:
model:
- adam-french.co.uk/backend/models.JobAppReference
fields:
deletedAt:
resolver: false
Place:
model:
- adam-french.co.uk/backend/models.Place
fields:
deletedAt:
resolver: false
Box:
model:
- adam-french.co.uk/backend/models.Box
fields:
deletedAt:
resolver: false
Page:
model:
- adam-french.co.uk/backend/models.Page
fields:
deletedAt:
resolver: false
Background:
model:
- adam-french.co.uk/backend/models.Background
fields:
deletedAt:
resolver: false
Layout:
model:
- adam-french.co.uk/backend/models.Layout
fields:
deletedAt:
resolver: false
boxCount:
resolver: true
hasBackground:
resolver: true
Component:
model:
- adam-french.co.uk/backend/models.Component
fields:
deletedAt:
resolver: false
uses:
resolver: true
CoverLetter:
model:
- adam-french.co.uk/backend/models.CoverLetter
fields:
deletedAt:
resolver: false
CoverSnippet:
model:
- adam-french.co.uk/backend/models.CoverSnippet
fields:
deletedAt:
resolver: false
+3 -16
View File
@@ -7,24 +7,16 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
return int(obj.ID), nil
}
// 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")
}
// Admin-only, but there is no check to see here: the field is marked
// @admin in the schema and the directive (directives.go) has already
// refused anyone else by the time this runs.
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&activity).Error; err != nil {
return nil, err
@@ -41,8 +33,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
}
return ptrs(activities), nil
}
// Activity returns ActivityResolver implementation.
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
type activityResolver struct{ *Resolver }
+3
View File
@@ -121,6 +121,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
// Me is the resolver for the me field.
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
// Checked here rather than with @signedIn because the message differs:
// this query has always answered "unauthorized", and the directive's is
// "authentication required".
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
+63
View File
@@ -0,0 +1,63 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// SetBackground is the resolver for the setBackground field.
func (r *mutationResolver) SetBackground(ctx context.Context, page string, input model.BackgroundInput) (*models.Background, error) {
// One row per page: replaced in place if there is one, so its id stays
// stable for the store on the front end.
bg, err := backgroundFrom(page, input)
if err != nil {
return nil, err
}
var existing models.Background
err = r.Store.DB.Where("page = ?", page).First(&existing).Error
switch {
case err == nil:
bg.ID, bg.CreatedAt = existing.ID, existing.CreatedAt
err = r.Store.DB.Save(&bg).Error
case errors.Is(err, gorm.ErrRecordNotFound):
err = r.Store.DB.Create(&bg).Error
}
if err != nil {
return nil, err
}
return &bg, nil
}
// ClearBackground is the resolver for the clearBackground field.
func (r *mutationResolver) ClearBackground(ctx context.Context, page string) (bool, error) {
res := r.Store.DB.Where("page = ?", page).Delete(&models.Background{})
return res.RowsAffected > 0, res.Error
}
// Background is the resolver for the background field.
func (r *queryResolver) Background(ctx context.Context, page string) (*models.Background, error) {
// Null, not an error, when the page has none: that is the default look.
// Hidden along with an adminOnly page, like its boxes.
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
if err != nil || hidden {
return nil, err
}
var bg models.Background
err = r.Store.DB.Where("page = ?", page).First(&bg).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &bg, nil
}
+53
View File
@@ -0,0 +1,53 @@
package graph
// Hand-written helpers for background.resolvers.go, kept out of the resolver
// file for the same reason as box_helpers.go.
import (
"errors"
"regexp"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// The SPA puts these values straight into a style binding, as
// `background-color` and `url("<image>")`. Vue sets them through the CSSOM,
// so nothing can escape into other properties, but a quote or bracket in the
// image could still end the url() early — hence the narrow shapes.
var (
// A hex colour, a colour name, or one of the colour functions — named,
// so that url() and friends don't pass as a "function".
bgColorPattern = regexp.MustCompile(`^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+|(rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z.,%/ -]*\))$`)
// A site path (an upload, /img/...) or an http(s) URL, with no quotes,
// brackets, backslashes or spaces.
bgImagePattern = regexp.MustCompile(`^(/|https?://)[^\s"'()\\<>]*$`)
)
const maxBgImageLen = 1000
var bgFits = map[string]bool{"cover": true, "contain": true, "tile": true}
// backgroundFrom validates input into a Background for page.
func backgroundFrom(page string, input model.BackgroundInput) (models.Background, error) {
bg := models.Background{
Page: page,
Color: strings.TrimSpace(input.Color),
Image: strings.TrimSpace(input.Image),
Fit: input.Fit,
}
if !validPageKey(page) {
return bg, errors.New("a background needs a valid page")
}
if bg.Color != "" && (len(bg.Color) > 64 || !bgColorPattern.MatchString(bg.Color)) {
return bg, errors.New(`colour must be a CSS colour such as #1b110e, black or rgb(0 0 0 / 50%)`)
}
if bg.Image != "" && (len(bg.Image) > maxBgImageLen || !bgImagePattern.MatchString(bg.Image)) {
return bg, errors.New("image must be a path on this site (e.g. /uploads/...) or an http(s) URL, without spaces or quotes")
}
if !bgFits[bg.Fit] {
return bg, errors.New(`fit must be "cover", "contain" or "tile"`)
}
return bg, nil
}
+33
View File
@@ -0,0 +1,33 @@
package graph
import (
"testing"
"adam-french.co.uk/backend/graph/model"
)
func TestBackgroundFrom(t *testing.T) {
for _, c := range []struct {
page string
input model.BackgroundInput
ok bool
}{
{"index", model.BackgroundInput{Color: "#102030", Fit: "cover"}, true},
{"shrines/gto", model.BackgroundInput{Image: "/uploads/abc.gif", Fit: "tile"}, true},
{"stp", model.BackgroundInput{Color: "rgb(0 0 0 / 50%)", Image: "https://example.com/a.png", Fit: "contain"}, true},
{"index", model.BackgroundInput{Color: "rebeccapurple", Fit: "cover"}, true},
{"index", model.BackgroundInput{Fit: "cover"}, true}, // plain theme colour
{"Index", model.BackgroundInput{Fit: "cover"}, false}, // bad page key
{"index", model.BackgroundInput{Fit: "stretch"}, false}, // unknown fit
{"index", model.BackgroundInput{Color: "red; color: blue", Fit: "cover"}, false},
{"index", model.BackgroundInput{Color: "url(/x.png)", Fit: "cover"}, false}, // an image in disguise
{"index", model.BackgroundInput{Image: `/x.png") , url("/y`, Fit: "cover"}, false},
{"index", model.BackgroundInput{Image: "javascript:alert(1)", Fit: "cover"}, false},
{"index", model.BackgroundInput{Image: "uploads/relative.png", Fit: "cover"}, false},
} {
_, err := backgroundFrom(c.page, c.input)
if (err == nil) != c.ok {
t.Errorf("backgroundFrom(%q, %+v) = %v, want ok=%v", c.page, c.input, err, c.ok)
}
}
}
-17
View File
@@ -7,22 +7,13 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
return int(obj.ID), nil
}
// CreateBookmark is the resolver for the createBookmark field.
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
return nil, err
@@ -32,9 +23,6 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
// DeleteBookmark is the resolver for the deleteBookmark field.
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
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.
@@ -56,8 +44,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
}
return ptrs(bookmarks), nil
}
// Bookmark returns BookmarkResolver implementation.
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
type bookmarkResolver struct{ *Resolver }
+168
View File
@@ -0,0 +1,168 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateBox is the resolver for the createBox field.
func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) {
// Framed defaults to true here rather than in the gorm tag — see the
// comment on models.Box.Framed. Sizes not supplied fall back to the
// same 300x200 the column defaults use.
box := models.Box{
Page: input.Page,
Kind: input.Kind,
Widget: input.Widget,
HTML: input.HTML,
Title: input.Title,
W: 300,
H: 200,
Framed: true,
}
setInt(&box.X, input.X)
setInt(&box.Y, input.Y)
setInt(&box.W, input.W)
setInt(&box.H, input.H)
setInt(&box.Z, input.Z)
if input.Framed != nil {
box.Framed = *input.Framed
}
if input.Shadow != nil {
box.Shadow = *input.Shadow
}
if input.HideOnMobile != nil {
box.HideOnMobile = *input.HideOnMobile
}
if input.AdminOnly != nil {
box.AdminOnly = *input.AdminOnly
}
// A linked box takes its html from the component, so its own is
// dropped rather than stored as a copy that would quietly go stale.
if input.ComponentID != nil {
id := uint(*input.ComponentID)
exists, err := componentExists(r.Store.DB, id)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.New("there is no such component")
}
box.Kind = "html"
box.Widget = nil
box.HTML = nil
box.ComponentID = &id
}
if err := validateBox(&box); err != nil {
return nil, err
}
if err := r.Store.DB.Create(&box).Error; err != nil {
return nil, err
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
return &box, nil
}
// UpdateBox is the resolver for the updateBox field.
func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) {
// Partial update: nil fields are left alone. The canvas sends only the
// geometry after a drag and only the html after an edit, so this is
// what keeps the two from overwriting each other. Kind is not
// updatable — switching a widget box to html is a delete and create.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
}
if input.Widget != nil {
box.Widget = input.Widget
}
if input.HTML != nil {
// A linked box's html is the component's; changing it here would
// only fork a copy. The editor sends it to updateComponent instead.
if box.ComponentID != nil {
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
}
box.HTML = input.HTML
}
if input.Title != nil {
box.Title = input.Title
}
setInt(&box.X, input.X)
setInt(&box.Y, input.Y)
setInt(&box.W, input.W)
setInt(&box.H, input.H)
setInt(&box.Z, input.Z)
if input.Framed != nil {
box.Framed = *input.Framed
}
if input.Shadow != nil {
box.Shadow = *input.Shadow
}
if input.HideOnMobile != nil {
box.HideOnMobile = *input.HideOnMobile
}
if input.AdminOnly != nil {
box.AdminOnly = *input.AdminOnly
}
if err := validateBox(&box); err != nil {
return nil, err
}
if err := r.Store.DB.Save(&box).Error; err != nil {
return nil, err
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
return &box, nil
}
// DeleteBox is the resolver for the deleteBox field.
func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box, error) {
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&box).Error; err != nil {
return nil, err
}
return &box, nil
}
// Boxes is the resolver for the boxes field.
func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) {
// Public: this is the page layout every visitor loads. Ordered by z so
// DOM order matches stacking order, which keeps tab order sensible.
//
// What is admin-only is filtered here rather than hidden in the browser,
// so a private note never reaches anyone else: an adminOnly page answers
// with no boxes at all, and adminOnly boxes are left out of the rest.
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
if err != nil {
return nil, err
}
if hidden {
return []*models.Box{}, nil
}
query := r.Store.DB.Where("page = ?", page)
if !IsAdminFromCtx(ctx) {
query = query.Where("admin_only = ?", false)
}
var boxes []models.Box
if err := query.Order("z ASC, id ASC").Find(&boxes).Error; err != nil {
return nil, err
}
if err := fillLinked(r.Store.DB, boxes); err != nil {
return nil, err
}
return ptrs(boxes), nil
}
+71
View File
@@ -0,0 +1,71 @@
package graph
// Hand-written helpers for box.resolvers.go. Kept out of that file because
// gqlgen moves unknown code in a resolvers file to the end, under a warning
// comment, on every regenerate.
import (
"errors"
"fmt"
"strings"
"adam-french.co.uk/backend/models"
)
// minBoxSize stops a box being resized to nothing, after which it could not
// be grabbed again on the canvas.
const minBoxSize = 40
// maxShadowLen bounds a box's shadow, which is a single CSS value: even a
// stack of a few comma-separated shadows is well under it.
const maxShadowLen = 200
func setInt(dst *int, src *int) {
if src != nil {
*dst = *src
}
}
// validateBox checks the fields a box needs to render and clamps geometry
// rather than rejecting it, because a drag that overshoots the canvas edge
// should land at the edge, not fail.
func validateBox(box *models.Box) error {
if !validPageKey(box.Page) {
return errors.New("a box needs a valid page")
}
switch box.Kind {
case "widget":
if box.Widget == nil || *box.Widget == "" {
return errors.New("a widget box needs a widget name")
}
case "html":
// A linked box's html lives on its component (fillLinked).
if box.HTML == nil && box.ComponentID == nil {
return errors.New("an html box needs html")
}
default:
return errors.New(`box kind must be "widget" or "html"`)
}
if box.ComponentID != nil && box.Kind != "html" {
return errors.New("only an html box can be linked to a component")
}
if err := validateShadow(&box.Shadow); err != nil {
return err
}
box.X = max(box.X, 0)
box.Y = max(box.Y, 0)
box.W = max(box.W, minBoxSize)
box.H = max(box.H, minBoxSize)
return nil
}
// validateShadow trims a box-shadow value and bounds its length. The value is
// not parsed: the front end sets it through a style binding, so it can only
// ever be the one property, and an invalid value just draws no shadow.
func validateShadow(shadow *string) error {
*shadow = strings.TrimSpace(*shadow)
if len(*shadow) > maxShadowLen {
return fmt.Errorf("a shadow is at most %d characters", maxShadowLen)
}
return nil
}
+47
View File
@@ -0,0 +1,47 @@
package graph
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidateBox(t *testing.T) {
str := func(s string) *string { return &s }
one := uint(1)
for _, c := range []struct {
name string
box models.Box
wantErr bool
}{
{"widget with a name", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat")}, false},
{"widget without a name", models.Box{Page: "stp", Kind: "widget"}, true},
{"widget with an empty name", models.Box{Page: "stp", Kind: "widget", Widget: str("")}, true},
{"html with html", models.Box{Page: "stp", Kind: "html", HTML: str("<p>hi</p>")}, false},
{"html with empty html", models.Box{Page: "stp", Kind: "html", HTML: str("")}, false},
{"html without html", models.Box{Page: "stp", Kind: "html"}, true},
{"linked html without html", models.Box{Page: "stp", Kind: "html", ComponentID: &one}, false},
{"linked widget", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), ComponentID: &one}, true},
{"no page", models.Box{Kind: "widget", Widget: str("Chat")}, true},
{"bad page", models.Box{Page: "Shrines/GTO", Kind: "widget", Widget: str("Chat")}, true},
{"unknown kind", models.Box{Page: "stp", Kind: "iframe", HTML: str("x")}, true},
} {
t.Run(c.name, func(t *testing.T) {
err := validateBox(&c.box)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
})
}
// Geometry is clamped, not rejected: a drag past the canvas edge lands
// at the edge, and a box can never shrink below a grabbable size.
box := models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), X: -30, Y: -1, W: 5, H: 0}
if err := validateBox(&box); err != nil {
t.Fatal(err)
}
if box.X != 0 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize {
t.Fatalf("clamped to %d,%d %dx%d; want 0,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize)
}
}
+195
View File
@@ -0,0 +1,195 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// Uses is the resolver for the uses field.
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
// One count per component, which is fine for an admin-only list of a
// handful; soft-deleted boxes are excluded by GORM's default scope.
var count int64
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
return 0, err
}
return int(count), nil
}
// CreateComponent is the resolver for the createComponent field.
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
// Framed defaults to true and the size to 300x200, as for a new box.
name, err := usableComponentName(r.Store.DB, input.Name, 0)
if err != nil {
return nil, err
}
c := models.Component{Name: name, Title: input.Title, HTML: input.HTML, W: 300, H: 200, Framed: true}
setInt(&c.W, input.W)
setInt(&c.H, input.H)
if input.Framed != nil {
c.Framed = *input.Framed
}
if input.Shadow != nil {
c.Shadow = *input.Shadow
}
if input.AdminOnly != nil {
c.AdminOnly = *input.AdminOnly
}
c.W = max(c.W, minBoxSize)
c.H = max(c.H, minBoxSize)
if err := validateShadow(&c.Shadow); err != nil {
return nil, err
}
if err := r.Store.DB.Create(&c).Error; err != nil {
return nil, err
}
return &c, nil
}
// UpdateComponent is the resolver for the updateComponent field.
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
// Partial, like updateBox. Nothing to do for the linked boxes: they
// read the html from here every time they are fetched.
var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := usableComponentName(r.Store.DB, *input.Name, c.ID)
if err != nil {
return nil, err
}
c.Name = name
}
if input.Title != nil {
c.Title = input.Title
}
if input.HTML != nil {
c.HTML = *input.HTML
}
setInt(&c.W, input.W)
setInt(&c.H, input.H)
if input.Framed != nil {
c.Framed = *input.Framed
}
if input.Shadow != nil {
c.Shadow = *input.Shadow
}
if input.AdminOnly != nil {
c.AdminOnly = *input.AdminOnly
}
c.W = max(c.W, minBoxSize)
c.H = max(c.H, minBoxSize)
if err := validateShadow(&c.Shadow); err != nil {
return nil, err
}
if err := r.Store.DB.Save(&c).Error; err != nil {
return nil, err
}
return &c, nil
}
// DeleteComponent is the resolver for the deleteComponent field.
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
// The linked boxes keep showing what they showed, as copies, so
// deleting a component never changes a page. One transaction, so a
// failure can't leave boxes linked to a deleted component.
var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err
}
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
if err := detachFrom(tx, &c); err != nil {
return err
}
return tx.Delete(&c).Error
})
if err != nil {
return nil, err
}
return &c, nil
}
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
// The box becomes the component's first linked instance, so carrying
// on editing it edits the component. A box that is already linked
// would make a component of a component's html; detach it first.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
}
if box.Kind != "html" || box.HTML == nil {
return nil, errors.New("only an html box can be saved as a component")
}
if box.ComponentID != nil {
return nil, errors.New("that box is already linked to a component")
}
name, err := usableComponentName(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
c := models.Component{
Name: name, Title: box.Title, HTML: *box.HTML,
W: box.W, H: box.H, Framed: box.Framed, Shadow: box.Shadow, AdminOnly: box.AdminOnly,
}
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&c).Error; err != nil {
return err
}
box.ComponentID = &c.ID
box.HTML = nil
return tx.Save(&box).Error
})
if err != nil {
return nil, err
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
return &box, nil
}
// DetachBox is the resolver for the detachBox field.
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
// The html is filled in from the component and then saved, which is
// exactly the copy fillLinked otherwise never lets reach the row.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
}
if box.ComponentID == nil {
return nil, errors.New("that box isn't linked to a component")
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
box.ComponentID = nil
if err := r.Store.DB.Save(&box).Error; err != nil {
return nil, err
}
return &box, nil
}
// Components is the resolver for the components field.
func (r *queryResolver) Components(ctx context.Context) ([]*models.Component, error) {
var components []models.Component
if err := r.Store.DB.Order("name ASC").Find(&components).Error; err != nil {
return nil, err
}
return ptrs(components), nil
}
// Component returns ComponentResolver implementation.
func (r *Resolver) Component() ComponentResolver { return &componentResolver{r} }
type componentResolver struct{ *Resolver }
+112
View File
@@ -0,0 +1,112 @@
package graph
// Hand-written helpers for component.resolvers.go, kept out of the resolver
// file for the same reason as box_helpers.go.
import (
"errors"
"fmt"
"strings"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const maxComponentNameLen = 100
// cleanComponentName trims name and reports why it can't be a component's
// name.
func cleanComponentName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a component needs a name")
}
if len(name) > maxComponentNameLen {
return name, fmt.Errorf("a component name is at most %d characters", maxComponentNameLen)
}
return name, nil
}
// componentNameTaken reports whether a live component other than exceptID
// has this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// usableComponentName checks name and answers with a sentence if it can't be
// used, so the resolvers that name a component share one set of messages.
func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error) {
name, err := cleanComponentName(name)
if err != nil {
return name, err
}
taken, err := componentNameTaken(db, name, exceptID)
if err != nil {
return name, err
}
if taken {
return name, errors.New("there is already a component with that name")
}
return name, nil
}
// fillLinked sets each linked box's in-memory HTML to its component's, with
// one query for all of them. Only for boxes about to be returned or
// snapshotted: a linked row's own HTML is nil, and saving a filled box would
// freeze a copy of the component into it. A box whose component has gone
// (deleted outside deleteComponent, which detaches first) is left with
// empty HTML rather than failing the whole page.
func fillLinked(db *gorm.DB, boxes []models.Box) error {
var ids []uint
for _, b := range boxes {
if b.ComponentID != nil {
ids = append(ids, *b.ComponentID)
}
}
if len(ids) == 0 {
return nil
}
var components []models.Component
if err := db.Where("id IN ?", ids).Find(&components).Error; err != nil {
return err
}
html := make(map[uint]string, len(components))
for _, c := range components {
html[c.ID] = c.HTML
}
for i := range boxes {
if id := boxes[i].ComponentID; id != nil {
h := html[*id]
boxes[i].HTML = &h
}
}
return nil
}
// fillLinkedOne is fillLinked for a single box.
func fillLinkedOne(db *gorm.DB, box *models.Box) error {
boxes := []models.Box{*box}
if err := fillLinked(db, boxes); err != nil {
return err
}
*box = boxes[0]
return nil
}
// componentExists reports whether id is a live component, for linking a box
// to it.
func componentExists(db *gorm.DB, id uint) (bool, error) {
var count int64
err := db.Model(&models.Component{}).Where("id = ?", id).Count(&count).Error
return count > 0, err
}
// detachFrom gives every box linked to component c its own copy of c's HTML
// and unlinks it, inside tx.
func detachFrom(tx *gorm.DB, c *models.Component) error {
return tx.Model(&models.Box{}).Where("component_id = ?", c.ID).
Updates(map[string]any{"html": c.HTML, "component_id": nil}).Error
}
+30
View File
@@ -0,0 +1,30 @@
package graph
import (
"strings"
"testing"
)
func TestCleanComponentName(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "Clock", "Clock", false},
{"trimmed", " Clock \n", "Clock", false},
{"empty", "", "", true},
{"only spaces", " ", "", true},
{"at the limit", strings.Repeat("a", maxComponentNameLen), strings.Repeat("a", maxComponentNameLen), false},
{"too long", strings.Repeat("a", maxComponentNameLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanComponentName(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
+12 -6
View File
@@ -27,7 +27,8 @@ const (
// 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.
// not an error here, because many queries are public. Turning "anonymous"
// into a refusal is the job of the schema directives, per field.
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
if !ok {
@@ -38,6 +39,10 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
// float64 because claims are decoded by encoding/json, hence the conversion.
//
// ok is also the test behind the @signedIn directive. A resolver calls this
// itself when it needs the id for more than a gate: to record a post's
// author, or to compare the caller with a row's owner.
func UserIDFromCtx(ctx context.Context) (uint, bool) {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
@@ -50,11 +55,12 @@ 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.
// IsAdminFromCtx reports whether the request carries an admin token. It is
// what the @admin directive tests (directives.go), which is how nearly every
// mutation is authorised; resolvers call it directly only for the softer
// cases a directive cannot express, such as the messages query filtering
// rather than refusing. Admin comes from the token, not the database, so a
// revoked admin flag only bites once the access token expires.
func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
+153
View File
@@ -0,0 +1,153 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateCoverLetter is the resolver for the createCoverLetter field.
func (r *mutationResolver) CreateCoverLetter(ctx context.Context, input model.CreateCoverLetterInput) (*models.CoverLetter, error) {
name, err := cleanCoverLetterName(input.Name)
if err != nil {
return nil, err
}
if err := checkCoverLetterBody(input.Body); err != nil {
return nil, err
}
taken, err := coverLetterNameTaken(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a cover letter with that name")
}
letter := models.CoverLetter{Name: name, Body: input.Body}
if err := r.Store.DB.Create(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// UpdateCoverLetter is the resolver for the updateCoverLetter field.
func (r *mutationResolver) UpdateCoverLetter(ctx context.Context, id int, input model.UpdateCoverLetterInput) (*models.CoverLetter, error) {
var letter models.CoverLetter
if err := r.Store.DB.First(&letter, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := cleanCoverLetterName(*input.Name)
if err != nil {
return nil, err
}
taken, err := coverLetterNameTaken(r.Store.DB, name, letter.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a cover letter with that name")
}
letter.Name = name
}
if input.Body != nil {
if err := checkCoverLetterBody(*input.Body); err != nil {
return nil, err
}
letter.Body = *input.Body
}
if err := r.Store.DB.Save(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// DeleteCoverLetter is the resolver for the deleteCoverLetter field.
func (r *mutationResolver) DeleteCoverLetter(ctx context.Context, id int) (*models.CoverLetter, error) {
var letter models.CoverLetter
if err := r.Store.DB.First(&letter, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// CreateCoverSnippet is the resolver for the createCoverSnippet field.
func (r *mutationResolver) CreateCoverSnippet(ctx context.Context, input model.CreateCoverSnippetInput) (*models.CoverSnippet, error) {
text, err := cleanSnippetText(input.Text)
if err != nil {
return nil, err
}
snippet := models.CoverSnippet{Text: text}
if input.Section != nil {
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
return nil, err
}
}
if err := r.Store.DB.Create(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// UpdateCoverSnippet is the resolver for the updateCoverSnippet field.
func (r *mutationResolver) UpdateCoverSnippet(ctx context.Context, id int, input model.UpdateCoverSnippetInput) (*models.CoverSnippet, error) {
// Letters it was dropped into keep their own copy of the old text.
var snippet models.CoverSnippet
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
return nil, err
}
var err error
if input.Text != nil {
if snippet.Text, err = cleanSnippetText(*input.Text); err != nil {
return nil, err
}
}
if input.Section != nil {
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
return nil, err
}
}
if err := r.Store.DB.Save(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// DeleteCoverSnippet is the resolver for the deleteCoverSnippet field.
func (r *mutationResolver) DeleteCoverSnippet(ctx context.Context, id int) (*models.CoverSnippet, error) {
var snippet models.CoverSnippet
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// CoverLetters is the resolver for the coverLetters field.
func (r *queryResolver) CoverLetters(ctx context.Context) ([]*models.CoverLetter, error) {
var letters []models.CoverLetter
if err := r.Store.DB.Order("updated_at DESC").Find(&letters).Error; err != nil {
return nil, err
}
return ptrs(letters), nil
}
// CoverSnippets is the resolver for the coverSnippets field.
func (r *queryResolver) CoverSnippets(ctx context.Context) ([]*models.CoverSnippet, error) {
var snippets []models.CoverSnippet
if err := r.Store.DB.Order("section ASC, created_at DESC").Find(&snippets).Error; err != nil {
return nil, err
}
return ptrs(snippets), nil
}
+84
View File
@@ -0,0 +1,84 @@
package graph
// Hand-written helpers for cover_letter.resolvers.go, kept out of the
// resolver file for the same reason as box_helpers.go.
import (
"encoding/json"
"errors"
"fmt"
"strings"
"unicode/utf8"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const (
maxCoverLetterNameLen = 100
// A letter is a page of text; 100 KB is far beyond any real one and
// still small enough that a runaway client can't fill the table.
maxCoverLetterBodyLen = 100 * 1024
maxSnippetTextLen = 5000
maxSnippetSectionLen = 100
)
// cleanCoverLetterName trims name and reports why it can't be a letter's
// name.
func cleanCoverLetterName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a cover letter needs a name")
}
if len(name) > maxCoverLetterNameLen {
return name, fmt.Errorf("a cover letter name is at most %d characters", maxCoverLetterNameLen)
}
return name, nil
}
// coverLetterNameTaken reports whether a live letter other than exceptID has
// this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// checkCoverLetterBody reports why body can't be stored. The server never
// reads inside it, so it only has to be a JSON object of a sane size — an
// array or a bare string would be a frontend bug worth refusing early.
func checkCoverLetterBody(body string) error {
if len(body) > maxCoverLetterBodyLen {
return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024)
}
var obj map[string]json.RawMessage
// null unmarshals into a nil map without error, so it is caught here too.
if err := json.Unmarshal([]byte(body), &obj); err != nil || obj == nil {
return errors.New("a cover letter body must be a JSON object")
}
return nil
}
// cleanSnippetText trims text and reports why it can't be a bank paragraph.
// Counted in characters, not bytes, since the limit is about how much prose
// fits rather than storage.
func cleanSnippetText(text string) (string, error) {
text = strings.TrimSpace(text)
if text == "" {
return text, errors.New("a paragraph can't be empty")
}
if utf8.RuneCountInString(text) > maxSnippetTextLen {
return text, fmt.Errorf("a paragraph is at most %d characters", maxSnippetTextLen)
}
return text, nil
}
// cleanSnippetSection trims a snippet's section title.
func cleanSnippetSection(section string) (string, error) {
section = strings.TrimSpace(section)
if utf8.RuneCountInString(section) > maxSnippetSectionLen {
return section, fmt.Errorf("a section title is at most %d characters", maxSnippetSectionLen)
}
return section, nil
}
@@ -0,0 +1,76 @@
package graph
import (
"strings"
"testing"
)
func TestCleanCoverLetterName(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "Acme", "Acme", false},
{"trimmed", " Acme \n", "Acme", false},
{"empty", "", "", true},
{"only spaces", " ", "", true},
{"at the limit", strings.Repeat("a", maxCoverLetterNameLen), strings.Repeat("a", maxCoverLetterNameLen), false},
{"too long", strings.Repeat("a", maxCoverLetterNameLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanCoverLetterName(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
func TestCheckCoverLetterBody(t *testing.T) {
for _, c := range []struct {
name, in string
wantErr bool
}{
{"object", `{"v":1,"sections":[]}`, false},
{"empty object", `{}`, false},
{"array", `[]`, true},
{"string", `"hi"`, true},
{"null", `null`, true},
{"not json", `{`, true},
{"empty", ``, true},
{"too big", `{"x":"` + strings.Repeat("a", maxCoverLetterBodyLen) + `"}`, true},
} {
t.Run(c.name, func(t *testing.T) {
if err := checkCoverLetterBody(c.in); (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
})
}
}
func TestCleanSnippetText(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "I like Go.", "I like Go.", false},
{"trimmed", "\n I like Go. ", "I like Go.", false},
{"empty", " ", "", true},
// Characters, not bytes: 5000 two-byte runes still fit.
{"multibyte at the limit", strings.Repeat("é", maxSnippetTextLen), strings.Repeat("é", maxSnippetTextLen), false},
{"too long", strings.Repeat("a", maxSnippetTextLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanSnippetText(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
+63
View File
@@ -0,0 +1,63 @@
package graph
import (
"context"
"fmt"
"github.com/99designs/gqlgen/graphql"
)
// The schema's two authorisation directives. A field marked @admin or
// @signedIn in graph/schema/*.graphql has the matching function here run
// before its resolver; if it returns an error the resolver is never called
// and the error is what the client receives for that field.
//
// This replaces a check that used to be copied into the top of every guarded
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
// it is now declared next to the field, where a missing one can be seen and
// tested for (directives_test.go), instead of being a line someone has to
// remember to paste.
//
// The two error strings are part of the contract with the front end, which
// shows them as they are; the tracker page, for one, explains "admin access
// required" as a lapsed session. Do not reword them.
//
// This file is hand-written and never touched by gqlgen.
const (
errAdminRequired = "admin access required"
errSignedInRequired = "authentication required"
)
// Directives is the set gqlgen needs in graph.Config. It is a function so
// that main and the tests wire exactly the same implementations.
//
// Leaving a directive nil in the Config does not open the fields that use it:
// the generated code answers "directive admin is not implemented" for each.
func Directives() DirectiveRoot {
return DirectiveRoot{
Admin: requireAdmin,
SignedIn: requireSignedIn,
}
}
// requireAdmin implements @admin: the request must carry an access token
// whose admin claim is true. Admin comes from the token, not the database, so
// demoting a user only bites once their access token is replaced.
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf(errAdminRequired)
}
return next(ctx)
}
// requireSignedIn implements @signedIn: any verified access token will do,
// admin or not. An admin is signed in, so this never needs pairing with
// @admin.
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf(errSignedInRequired)
}
return next(ctx)
}
+320
View File
@@ -0,0 +1,320 @@
package graph
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"sort"
"strings"
"testing"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/golang-jwt/jwt/v5"
"github.com/vektah/gqlparser/v2/ast"
"adam-french.co.uk/backend/handlers"
)
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
// by directives.go. These tests cover both halves: that the two functions
// decide correctly, and that the schema marks the fields it should — the
// second being the one that matters day to day, since the way this goes
// wrong is a new field added without a directive.
//
// Nothing here needs a database: a refused field never reaches its resolver,
// and the tests only ever drive fields that are refused or that return before
// touching the Store.
// withClaims builds the context AuthContextMiddleware would for a verified
// token. Claims are decoded from JSON in production, hence float64 for the id.
func withClaims(id float64, admin bool) context.Context {
claims := jwt.MapClaims{"id": id, "admin": admin}
return context.WithValue(context.Background(), userClaimsKey, &claims)
}
func TestDirectives(t *testing.T) {
anonymous := context.Background()
user := withClaims(2, false)
admin := withClaims(1, true)
// A token that verified but carries no id: not something GenerateJWT
// mints, but it must not count as signed in.
noID := func() context.Context {
claims := jwt.MapClaims{"admin": false}
return context.WithValue(context.Background(), userClaimsKey, &claims)
}()
cases := []struct {
name string
directive func(context.Context, any, graphql.Resolver) (any, error)
ctx context.Context
wantErr string // "" means the resolver must run
}{
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
{"@admin admits an admin", requireAdmin, admin, ""},
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
{"@signedIn admits an admin", requireSignedIn, admin, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
called := false
next := func(ctx context.Context) (any, error) {
called = true
return "resolved", nil
}
res, err := c.directive(c.ctx, nil, next)
if c.wantErr == "" {
if err != nil || !called || res != "resolved" {
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
}
return
}
// The exact strings are what the front end displays.
if err == nil || err.Error() != c.wantErr {
t.Fatalf("err = %v, want %q", err, c.wantErr)
}
if called {
t.Fatal("the resolver ran for a refused request")
}
if res != nil {
t.Fatalf("res = %v, want nil alongside the error", res)
}
})
}
}
// Directives() must supply every directive the schema declares; a nil one
// makes gqlgen fail each field that uses it.
func TestDirectivesAreAllImplemented(t *testing.T) {
d := Directives()
if d.Admin == nil || d.SignedIn == nil {
t.Fatal("Directives() left a directive unimplemented")
}
}
// guardOf reports which authorisation directive a field carries: "admin",
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
// nothing to @admin) and fails the test rather than being quietly accepted.
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
t.Helper()
admin := field.Directives.ForName("admin") != nil
signedIn := field.Directives.ForName("signedIn") != nil
switch {
case admin && signedIn:
t.Errorf("%s carries both @admin and @signedIn", field.Name)
return "admin"
case admin:
return "admin"
case signedIn:
return "signedIn"
}
return ""
}
func schemaUnderTest() *ast.Schema {
return NewExecutableSchema(Config{}).Schema()
}
// publicMutations is the complete list of mutations that anyone may call.
// A mutation is public only by being named here, so adding one to the schema
// without a directive fails TestEveryMutationIsGuarded until it is either
// guarded or deliberately listed.
//
// All three are how a session is obtained or given up, so they cannot require
// one: login checks a password, refreshToken checks the refresh cookie, and
// logout is a no-op for a visitor who is not signed in.
var publicMutations = []string{"login", "logout", "refreshToken"}
func TestEveryMutationIsGuarded(t *testing.T) {
schema := schemaUnderTest()
var seen []string
for _, field := range schema.Mutation.Fields {
if strings.HasPrefix(field.Name, "__") {
continue
}
seen = append(seen, field.Name)
guard := guardOf(t, field)
public := slices.Contains(publicMutations, field.Name)
switch {
case guard == "" && !public:
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
case guard != "" && public:
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
}
}
// A renamed or removed mutation must not leave a stale exemption behind.
for _, name := range publicMutations {
if !slices.Contains(seen, name) {
t.Errorf("publicMutations lists %s, which is not in the schema", name)
}
}
}
// The mutations that need only a session rather than an admin. Pinned so that
// loosening a mutation from @admin to @signedIn — which the test above would
// accept — has to be done here too.
func TestSignedInMutationsArePinned(t *testing.T) {
want := []string{"createPlace", "deletePlace", "updatePlace"}
var got []string
for _, field := range schemaUnderTest().Mutation.Fields {
if guardOf(t, field) == "signedIn" {
got = append(got, field.Name)
}
}
sort.Strings(got)
if !slices.Equal(got, want) {
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
}
}
// Queries are public by default — the home page is built from them — so the
// rule cannot be "every field is guarded". Instead the guarded set is pinned
// exactly: removing a directive from one of these, or adding a query that
// exposes private data without one, has to be a visible change to this map.
//
// Three queries are sensitive to who is asking without being in it, because
// they answer rather than refuse: `me` returns "unauthorized" itself,
// `messages` filters out private rows for non-admins, and
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
"user": "admin",
"places": "signedIn",
"layouts": "admin",
"components": "admin",
"coverLetters": "admin",
"coverSnippets": "admin",
"permissionTypes": "signedIn",
}
got := map[string]string{}
for _, field := range schemaUnderTest().Query.Fields {
if strings.HasPrefix(field.Name, "__") {
continue
}
if guard := guardOf(t, field); guard != "" {
got[field.Name] = guard
}
}
for name, guard := range want {
if got[name] != guard {
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
}
}
for name, guard := range got {
if _, ok := want[name]; !ok {
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
}
}
}
// The directives are FIELD_DEFINITION only and are meant for the two root
// types. One on an object's field would be enforced, but nothing above would
// notice it being removed, so keep them where the tests look.
func TestDirectivesOnlyOnRootFields(t *testing.T) {
schema := schemaUnderTest()
for name, def := range schema.Types {
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
continue
}
for _, field := range def.Fields {
if guardOf(t, field) != "" {
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
}
}
}
}
// execute runs one operation through the real executable schema, wired the
// way main wires it, and returns the response's error messages. The Store is
// empty: every operation below is refused, or returns, before its resolver
// would touch the database.
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
t.Helper()
srv := handler.New(NewExecutableSchema(Config{
Resolvers: &Resolver{Store: &handlers.Store{}},
Directives: Directives(),
}))
srv.AddTransport(transport.POST{})
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, req)
var resp struct {
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decoding response %s: %v", rec.Body, err)
}
var messages []string
for _, e := range resp.Errors {
messages = append(messages, e.Message)
}
return messages
}
// End to end: the message a client receives for a refused field is the bare
// string the resolvers used to return, with nothing wrapped around it.
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
cases := []struct {
name string
ctx context.Context
query string
want string
}{
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
{"non-admin admin query", withClaims(2, false), `{ users { id } }`, "admin access required"},
{"anonymous admin mutation", context.Background(), `mutation { deleteBookmark(id: 1) { id } }`, "admin access required"},
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
// Not a directive, and a different message on purpose.
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := execute(t, c.ctx, c.query, nil)
if !slices.Equal(got, []string{c.want}) {
t.Fatalf("errors = %q, want exactly %q", got, c.want)
}
})
}
}
// IDs: the wire form must be what it was when every type had a hand-written
// resolver returning int. Both marshallers write a quoted decimal string and
// both read a string or a number.
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
for _, id := range []uint{0, 1, 12, 4294967295} {
var asUint, asInt bytes.Buffer
graphql.MarshalUintID(id).MarshalGQL(&asUint)
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
if asUint.String() != asInt.String() {
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
}
}
if got := func() string {
var b bytes.Buffer
graphql.MarshalUintID(12).MarshalGQL(&b)
return b.String()
}(); got != `"12"` {
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
}
}
+28 -9
View File
@@ -9,8 +9,11 @@
// 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.
// types. A model's `ID uint` binds to `id: ID!` directly, because
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
// needed for it. A field resolver is only written where the Go type has
// no binding (Message.authorId and Rowing's time/distance are unsigned in
// Go and Int in the schema).
// - Resolvers reach the database and the third-party caches through
// Resolver.Store, the same handlers.Store the REST endpoints use.
// - context.go and middleware.go carry the caller's identity from Gin into
@@ -18,13 +21,29 @@
//
// 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.
// annotates the context and lets everything through. What guards a field is a
// directive on it in the schema:
//
// createUser(input: CreateUserInput!): User! @admin
// places: [Place!]! @signedIn
//
// @admin requires an admin's access token, @signedIn any valid one. Both are
// implemented once, in directives.go, and run before the resolver, so a
// guarded resolver contains no check of its own. A field with NEITHER
// directive is fully public.
//
// The rule of thumb in this schema is that queries are public and mutations
// are @admin, with these exceptions: login, logout and refreshToken are
// public; the places mutations and query are @signedIn; and the users
// queries are @admin (they are private data).
// directives_test.go holds that list and fails when the schema departs from
// it — in particular when a mutation is added with no directive.
//
// A directive is only a gate. Anything finer stays in the resolver and uses
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
// author, `me` answers for the caller (with its own "unauthorized" error),
// the messages query hides private messages from non-admins rather than
// refusing, and spotifyNeedsReauth is simply false for non-admins.
//
// The files ending in _helpers.go are hand-written and are not touched by
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
-15
View File
@@ -7,23 +7,13 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
return int(obj.ID), nil
}
// CreateFavorite is the resolver for the createFavorite field.
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&favorite).Error; err != nil {
return nil, err
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
}
return ptrs(favorites), nil
}
// Favorite returns FavoriteResolver implementation.
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
type favoriteResolver struct{ *Resolver }
+6293 -1368
View File
File diff suppressed because it is too large Load Diff
@@ -1,95 +0,0 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
return int(obj.ID), nil
}
// CreateJobAppReference is the resolver for the createJobAppReference field.
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
ref := models.JobAppReference{
Category: input.Category,
Label: input.Label,
Value: input.Value,
}
if input.SortOrder != nil {
ref.SortOrder = *input.SortOrder
}
if err := r.Store.DB.Create(&ref).Error; err != nil {
return nil, err
}
return &ref, nil
}
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var ref models.JobAppReference
if err := r.Store.DB.First(&ref, id).Error; err != nil {
return nil, err
}
if input.Category != nil {
ref.Category = *input.Category
}
if input.Label != nil {
ref.Label = *input.Label
}
if input.Value != nil {
ref.Value = *input.Value
}
if input.SortOrder != nil {
ref.SortOrder = *input.SortOrder
}
if err := r.Store.DB.Save(&ref).Error; err != nil {
return nil, err
}
return &ref, nil
}
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
if !IsAdminFromCtx(ctx) {
return false, fmt.Errorf("admin access required")
}
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
return false, err
}
return true, nil
}
// JobAppReferences is the resolver for the jobAppReferences field.
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
if !IsAdminFromCtx(ctx) {
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
}
return refs, nil
}
// JobAppReference returns JobAppReferenceResolver implementation.
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
type jobAppReferenceResolver struct{ *Resolver }
-144
View File
@@ -1,144 +0,0 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"fmt"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
)
// ID is the resolver for the id field.
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
return int(obj.ID), nil
}
// CreateJobApplication is the resolver for the createJobApplication field.
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// String! is non-null but not non-empty, and the columns are only
// `not null`, so "" stores happily and then never matches the email
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
jobTitle := strings.TrimSpace(input.JobTitle)
company := strings.TrimSpace(input.Company)
if jobTitle == "" || company == "" {
return nil, fmt.Errorf("jobTitle and company are required")
}
app := models.JobApplication{
JobTitle: jobTitle,
Company: company,
Location: input.Location,
URL: input.URL,
Status: services.NormalizeStatus(input.Status),
Notes: input.Notes,
AppliedAt: input.AppliedAt,
}
if err := r.Store.DB.Create(&app).Error; err != nil {
return nil, err
}
return &app, nil
}
// UpdateJobApplication is the resolver for the updateJobApplication field.
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
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.
// An explicit "" on a nullable column does clear it — that is how the UI
// empties a wrong URL or stale notes — but the same value on a required
// column is rejected rather than blanking a live row.
var app models.JobApplication
if err := r.Store.DB.First(&app, id).Error; err != nil {
return nil, err
}
if input.JobTitle != nil {
if strings.TrimSpace(*input.JobTitle) == "" {
return nil, fmt.Errorf("jobTitle cannot be empty")
}
app.JobTitle = strings.TrimSpace(*input.JobTitle)
}
if input.Company != nil {
if strings.TrimSpace(*input.Company) == "" {
return nil, fmt.Errorf("company cannot be empty")
}
app.Company = strings.TrimSpace(*input.Company)
}
if input.Location != nil {
app.Location = input.Location
}
if input.URL != nil {
app.URL = input.URL
}
if input.Status != nil {
app.Status = services.NormalizeStatus(*input.Status)
}
if input.Notes != nil {
app.Notes = input.Notes
}
if input.AppliedAt != nil {
app.AppliedAt = input.AppliedAt
}
if err := r.Store.DB.Save(&app).Error; err != nil {
return nil, err
}
return &app, nil
}
// DeleteJobApplication is the resolver for the deleteJobApplication field.
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
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
}
return true, nil
}
// 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
// id is the tie-break: one sync loop inserts several rows inside the same
// timestamp, and Postgres gives no stable order for equal sort keys, so
// without it the list can reshuffle between two identical page loads.
if err := r.Store.DB.Order("created_at desc, id desc").Find(&apps).Error; err != nil {
return nil, err
}
return apps, nil
}
// JobApplication is the resolver for the jobApplication field.
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var app models.JobApplication
if err := r.Store.DB.First(&app, id).Error; err != nil {
return nil, err
}
return &app, nil
}
// JobApplication returns JobApplicationResolver implementation.
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
type jobApplicationResolver struct{ *Resolver }
+147
View File
@@ -0,0 +1,147 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// BoxCount is the resolver for the boxCount field.
func (r *layoutResolver) BoxCount(ctx context.Context, obj *models.Layout) (int, error) {
// Decoded rather than stored, so it can never disagree with the boxes.
boxes, err := decodeLayoutBoxes(obj)
if err != nil {
return 0, err
}
return len(boxes), nil
}
// HasBackground is the resolver for the hasBackground field.
func (r *layoutResolver) HasBackground(ctx context.Context, obj *models.Layout) (bool, error) {
return obj.Background != nil, nil
}
// CreateLayout is the resolver for the createLayout field.
func (r *mutationResolver) CreateLayout(ctx context.Context, input model.CreateLayoutInput) (*models.Layout, error) {
// A snapshot of the page as it is now, adminOnly boxes included —
// which is why every layout field is @admin.
name, err := cleanLayoutName(input.Name)
if err != nil {
return nil, err
}
if !validPageKey(input.Page) {
return nil, errors.New("a layout needs a valid page")
}
taken, err := layoutNameTaken(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a layout with that name")
}
layout, empty, err := snapshotPage(r.Store.DB, input.Page, name)
if err != nil {
return nil, err
}
if empty {
return nil, errors.New("that page has nothing on it to save")
}
if err := r.Store.DB.Create(&layout).Error; err != nil {
return nil, err
}
return &layout, nil
}
// UpdateLayout is the resolver for the updateLayout field.
func (r *mutationResolver) UpdateLayout(ctx context.Context, id int, input model.UpdateLayoutInput) (*models.Layout, error) {
// Only the name changes: a layout is a snapshot, and saving the page
// again under a new name is how its content is refreshed.
var layout models.Layout
if err := r.Store.DB.First(&layout, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := cleanLayoutName(*input.Name)
if err != nil {
return nil, err
}
taken, err := layoutNameTaken(r.Store.DB, name, layout.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a layout with that name")
}
layout.Name = name
}
if err := r.Store.DB.Save(&layout).Error; err != nil {
return nil, err
}
return &layout, nil
}
// DeleteLayout is the resolver for the deleteLayout field.
func (r *mutationResolver) DeleteLayout(ctx context.Context, id int) (*models.Layout, error) {
// Pages it was loaded onto keep their boxes: they were copies.
var layout models.Layout
if err := r.Store.DB.First(&layout, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&layout).Error; err != nil {
return nil, err
}
return &layout, nil
}
// ApplyLayout is the resolver for the applyLayout field.
func (r *mutationResolver) ApplyLayout(ctx context.Context, id int, page string, replace bool) ([]*models.Box, error) {
// One transaction, so a replace that fails partway leaves the page as
// it was rather than half emptied.
var layout models.Layout
if err := r.Store.DB.First(&layout, id).Error; err != nil {
return nil, err
}
exists, err := canvasExists(r.Store.DB, page)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.New("there is no page at that address")
}
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
return applyLayoutTo(tx, &layout, page, replace)
})
if err != nil {
return nil, err
}
boxes, err := pageBoxes(r.Store.DB, page)
if err != nil {
return nil, err
}
if err := fillLinked(r.Store.DB, boxes); err != nil {
return nil, err
}
return ptrs(boxes), nil
}
// Layouts is the resolver for the layouts field.
func (r *queryResolver) Layouts(ctx context.Context) ([]*models.Layout, error) {
var layouts []models.Layout
if err := r.Store.DB.Order("created_at DESC").Find(&layouts).Error; err != nil {
return nil, err
}
return ptrs(layouts), nil
}
// Layout returns LayoutResolver implementation.
func (r *Resolver) Layout() LayoutResolver { return &layoutResolver{r} }
type layoutResolver struct{ *Resolver }
+275
View File
@@ -0,0 +1,275 @@
package graph
// Hand-written helpers for layout.resolvers.go, kept out of the resolver file
// for the same reason as box_helpers.go.
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const maxLayoutNameLen = 100
// layoutBox is one box as a layout stores it: what makes it look the way it
// does, without the id and page that tie a row to one canvas. Changing these
// field names would make older layouts load with the renamed fields empty.
type layoutBox struct {
Kind string `json:"kind"`
Widget *string `json:"widget,omitempty"`
HTML *string `json:"html,omitempty"`
Title *string `json:"title,omitempty"`
X int `json:"x"`
Y int `json:"y"`
W int `json:"w"`
H int `json:"h"`
Z int `json:"z"`
Framed bool `json:"framed"`
Shadow string `json:"shadow,omitempty"`
HideOnMobile bool `json:"hideOnMobile"`
AdminOnly bool `json:"adminOnly"`
// ComponentID is the component a linked box was linked to. HTML is
// stored too, so that a layout outlives the component: loading links the
// box again if the component is still there and uses HTML if not.
ComponentID *uint `json:"componentId,omitempty"`
}
type layoutBackground struct {
Color string `json:"color"`
Image string `json:"image"`
Fit string `json:"fit"`
}
// cleanLayoutName trims name and reports why it can't be a layout's name.
func cleanLayoutName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a layout needs a name")
}
if len(name) > maxLayoutNameLen {
return name, fmt.Errorf("a layout name is at most %d characters", maxLayoutNameLen)
}
return name, nil
}
// layoutNameTaken reports whether a live layout other than exceptID has this
// name. Checked up front, like slugTaken, so the admin gets a sentence rather
// than a constraint violation.
func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// canvasExists reports whether page is a canvas boxes can be put on: the
// landing page, or a live Page. Loading a layout onto any other key would
// leave its boxes where nothing shows them.
func canvasExists(db *gorm.DB, page string) (bool, error) {
if page == "index" {
return true, nil
}
if !validPageKey(page) {
return false, nil
}
var count int64
err := db.Model(&models.Page{}).Where("slug = ?", page).Count(&count).Error
return count > 0, err
}
// pageBoxes is every box on page, adminOnly ones included, in the order the
// boxes query returns them. Only for admin-only callers.
func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) {
var boxes []models.Box
err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error
return boxes, err
}
// snapshotPage is an unsaved Layout holding page's boxes and background as
// they are now. empty is true when there was nothing to keep.
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
boxes, err := pageBoxes(db, page)
if err != nil {
return layout, false, err
}
if err := fillLinked(db, boxes); err != nil {
return layout, false, err
}
stored := make([]layoutBox, len(boxes))
for i, b := range boxes {
stored[i] = layoutBox{
Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z,
Framed: b.Framed, Shadow: b.Shadow, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
ComponentID: b.ComponentID,
}
}
boxesJSON, err := json.Marshal(stored)
if err != nil {
return layout, false, err
}
layout = models.Layout{Name: name, SourcePage: page, Boxes: string(boxesJSON)}
var bg models.Background
err = db.Where("page = ?", page).First(&bg).Error
switch {
case err == nil:
bgJSON, err := json.Marshal(layoutBackground{Color: bg.Color, Image: bg.Image, Fit: bg.Fit})
if err != nil {
return layout, false, err
}
s := string(bgJSON)
layout.Background = &s
case !errors.Is(err, gorm.ErrRecordNotFound):
return layout, false, err
}
return layout, len(boxes) == 0 && layout.Background == nil, nil
}
func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
var boxes []layoutBox
if err := json.Unmarshal([]byte(layout.Boxes), &boxes); err != nil {
return nil, fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
}
return boxes, nil
}
// pageLabel is how a page key reads in a generated layout name.
func pageLabel(page string) string {
if page == "index" {
return "/"
}
return "/" + page
}
// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken.
func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
name := base
for n := 2; ; n++ {
taken, err := layoutNameTaken(db, name, 0)
if err != nil || !taken {
return name, err
}
name = fmt.Sprintf("%s (%d)", base, n)
}
}
// applyLayoutTo copies layout onto page inside tx; see applyLayout in
// layout.graphql for what replace does. The copies are new rows, so the page
// owns them outright.
func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error {
stored, err := decodeLayoutBoxes(layout)
if err != nil {
return err
}
// Added on top, the copies keep their own stacking order but all sit
// above what the page already has.
zShift := 0
if replace {
// What is being replaced is kept first, so a replace can be undone by
// loading that layout back. A page with nothing on it has nothing to
// keep.
name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s",
pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04")))
if err != nil {
return err
}
backup, empty, err := snapshotPage(tx, page, name)
if err != nil {
return err
}
if !empty {
if err := tx.Create(&backup).Error; err != nil {
return err
}
}
if err := tx.Where("page = ?", page).Delete(&models.Box{}).Error; err != nil {
return err
}
if err := tx.Where("page = ?", page).Delete(&models.Background{}).Error; err != nil {
return err
}
} else if len(stored) > 0 {
var top *int
if err := tx.Model(&models.Box{}).Where("page = ?", page).Select("MAX(z)").Scan(&top).Error; err != nil {
return err
}
if top != nil {
lowest := stored[0].Z
for _, b := range stored {
lowest = min(lowest, b.Z)
}
zShift = *top + 1 - lowest
}
}
live, err := liveComponents(tx, stored)
if err != nil {
return err
}
boxes := make([]models.Box, len(stored))
for i, b := range stored {
boxes[i] = models.Box{
Page: page, Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z + zShift,
Framed: b.Framed, Shadow: b.Shadow, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
}
if b.ComponentID != nil && live[*b.ComponentID] {
boxes[i].ComponentID = b.ComponentID
boxes[i].HTML = nil
}
if err := validateBox(&boxes[i]); err != nil {
return err
}
}
if len(boxes) > 0 {
if err := tx.Create(&boxes).Error; err != nil {
return err
}
}
// Adding on top leaves the page's own background alone.
if replace && layout.Background != nil {
var saved layoutBackground
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
return fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
}
bg, err := backgroundFrom(page, model.BackgroundInput{Color: saved.Color, Image: saved.Image, Fit: saved.Fit})
if err != nil {
return err
}
if err := tx.Create(&bg).Error; err != nil {
return err
}
}
return nil
}
// liveComponents is the set of components the stored boxes were linked to
// that still exist, so applyLayoutTo knows which boxes to link again.
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
var ids []uint
for _, b := range stored {
if b.ComponentID != nil {
ids = append(ids, *b.ComponentID)
}
}
live := map[uint]bool{}
if len(ids) == 0 {
return live, nil
}
var found []uint
if err := db.Model(&models.Component{}).Where("id IN ?", ids).Pluck("id", &found).Error; err != nil {
return nil, err
}
for _, id := range found {
live[id] = true
}
return live, nil
}
-5
View File
@@ -11,11 +11,6 @@ import (
"adam-french.co.uk/backend/models"
)
// ID is the resolver for the id field.
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
return int(obj.ID), nil
}
// 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.
+4 -3
View File
@@ -13,9 +13,10 @@ import (
// 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.
// is what lets public queries work and leaves every authorisation decision
// to the field being resolved — the @admin / @signedIn directives on it (see
// directives.go), or the resolver itself for anything finer. Both cookie and
// verify errors are swallowed for exactly that reason.
//
// It takes the database because validating a token means loading the user to
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
+94 -26
View File
@@ -12,6 +12,12 @@ type AuthPayload struct {
User *models.User `json:"user"`
}
type BackgroundInput struct {
Color string `json:"color"`
Image string `json:"image"`
Fit string `json:"fit"`
}
type CreateActivityInput struct {
Type string `json:"type"`
Name string `json:"name"`
@@ -24,27 +30,60 @@ type CreateBookmarkInput struct {
Link string `json:"link"`
}
type CreateBoxInput struct {
Page string `json:"page"`
Kind string `json:"kind"`
Widget *string `json:"widget,omitempty"`
HTML *string `json:"html,omitempty"`
Title *string `json:"title,omitempty"`
X *int `json:"x,omitempty"`
Y *int `json:"y,omitempty"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Z *int `json:"z,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
ComponentID *int `json:"componentId,omitempty"`
}
type CreateComponentInput struct {
Name string `json:"name"`
Title *string `json:"title,omitempty"`
HTML string `json:"html"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type CreateCoverLetterInput struct {
Name string `json:"name"`
Body string `json:"body"`
}
type CreateCoverSnippetInput struct {
Text string `json:"text"`
Section *string `json:"section,omitempty"`
}
type CreateFavoriteInput struct {
Type string `json:"type"`
Name string `json:"name"`
Link *string `json:"link,omitempty"`
}
type CreateJobAppReferenceInput struct {
Category string `json:"category"`
Label string `json:"label"`
Value string `json:"value"`
SortOrder *int `json:"sortOrder,omitempty"`
type CreateLayoutInput struct {
Name string `json:"name"`
Page string `json:"page"`
}
type CreateJobApplicationInput struct {
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location *string `json:"location,omitempty"`
URL *string `json:"url,omitempty"`
Status string `json:"status"`
Notes *string `json:"notes,omitempty"`
AppliedAt *time.Time `json:"appliedAt,omitempty"`
type CreatePageInput struct {
Slug string `json:"slug"`
Title string `json:"title"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type CreatePlaceInput struct {
@@ -130,21 +169,50 @@ type SteamStatus struct {
RecentGames []*SteamGame `json:"recentGames"`
}
type UpdateJobAppReferenceInput struct {
Category *string `json:"category,omitempty"`
Label *string `json:"label,omitempty"`
Value *string `json:"value,omitempty"`
SortOrder *int `json:"sortOrder,omitempty"`
type UpdateBoxInput struct {
Widget *string `json:"widget,omitempty"`
HTML *string `json:"html,omitempty"`
Title *string `json:"title,omitempty"`
X *int `json:"x,omitempty"`
Y *int `json:"y,omitempty"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Z *int `json:"z,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdateJobApplicationInput struct {
JobTitle *string `json:"jobTitle,omitempty"`
Company *string `json:"company,omitempty"`
Location *string `json:"location,omitempty"`
URL *string `json:"url,omitempty"`
Status *string `json:"status,omitempty"`
Notes *string `json:"notes,omitempty"`
AppliedAt *time.Time `json:"appliedAt,omitempty"`
type UpdateComponentInput struct {
Name *string `json:"name,omitempty"`
Title *string `json:"title,omitempty"`
HTML *string `json:"html,omitempty"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdateCoverLetterInput struct {
Name *string `json:"name,omitempty"`
Body *string `json:"body,omitempty"`
}
type UpdateCoverSnippetInput struct {
Text *string `json:"text,omitempty"`
Section *string `json:"section,omitempty"`
}
type UpdateLayoutInput struct {
Name *string `json:"name,omitempty"`
}
type UpdatePageInput struct {
Slug *string `json:"slug,omitempty"`
Title *string `json:"title,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdatePlaceInput struct {
+152
View File
@@ -0,0 +1,152 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// CreatePage is the resolver for the createPage field.
func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePageInput) (*models.Page, error) {
page := models.Page{
Slug: input.Slug,
Title: strings.TrimSpace(input.Title),
}
if input.AdminOnly != nil {
page.AdminOnly = *input.AdminOnly
}
if err := validateSlug(page.Slug); err != nil {
return nil, err
}
if page.Title == "" {
return nil, errors.New("a page needs a title")
}
taken, err := slugTaken(r.Store.DB, page.Slug, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a page at that address")
}
if err := r.Store.DB.Create(&page).Error; err != nil {
return nil, err
}
return &page, nil
}
// UpdatePage is the resolver for the updatePage field.
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
// Partial update, like updateBox. A new slug moves the page's boxes and
// background with it in the same transaction, since both find their page
// by slug.
var page models.Page
if err := r.Store.DB.First(&page, id).Error; err != nil {
return nil, err
}
oldSlug := page.Slug
if input.Slug != nil {
page.Slug = *input.Slug
}
if input.Title != nil {
page.Title = strings.TrimSpace(*input.Title)
}
if input.AdminOnly != nil {
page.AdminOnly = *input.AdminOnly
}
if page.Title == "" {
return nil, errors.New("a page needs a title")
}
if page.Slug != oldSlug {
if err := validateSlug(page.Slug); err != nil {
return nil, err
}
taken, err := slugTaken(r.Store.DB, page.Slug, page.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a page at that address")
}
}
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
if page.Slug != oldSlug {
if err := tx.Model(&models.Box{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
return err
}
if err := tx.Model(&models.Background{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
return err
}
}
return tx.Save(&page).Error
})
if err != nil {
return nil, err
}
return &page, nil
}
// DeletePage is the resolver for the deletePage field.
func (r *mutationResolver) DeletePage(ctx context.Context, id int) (*models.Page, error) {
// The boxes and background go too: left behind, they would reappear on
// any page later created at the same address.
var page models.Page
if err := r.Store.DB.First(&page, id).Error; err != nil {
return nil, err
}
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("page = ?", page.Slug).Delete(&models.Box{}).Error; err != nil {
return err
}
if err := tx.Where("page = ?", page.Slug).Delete(&models.Background{}).Error; err != nil {
return err
}
return tx.Delete(&page).Error
})
if err != nil {
return nil, err
}
return &page, nil
}
// Pages is the resolver for the pages field.
func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
// Public, for page indexes such as /shrines; adminOnly pages are only
// listed for an admin.
query := r.Store.DB.Order("slug ASC")
if !IsAdminFromCtx(ctx) {
query = query.Where("admin_only = ?", false)
}
var pages []models.Page
if err := query.Find(&pages).Error; err != nil {
return nil, err
}
return ptrs(pages), nil
}
// Page is the resolver for the page field.
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
// Null, not an error, for a missing page: the SPA's catch-all route asks
// this for every unknown path and shows its 404 on null. An adminOnly
// page reads as missing to everyone else, so its existence isn't leaked.
var page models.Page
err := r.Store.DB.Where("slug = ?", slug).First(&page).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
if page.AdminOnly && !IsAdminFromCtx(ctx) {
return nil, nil
}
return &page, nil
}
+73
View File
@@ -0,0 +1,73 @@
package graph
// Hand-written helpers for page.resolvers.go and box.resolvers.go, kept out
// of the resolver files for the same reason as box_helpers.go.
import (
"context"
"errors"
"regexp"
"strings"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// pageKeyPattern is the shape of a box's page key and of a page slug: lower
// case words joined by hyphens, in one or more /-separated segments. It is
// URL-safe as it stands, so the front end can use a slug as a path without
// escaping it.
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
const maxSlugLen = 100
// reservedFirstSegments are paths a page could never be reached at, because
// nginx or one of the SPA's own routes answers them first (see
// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the
// landing page's key "index", whose boxes a page of the same slug would
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
// pages under it and the home page /stp are all canvas pages.
var reservedFirstSegments = map[string]bool{
"stp2": true, "index": true, "admin": true, "cv": true,
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
"gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true,
"usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true,
"sound": true, "assets": true, "internal": true, "dozzle": true, "garage": true,
}
func validPageKey(key string) bool {
return len(key) <= maxSlugLen && pageKeyPattern.MatchString(key)
}
// validateSlug reports why slug can't be a page's address, or nil.
func validateSlug(slug string) error {
if !validPageKey(slug) {
return errors.New("a page address is lower-case letters, digits and hyphens, in /-separated parts, e.g. shrines/evangelion")
}
first, _, _ := strings.Cut(slug, "/")
if reservedFirstSegments[first] {
return errors.New("that address is already used by the site")
}
return nil
}
// pageHiddenFrom reports whether the page with this key is an adminOnly page
// and the caller is not an admin. A key with no Page row (the landing page,
// or a page that doesn't exist) is not hidden.
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
if IsAdminFromCtx(ctx) {
return false, nil
}
var count int64
err := db.Model(&models.Page{}).Where("slug = ? AND admin_only = ?", key, true).Count(&count).Error
return count > 0, err
}
// slugTaken reports whether a live page other than exceptID has this slug.
// Checked up front so the admin gets a sentence rather than a constraint
// violation; the partial unique index still backs it up.
func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error
return count > 0, err
}
+34
View File
@@ -0,0 +1,34 @@
package graph
import "testing"
func TestValidateSlug(t *testing.T) {
for _, c := range []struct {
slug string
ok bool
}{
{"notes-to-self", true},
{"shrines/evangelion", true},
{"shrines/neon-genesis/rei2", true},
{"", false},
{"Shrines/GTO", false}, // upper case
{"shrines/", false}, // empty segment
{"/shrines/gto", false}, // leading slash
{"shrines//gto", false}, // empty segment
{"shrines/gto-", false}, // trailing hyphen
{"shrines/../admin", false}, // dots
{"shrines", true}, // the index is a canvas page too
{"shrines/demoman", true}, // no longer an SPA route
{"admin/pages", false}, // under an SPA route
{"jobs/x", false}, // under an nginx route
{"stp", true}, // the home page is a canvas page too
{"stp2", false}, // an SPA route
{"index", false}, // the landing canvas's key
{"stp-fan-page", true}, // only whole segments are reserved
} {
err := validateSlug(c.slug)
if (err == nil) != c.ok {
t.Errorf("validateSlug(%q) = %v, want ok=%v", c.slug, err, c.ok)
}
}
}
+3 -25
View File
@@ -7,7 +7,6 @@ package graph
import (
"context"
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
@@ -16,11 +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")
}
// collaboratively edited list on the site, so the schema marks these
// fields @signedIn rather than @admin. There is no per-user ownership, so
// any signed-in user can edit or delete any place.
place := models.Place{
Title: input.Title,
Location: input.Location,
@@ -43,9 +40,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
// UpdatePlace is the resolver for the updatePlace field.
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
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
@@ -84,9 +78,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
// DeletePlace is the resolver for the deletePlace field.
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf("authentication required")
}
var place models.Place
if err := r.Store.DB.First(&place, id).Error; err != nil {
return nil, err
@@ -97,24 +88,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
return &place, nil
}
// ID is the resolver for the id field.
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
return int(obj.ID), nil
}
// Places is the resolver for the places field.
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
if _, ok := UserIDFromCtx(ctx); !ok {
return nil, fmt.Errorf("authentication required")
}
var places []models.Place
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
return nil, err
}
return ptrs(places), nil
}
// Place returns PlaceResolver implementation.
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
type placeResolver struct{ *Resolver }
+13 -24
View File
@@ -8,6 +8,7 @@ package graph
import (
"context"
"fmt"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
@@ -15,15 +16,20 @@ import (
// CreatePost is the resolver for the createPost field.
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
// @admin has already established that there is a session; the id is read
// here because the post needs an author, not as a second gate. The !ok
// branch is only reachable with a token that has admin but no usable id.
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
}
// The admin form submits whatever is in its fields, so an accidental click
// on an empty form would otherwise publish a blank post to the feed.
if strings.TrimSpace(input.Title) == "" {
return nil, fmt.Errorf("a post needs a title")
}
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
if err := r.Store.DB.Create(&post).Error; err != nil {
return nil, err
@@ -34,10 +40,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
// UpdatePost is the resolver for the updatePost field.
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -48,8 +50,9 @@ 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.
// Admin alone (the @admin on the field) is not enough: a post may only be
// edited by its author, so one admin cannot rewrite another's posts. This
// is the kind of rule a directive cannot express, so it stays here.
if post.AuthorID != userID {
return nil, fmt.Errorf("you can only update your own posts")
}
@@ -67,10 +70,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
// DeletePost is the resolver for the deletePost field.
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -95,11 +94,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
return &post, nil
}
// ID is the resolver for the id field.
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
return int(obj.ID), nil
}
// 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.
@@ -120,8 +114,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
}
return &post, nil
}
// Post returns PostResolver implementation.
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
type postResolver struct{ *Resolver }
+6 -4
View File
@@ -12,10 +12,12 @@ import "adam-french.co.uk/backend/handlers"
// 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.
// The generated code embeds *Resolver in per-type resolver structs, which is
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
// resolvers files. A type only gets one when a field of it needs a resolver:
// queryResolver and mutationResolver always, messageResolver and
// rowingResolver for their unsigned-to-Int fields. Most object types bind
// every field straight to the model and have none.
type Resolver struct {
Store *handlers.Store
}
-5
View File
@@ -20,11 +20,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
return ptrs(rows), nil
}
// ID is the resolver for the id field.
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
return int(obj.ID), nil
}
// 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.
+1 -1
View File
@@ -18,5 +18,5 @@ extend type Query {
}
extend type Mutation {
createActivity(input: CreateActivityInput!): Activity!
createActivity(input: CreateActivityInput!): Activity! @admin
}
+4
View File
@@ -7,10 +7,14 @@ type AuthPayload {
user: User!
}
# `me` carries no directive although it needs a session: it answers
# "unauthorized", not @signedIn's "authentication required", and the front end
# relies on that query failing quietly for an anonymous visitor.
extend type Query {
me: User
}
# Deliberately public: these are how a session is obtained and given up.
extend type Mutation {
login(input: LoginInput!): AuthPayload!
logout: Boolean!
+37
View File
@@ -0,0 +1,37 @@
# The background behind a canvas page, keyed by the same page key as its
# boxes ("index" for the landing page, or a Page's slug), so the landing
# page and every other canvas page are set the same way. Edited from the
# canvas's "Background" button; see models.Background.
#
# Anyone may read it, as part of the page, except that an adminOnly page's
# background is null to everyone but an admin.
type Background {
id: ID!
updatedAt: Time!
page: String!
# A CSS colour, or "" for the theme's page colour.
color: String!
# An image URL, or "" for none.
image: String!
# "cover", "contain" or "tile".
fit: String!
}
input BackgroundInput {
color: String!
image: String!
fit: String!
}
extend type Query {
# Null when the page has none, i.e. shows the theme's default.
background(page: String!): Background
}
extend type Mutation {
# Creates or replaces the page's background.
setBackground(page: String!, input: BackgroundInput!): Background! @admin
# Back to the theme's default. True if there was one to remove.
clearBackground(page: String!): Boolean! @admin
}
+2 -2
View File
@@ -18,6 +18,6 @@ extend type Query {
}
extend type Mutation {
createBookmark(input: CreateBookmarkInput!): Bookmark!
deleteBookmark(id: ID!): Bookmark!
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
deleteBookmark(id: ID!): Bookmark! @admin
}
+77
View File
@@ -0,0 +1,77 @@
# Boxes on a canvas page: the landing page (page "index") or an
# admin-created Page (page = its slug; the home page /stp is the Page "stp").
# Anyone may read a page's layout — it is the page — but only an admin may
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
# are px on a fixed 1400px-wide design canvas; see models.Box.
#
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
# componentId is linked to that Component: its html is the component's, and
# updateBox refuses to change it (component.graphql).
type Box {
id: ID!
createdAt: Time!
updatedAt: Time!
page: String!
kind: String!
widget: String
html: String
title: String
x: Int!
y: Int!
w: Int!
h: Int!
z: Int!
framed: Boolean!
# A CSS box-shadow value, or "" for none.
shadow: String!
hideOnMobile: Boolean!
adminOnly: Boolean!
componentId: ID
}
input CreateBoxInput {
page: String!
kind: String!
widget: String
html: String
title: String
x: Int
y: Int
w: Int
h: Int
z: Int
framed: Boolean
shadow: String
hideOnMobile: Boolean
adminOnly: Boolean
# Links the new box to this component; kind is then "html" and html is
# ignored.
componentId: ID
}
input UpdateBoxInput {
widget: String
html: String
title: String
x: Int
y: Int
w: Int
h: Int
z: Int
framed: Boolean
shadow: String
hideOnMobile: Boolean
adminOnly: Boolean
}
extend type Query {
boxes(page: String!): [Box!]!
}
extend type Mutation {
createBox(input: CreateBoxInput!): Box! @admin
updateBox(id: ID!, input: UpdateBoxInput!): Box! @admin
deleteBox(id: ID!): Box! @admin
}
+67
View File
@@ -0,0 +1,67 @@
# Components: named HTML boxes that can be placed on any canvas page, either
# as a copy (an ordinary box) or linked (a Box whose componentId is set).
# Linked boxes share only the html — editing a component changes every box
# linked to it — while title, geometry, frame and visibility stay each box's
# own. title, w, h, framed, shadow and adminOnly here are what a newly placed box
# starts with. See models.Component and graph/component_helpers.go.
#
# Admin only throughout, reads included, because a component may have been
# saved from an adminOnly note. A linked box's html still reaches visitors
# through the boxes query, which is the point.
type Component {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
title: String
html: String!
w: Int!
h: Int!
framed: Boolean!
shadow: String!
adminOnly: Boolean!
# How many boxes are linked to it.
uses: Int!
}
input CreateComponentInput {
name: String!
title: String
html: String!
w: Int
h: Int
framed: Boolean
shadow: String
adminOnly: Boolean
}
input UpdateComponentInput {
name: String
title: String
html: String
w: Int
h: Int
framed: Boolean
shadow: String
adminOnly: Boolean
}
extend type Query {
# By name.
components: [Component!]! @admin
}
extend type Mutation {
createComponent(input: CreateComponentInput!): Component! @admin
# A new html changes every box linked to it.
updateComponent(id: ID!, input: UpdateComponentInput!): Component! @admin
# Detaches every linked box first, giving each its own copy of the html, so
# no page changes.
deleteComponent(id: ID!): Component! @admin
# Makes html box `id` into a component named `name`, from its html, title,
# size, frame, shadow and adminOnly, and links the box to it. Answers with the box.
saveBoxAsComponent(id: ID!, name: String!): Box! @admin
# Gives linked box `id` its own copy of the component's html and unlinks it.
detachBox(id: ID!): Box! @admin
}
+60
View File
@@ -0,0 +1,60 @@
# Cover letters: saved letters from the /cv Cover Letter tab, and the bank of
# reusable paragraphs dragged into them. A letter's body is JSON the frontend
# owns (views/CV/coverLetter.js); the server only checks it is a JSON object
# of a sane size. See models.CoverLetter and graph/cover_letter_helpers.go.
#
# Admin only throughout, reads included: /cv is public, but the letters are
# drafts addressed to particular employers.
type CoverLetter {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
# The whole letter, as a JSON object.
body: String!
}
type CoverSnippet {
id: ID!
createdAt: Time!
text: String!
# The section title it was written for; "" for none. Only groups the bank.
section: String!
}
input CreateCoverLetterInput {
name: String!
body: String!
}
input UpdateCoverLetterInput {
name: String
body: String
}
input CreateCoverSnippetInput {
text: String!
section: String
}
input UpdateCoverSnippetInput {
text: String
section: String
}
extend type Query {
# Most recently updated first.
coverLetters: [CoverLetter!]! @admin
# By section, then newest first.
coverSnippets: [CoverSnippet!]! @admin
}
extend type Mutation {
createCoverLetter(input: CreateCoverLetterInput!): CoverLetter! @admin
updateCoverLetter(id: ID!, input: UpdateCoverLetterInput!): CoverLetter! @admin
deleteCoverLetter(id: ID!): CoverLetter! @admin
createCoverSnippet(input: CreateCoverSnippetInput!): CoverSnippet! @admin
updateCoverSnippet(id: ID!, input: UpdateCoverSnippetInput!): CoverSnippet! @admin
deleteCoverSnippet(id: ID!): CoverSnippet! @admin
}
+1 -1
View File
@@ -18,5 +18,5 @@ extend type Query {
}
extend type Mutation {
createFavorite(input: CreateFavoriteInput!): Favorite!
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
}
@@ -1,33 +0,0 @@
type JobAppReference {
id: ID!
createdAt: Time!
updatedAt: Time!
category: String!
label: String!
value: String!
sortOrder: Int!
}
input CreateJobAppReferenceInput {
category: String!
label: String!
value: String!
sortOrder: Int
}
input UpdateJobAppReferenceInput {
category: String
label: String
value: String
sortOrder: Int
}
extend type Query {
jobAppReferences: [JobAppReference!]!
}
extend type Mutation {
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
deleteJobAppReference(id: ID!): Boolean!
}
@@ -1,51 +0,0 @@
# 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!
updatedAt: Time!
jobTitle: String!
company: String!
location: String
url: String
status: String!
notes: String
appliedAt: Time
}
input CreateJobApplicationInput {
jobTitle: String!
company: String!
location: String
url: String
status: String!
notes: String
appliedAt: Time
}
input UpdateJobApplicationInput {
jobTitle: String
company: String
location: String
url: String
status: String
notes: String
appliedAt: Time
}
extend type Query {
jobApplications: [JobApplication!]!
jobApplication(id: ID!): JobApplication
}
extend type Mutation {
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
deleteJobApplication(id: ID!): Boolean!
}
+48
View File
@@ -0,0 +1,48 @@
# Saved layouts: a named copy of one canvas page's boxes and background,
# which can be loaded onto any canvas page — the landing page ("index") or a
# Page's slug. Loading copies: the new boxes belong to the target page, so
# editing a page afterwards never changes the layout or another page. Moving
# a layout is saving it on one page and loading it on another with
# replace: true. See models.Layout and graph/layout_helpers.go.
#
# Admin only throughout, reads included, because a layout keeps a page's
# adminOnly boxes along with the rest.
type Layout {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
# The page key it was saved from.
sourcePage: String!
boxCount: Int!
hasBackground: Boolean!
}
input CreateLayoutInput {
name: String!
# The page key to save, as it is now.
page: String!
}
input UpdateLayoutInput {
name: String
}
extend type Query {
# Newest first.
layouts: [Layout!]! @admin
}
extend type Mutation {
createLayout(input: CreateLayoutInput!): Layout! @admin
# Renames it; what a layout holds never changes after it is saved.
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
deleteLayout(id: ID!): Layout! @admin
# Copies the layout onto `page` and answers with that page's boxes.
# replace: false adds the copies on top of what is there, leaving the
# background alone. replace: true first saves the page as a layout named
# "<page> before <layout>, <time>", then swaps its boxes and background
# for the layout's.
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
}
+2 -1
View File
@@ -3,7 +3,8 @@
#
# 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.
# rather than causing an error — which is why the query has no @admin: the
# resolver makes that decision per row.
type Message {
id: ID!
+41
View File
@@ -0,0 +1,41 @@
# Admin-created canvas pages. A page is just a slug and a title; its content
# is the boxes whose `page` is the slug (see box.graphql). The SPA serves it
# at /<slug> through its catch-all route, so a slug may not start with a path
# the site already uses — see validateSlug in page_helpers.go.
#
# adminOnly pages, and their boxes, are invisible to everyone but an admin:
# `page` answers null and `pages` leaves them out.
type Page {
id: ID!
createdAt: Time!
updatedAt: Time!
slug: String!
title: String!
adminOnly: Boolean!
}
input CreatePageInput {
slug: String!
title: String!
adminOnly: Boolean
}
input UpdatePageInput {
slug: String
title: String
adminOnly: Boolean
}
extend type Query {
pages: [Page!]!
page(slug: String!): Page
}
extend type Mutation {
createPage(input: CreatePageInput!): Page! @admin
# Renaming a page moves its boxes with it.
updatePage(id: ID!, input: UpdatePageInput!): Page! @admin
# Deletes the page's boxes too.
deletePage(id: ID!): Page! @admin
}
+7 -6
View File
@@ -1,5 +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.
# Places to go. Unlike most mutations these require only a signed-in user
# (@signedIn), not an admin, and there is no per-user ownership: the list is
# shared. The query is guarded too — the list is not public.
type Place {
id: ID!
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
}
extend type Query {
places: [Place!]!
places: [Place!]! @signedIn
}
extend type Mutation {
createPlace(input: CreatePlaceInput!): Place!
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
deletePlace(id: ID!): Place!
createPlace(input: CreatePlaceInput!): Place! @signedIn
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
deletePlace(id: ID!): Place! @signedIn
}
+5 -3
View File
@@ -22,8 +22,10 @@ extend type Query {
post(id: ID!): Post
}
# @admin is only the first half of the rule for updatePost and deletePost:
# the resolver also requires the caller to be the post's author.
extend type Mutation {
createPost(input: CreatePostInput!): Post!
updatePost(id: ID!, input: UpdatePostInput!): Post!
deletePost(id: ID!): Post!
createPost(input: CreatePostInput!): Post! @admin
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
deletePost(id: ID!): Post! @admin
}
+17
View File
@@ -16,5 +16,22 @@
scalar Time
# Authorisation. There is no middleware in front of /graphql, so a field is
# PUBLIC unless it carries one of these. Each is implemented once, in
# graph/directives.go, and runs before the field's resolver:
#
# @admin the request must carry an admin's access token
# (error: "admin access required")
# @signedIn any valid access token will do
# (error: "authentication required")
#
# Every mutation needs one of them unless it is deliberately public (login,
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
# which queries are guarded. Rules that are not a plain gate stay in the
# resolver: a post is only editable by its author, `me` answers for whoever is
# signed in, and `messages` filters private rows rather than refusing.
directive @admin on FIELD_DEFINITION
directive @signedIn on FIELD_DEFINITION
type Query
type Mutation
+2 -1
View File
@@ -36,6 +36,7 @@ extend type Query {
spotifyRecent: [SpotifyRecentItem!]
# True only for an admin session while the backend lacks a Spotify client
# (OAuth never completed or the token was revoked), used by the Listening
# widget to offer a reconnect link. Everyone else gets false.
# widget to offer a reconnect link. Everyone else gets false — a soft
# check in the resolver, not @admin, so the home page query never errors.
spotifyNeedsReauth: Boolean!
}
+21 -5
View File
@@ -4,6 +4,17 @@ type User {
updatedAt: Time!
username: String!
admin: Boolean!
# Keys of the gated services this user may use (see PermissionType). Admins
# pass every permission check whatever this holds.
permissions: [String!]!
}
# One grantable service, from services.PermissionTypes: `key` is what is
# stored and what nginx gates on, `label` and `path` are for display.
type PermissionType {
key: String!
label: String!
path: String!
}
input CreateUserInput {
@@ -12,12 +23,17 @@ input CreateUserInput {
}
extend type Query {
users: [User!]!
user(id: ID!): User
users: [User!]! @admin
user(id: ID!): User @admin
# @signedIn rather than @admin: /account lists a non-admin's own services
# from it. The list itself is not a secret.
permissionTypes: [PermissionType!]! @signedIn
}
extend type Mutation {
createUser(input: CreateUserInput!): User!
deleteUser(id: ID!): User!
setUserAdmin(id: ID!, admin: Boolean!): User!
createUser(input: CreateUserInput!): User! @admin
deleteUser(id: ID!): User! @admin
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
# Replaces the user's whole permission list; unknown keys are rejected.
setUserPermissions(id: ID!, permissions: [String!]!): User! @admin
}
+2
View File
@@ -61,6 +61,8 @@ func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
return false, nil
}
// A soft check, deliberately not @admin: the directive would turn this
// into an error on the public home page query.
if !IsAdminFromCtx(ctx) {
return false, nil
}
+44 -28
View File
@@ -8,20 +8,19 @@ package graph
import (
"context"
"fmt"
"slices"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"golang.org/x/crypto/bcrypt"
)
// CreateUser is the resolver for the createUser field.
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
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.
// Only an existing admin can create accounts (@admin in the schema) —
// there is no public sign-up. New users are created non-admin;
// setUserAdmin promotes them.
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
return nil, err
@@ -37,10 +36,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
// DeleteUser is the resolver for the deleteUser field.
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
@@ -55,10 +50,6 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
// SetUserAdmin is the resolver for the setUserAdmin field.
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
callerID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
@@ -83,11 +74,43 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return &user, nil
}
// SetUserPermissions is the resolver for the setUserPermissions field.
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
// The whole list is replaced, so the admin panel sends every ticked box
// each time. An unknown key is refused rather than dropped, so a stale
// front end cannot silently save less than it showed. The stored list is
// rebuilt in registry order, which also drops duplicates.
want := map[string]bool{}
for _, key := range permissions {
if !services.ValidPermission(key) {
return nil, fmt.Errorf("unknown permission %q", key)
}
want[key] = true
}
granted := []string{}
for _, p := range services.PermissionTypes {
if want[p.Key] {
granted = append(granted, p.Key)
}
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
// No token bump needed: the permission gate reads this column on every
// request, so the change applies to the user's next one.
user.Permissions = granted
if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// Users is the resolver for the users field.
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var users []models.User
if err := r.Store.DB.Find(&users).Error; err != nil {
return nil, err
@@ -97,9 +120,6 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
// User is the resolver for the user field.
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
if !IsAdminFromCtx(ctx) {
return nil, fmt.Errorf("admin access required")
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
@@ -107,12 +127,8 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
return &user, nil
}
// ID is the resolver for the id field.
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
return int(obj.ID), nil
// PermissionTypes is the resolver for the permissionTypes field.
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
// A copy, so nothing downstream can write through to the registry.
return ptrs(slices.Clone(services.PermissionTypes)), nil
}
// User returns UserResolver implementation.
func (r *Resolver) User() UserResolver { return &userResolver{r} }
type userResolver struct{ *Resolver }
-178
View File
@@ -1,178 +0,0 @@
package handlers
import (
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
)
// This file backs the admin diagnostics panel: a configuration report and a
// log tail. Both are admin-only REST endpoints rather than GraphQL because
// they read the process environment and the filesystem — things outside the
// data model the GraphQL schema describes.
// ConfigVar describes one piece of configuration the backend can report on.
// Required marks vars whose absence visibly breaks a feature; Optional vars
// have a working default.
type ConfigVar struct {
Name string `json:"name"`
Purpose string `json:"purpose"`
Required bool `json:"required"`
}
// configVars is the checklist the panel renders. Sensitive values are never
// returned — only whether each var is present — so the endpoint cannot leak
// credentials even to an admin client.
var configVars = []ConfigVar{
{"POSTGRES_HOST", "Database connectivity", true},
{"POSTGRES_USER", "Database connectivity", true},
{"POSTGRES_PASSWORD", "Database connectivity", true},
{"POSTGRES_DB", "Database connectivity", true},
{"DOMAIN", "Site origin, JWT cookie domain", true},
{"AUTH_SECRET", "JWT signing", true},
{"SPOTIFY_CLIENT_ID", "Spotify listening widget", true},
{"SPOTIFY_CLIENT_SECRET", "Spotify listening widget", true},
{"SPOTIFY_REDIRECT_URI", "Spotify listening widget", true},
{"STEAM_API_KEY", "Steam status widget", false},
{"STEAM_ID", "Steam status widget", false},
{"CLAUDE_API_KEY", "Email summarisation", false},
{"EMAIL_BACKEND", "Email sync (graph/imap)", false},
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
{"MSGRAPH_REDIRECT_URI", "Email sync (Microsoft Graph)", false},
{"MSGRAPH_TENANT_ID", "Email sync (Microsoft Graph)", false},
{"IMAP_HOST", "Email sync (IMAP fallback)", false},
{"IMAP_EMAIL", "Email sync (IMAP fallback)", false},
{"IMAP_PASSWORD", "Email sync (IMAP fallback)", false},
{"GITEA_HOST", "Gitea activity feed", false},
{"GITEA_PORT", "Gitea activity feed", false},
{"JWT_COOKIE_SECURE", "Cookie security in dev", false},
{"ICECAST_URL", "Radio queue widget", false},
}
// ConfigCheck backs GET /admin/config. It reports one entry per known var:
// set or empty, plus the value only for vars flagged non-sensitive (none of
// the credentials are). A var not in the list at all is not reported — the
// point is a checklist, not a full env dump.
func (store *Store) ConfigCheck(ctx *gin.Context) {
type entry struct {
ConfigVar
Set bool `json:"set"`
Value string `json:"value,omitempty"`
Secret bool `json:"secret"`
}
// Vars whose *value* may come back (bad values like "consumers" are fine;
// they contain no credential).
visible := map[string]bool{
"EMAIL_BACKEND": true,
"MSGRAPH_TENANT_ID": true,
"ICECAST_URL": true,
"STEAM_ID": true,
}
// Explicitly-credentialled vars get the secret badge so the panel can
// label them "present" instead of showing a masked string.
secrets := map[string]bool{
"POSTGRES_PASSWORD": true,
"AUTH_SECRET": true,
"SPOTIFY_CLIENT_SECRET": true,
"MSGRAPH_CLIENT_SECRET": true,
"CLAUDE_API_KEY": true,
"STEAM_API_KEY": true,
"IMAP_PASSWORD": true,
}
result := make([]entry, 0, len(configVars))
for _, v := range configVars {
val := os.Getenv(v.Name)
e := entry{ConfigVar: v, Set: strings.TrimSpace(val) != "", Secret: secrets[v.Name]}
if e.Set && visible[v.Name] {
e.Value = val
}
result = append(result, e)
}
ctx.JSON(http.StatusOK, gin.H{"vars": result})
}
// logTailBytes and logTailLines bound how much of the log file one request
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
// cheap even on the Pi.
const (
logTailBytes = 256 << 10
logTailLines = 500
)
// Logs backs GET /admin/logs. It returns the tail of the backend's own log
// file (go.log — Gin traffic plus application log lines), which lives on the
// bind-mounted ./logs volume.
//
// Why tail and not offer a range: the panel wants "what happened recently",
// and the file can grow unboundedly between rotations, so anything else
// invites reading the whole thing into memory.
func (store *Store) Logs(ctx *gin.Context) {
lines, size, err := tailLogFile(logPath)
if err != nil {
// The mount being absent is a deployment problem worth surfacing
// distinctly from "log file empty".
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size})
}
// logPath matches the file main.go opens for gin.DefaultWriter.
const logPath = "/backend/logs/go.log"
// tailLogFile returns the last logTailLines lines of a file, reading at most
// logTailBytes from the end. Split out from the handler so the offset and
// partial-line rules are testable without a filesystem mount.
func tailLogFile(path string) ([]string, int64, error) {
f, err := os.Open(path)
if err != nil {
return nil, 0, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, 0, err
}
// Read from near the end rather than head-to-toe so the read stays
// constant-size regardless of how old the file is.
start := int64(0)
if info.Size() > logTailBytes {
start = info.Size() - logTailBytes
}
buf := make([]byte, info.Size()-start)
if len(buf) > 0 {
if _, err := f.ReadAt(buf, start); err != nil {
return nil, 0, err
}
}
// Starting mid-file almost certainly lands mid-line; drop that fragment
// so the panel never renders a truncated first entry.
text := string(buf)
if start > 0 {
if i := strings.IndexByte(text, '\n'); i >= 0 {
text = text[i+1:]
}
}
text = strings.TrimRight(text, "\n")
if text == "" {
return []string{}, info.Size(), nil
}
lines := strings.Split(text, "\n")
if len(lines) > logTailLines {
lines = lines[len(lines)-logTailLines:]
}
return lines, info.Size(), nil
}
-76
View File
@@ -1,76 +0,0 @@
package handlers
import (
"os"
"path/filepath"
"strings"
"testing"
)
// tailLogFile's rules that are easy to get wrong: the line cap, and dropping
// the partial first line when the read started mid-file.
func writeLog(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "go.log")
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("writing fixture: %v", err)
}
return path
}
func TestTailLogFileCapsLines(t *testing.T) {
var b strings.Builder
for range logTailLines + 50 {
b.WriteString("line\n")
}
lines, _, err := tailLogFile(writeLog(t, b.String()))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) != logTailLines {
t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines)
}
}
func TestTailLogFileDropsPartialFirstLine(t *testing.T) {
// A file larger than the byte window: the read starts mid-file, so the
// first line it sees is a fragment and must be discarded.
filler := strings.Repeat("x", 100) + "\n"
var b strings.Builder
for b.Len() < logTailBytes+len(filler) {
b.WriteString(filler)
}
b.WriteString("FINAL\n")
lines, _, err := tailLogFile(writeLog(t, b.String()))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) == 0 {
t.Fatal("expected some lines")
}
if lines[len(lines)-1] != "FINAL" {
t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1])
}
// Every surviving line must be whole, i.e. a full filler line.
if got := lines[0]; got != strings.TrimSuffix(filler, "\n") {
t.Fatalf("first line = %q, want a complete filler line", got)
}
}
func TestTailLogFileEmpty(t *testing.T) {
lines, size, err := tailLogFile(writeLog(t, ""))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) != 0 || size != 0 {
t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size)
}
}
func TestTailLogFileMissing(t *testing.T) {
if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil {
t.Fatal("expected an error for a missing log file")
}
}
+72 -36
View File
@@ -93,51 +93,86 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
}
// 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.
// decide whether to show admin UI, nginx's admin gate calls as an
// auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
// new cookie pair as a side effect, so a returning admin is recognised
// without a visible re-login.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
accessToken, err := ctx.Cookie("access_token")
if err != nil {
// No access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// On the access-token path admin is read from the token, as
// everywhere else; on the refresh path there is no admin claim, and
// the row is what makes that path pick up a revoked admin flag.
if claims == nil {
return user.Admin
}
return
}
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err != nil {
// Expired, invalid or revoked access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
}
return
}
admin, ok := (*claims)["admin"].(bool)
if !ok || !admin {
ctx.Status(http.StatusForbidden)
return
}
ctx.Status(http.StatusOK)
admin, ok := (*claims)["admin"].(bool)
return ok && admin
})
}
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
// ValidatePermission backs GET /auth/validate/:permission, nginx's permission
// gate (see services/permissions.go). Same bare-status contract and refresh
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in an nginx location fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The 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.
// The decision reads the user row, not the token, for admins as well: a
// grant, a revoke or a demotion applies on the very next request.
func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission")
if !services.ValidPermission(key) {
ctx.Status(http.StatusNotFound)
return
}
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
return services.HasPermission(user, key)
})
}
// validateSession is the body shared by the two validate endpoints: identify
// the caller from the access token, or failing that the refresh token, and
// answer 200 / 403 / 401 according to allow.
//
// 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 {
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which nginx can lift with
// auth_request_set and hand to the service behind the gate, so that service
// knows who is using it without having accounts of its own.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err == nil {
if !allow(user, claims) {
ctx.Status(http.StatusForbidden)
return
}
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return
}
}
// No access token, or an expired, invalid or revoked one — try refreshing.
if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized)
}
}
// tryRefreshAndValidate re-authenticates from the refresh token.
//
// The bool does not mean "allowed" — it means "this function already wrote
// the response". It returns true both for a successful refresh (200, new
// cookies set) and for a valid but unauthorised user (403, no new cookies),
// and false only when it could not decide, leaving the caller to send 401.
// Getting this backwards would send two status codes for one request.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
@@ -150,7 +185,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
return false
}
if !user.Admin {
if !allow(user, nil) {
ctx.Status(http.StatusForbidden)
return true
}
@@ -162,6 +197,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
store.setAuthCookies(ctx, tokens)
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return true
}
-61
View File
@@ -1,61 +0,0 @@
package handlers
import (
"log"
"net/http"
"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
}
err := store.EmailSync.SyncEmails(ctx.Request.Context())
if err != nil {
log.Printf("[EmailSync] Manual sync error: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
return
}
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"})
return
}
code := ctx.Query("code")
if code == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
return
}
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
log.Printf("[EmailSync] Auth completion error: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
}
-178
View File
@@ -1,178 +0,0 @@
package handlers
import (
"crypto/rand"
"encoding/hex"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Attachment upload for the chat.
//
// Files land in one of two directories. /backend/uploads/ is served by nginx
// at /uploads/ with no authentication, so anything written there is publicly
// reachable by URL — which is why the extension and content checks below
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
// messages and is served at /uploads/private/ behind an nginx auth_request
// gate; only an admin may upload there.
// 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/",
}
// publicUploadDir and privateUploadDir are the two destinations; the private
// one is created on demand because nothing else guarantees it exists.
const (
publicUploadDir = "/backend/uploads/"
privateUploadDir = "/backend/uploads/private/"
)
// UploadMessageFile backs POST /messages/upload (login required) and returns
// the URL of the stored file, which the client then sends over the WebSocket
// as a message's fileUrl.
//
// The multipart form takes an optional "private" field: "true" stores the file
// under /uploads/private/ for use as a private message's attachment. That is
// admin-only, because private messages themselves are — an attachment URL
// leaking out is the same disclosure as the message leaking out.
func (store *Store) UploadMessageFile(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
const maxSize = 10 << 20 // 10MB
if file.Size > maxSize {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowedExtensions[ext] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed"})
return
}
// Validate actual content type matches extension
f, err := file.Open()
if err != nil {
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()
if err != nil && n == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file content"})
return
}
detectedType := http.DetectContentType(buf[:n])
expectedPrefix, ok := extensionToMIMEPrefix[ext]
if ok && !strings.HasPrefix(detectedType, expectedPrefix) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file content does not match extension"})
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"})
return
}
filename := hex.EncodeToString(b) + ext
uploadDir := publicUploadDir
urlPrefix := "/uploads/"
if private {
uploadDir = privateUploadDir
urlPrefix = "/uploads/private/"
// 0755 so nginx (a different user) can traverse the directory to
// serve the files once its auth_request gate has approved.
if err := os.MkdirAll(uploadDir, 0755); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
}
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"})
return
}
defer src.Close()
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
defer out.Close()
if _, err := io.Copy(out, src); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+47 -59
View File
@@ -2,8 +2,6 @@ package handlers
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"log"
@@ -13,7 +11,6 @@ import (
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/anthropics/anthropic-sdk-go"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
@@ -22,15 +19,40 @@ import (
// the admin uploads a photo of the rowing machine display and Claude reads the
// numbers off it. The session date comes from the photo's EXIF metadata, which
// also doubles as the deduplication key.
//
// The Claude call itself lives in the Python service (python/app/rowing.py),
// reached directly over the Docker network. Everything that needs the session
// or the database — the admin gate, EXIF, the duplicate check, the sanity
// bounds, the insert — stays here.
// ExtractedRowingData is the JSON contract for what Claude reads off the
// display; the keys must match the prompt in CreateRowing.
// display: the body of the Python service's reply, whose keys are the ones
// its prompt asks the model for (RowingReading in python/app/rowing.py).
type ExtractedRowingData struct {
TimeMinutes uint64 `json:"timeMinutes"`
TimeSeconds uint64 `json:"timeSeconds"`
Distance uint64 `json:"distance"`
}
// rowingReadPath is the Python route. It is internal: nginx refuses
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
// only way in is the direct container-to-container call services.CallPython
// makes.
const rowingReadPath = "/internal/rowing/read"
// readRowingDisplay sends the image to the Python service and returns what
// Claude read off it. No plausibility checking happens on either side of this
// call; that is CreateRowing's job. A failure the reader described in its own
// words comes back as a *services.PythonError (see services.CallPython).
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
// Data is a []byte so that it is sent as standard base64, the encoding
// the Anthropic API expects.
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
MediaType string `json:"media_type"`
Data []byte `json:"data"`
}{mediaType, image})
}
// GetRowing backs the public GET /rowing with every logged session, newest
// first.
func (store *Store) GetRowing(ctx *gin.Context) {
@@ -47,9 +69,10 @@ func (store *Store) GetRowing(ctx *gin.Context) {
// 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.
// distance (via the Python service), sanity-checks the result and stores a
// session.
//
// Note it is admin-gated and calls a paid API once per request, so the
// Note it is admin-gated and costs a paid API call once per request, so the
// validation below exists to catch misreadings rather than hostile input.
func (store *Store) CreateRowing(ctx *gin.Context) {
file, err := ctx.FormFile("image")
@@ -81,16 +104,17 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
// exif.Decode consumed part of the stream, so rewind before reading the
// bytes to send to Claude.
// bytes to send on for reading.
if _, err := f.Seek(0, io.SeekStart); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
return
}
// Cap the upload before buffering it (and then base64-encoding it, 1.33x
// bigger): the route is admin-only but an unbounded read would still let
// a giant file exhaust the Pi's memory and produce a huge paid API call.
// 10MB is well above any photo this endpoint is meant to take.
// bigger, on its way to the Python service): the route is admin-only but
// an unbounded read would still let a giant file exhaust the Pi's memory
// and produce a huge paid API call. 10MB is well above any photo this
// endpoint is meant to take; the Python side's own limit is sized from it.
if file.Size > 10<<20 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
return
@@ -110,13 +134,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
// 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.
// keep the API call well-formed rather than to police the file. The
// Python service enforces the same list; checking here first gives the
// admin a clear 400 instead of that side's validation error.
mediaType := file.Header.Get("Content-Type")
if !allowedMediaTypes[mediaType] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
return
}
encoded := base64.StdEncoding.EncodeToString(data)
// 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
@@ -137,55 +162,18 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return
}
// Build the message with an image + text prompt
message, err := store.ClaudeClient.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeHaiku4_5,
MaxTokens: 256,
Messages: []anthropic.MessageParam{
{
Role: "user",
Content: []anthropic.ContentBlockParamUnion{
// Image block
anthropic.NewImageBlock(anthropic.Base64ImageSourceParam{
Type: "base64",
MediaType: anthropic.Base64ImageSourceMediaType(mediaType),
Data: encoded,
}),
// Text prompt requesting exactly 2 variables
anthropic.NewTextBlock(
`Look at this rowing machine display. Extract the total elapsed time and total distance.
Return ONLY a JSON object with these exact keys and numeric values:
- "timeMinutes": total minutes (e.g. 2:30 = 2)
- "timeSeconds": total seconds (e.g. 2:30 = 30)
- "distance": distance in meters as a number (e.g. 5000)
No text, no markdown, no explanation. Just the JSON object.`),
},
},
},
})
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to process image"})
return
}
if len(message.Content) == 0 {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "empty response from image processor"})
return
}
// Strip a markdown code fence if the model wrapped its JSON in one
// despite the prompt; shared with the email pipeline, which asks for bare
// JSON in the same way and gets fenced output just as often.
extractedData := ExtractedRowingData{}
raw := services.StripMarkdownFence(message.Content[0].Text)
err = json.Unmarshal([]byte(raw), &extractedData)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse image data"})
// The reader's own messages ("failed to parse image data", ...) are
// passed on; anything else is a plumbing failure the admin can do
// nothing with.
msg := "failed to process image"
var readErr *services.PythonError
if errors.As(err, &readErr) {
msg = readErr.Detail
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
return
}
+96
View File
@@ -0,0 +1,96 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"adam-french.co.uk/backend/services"
)
// readRowingDisplay is the Go half of the contract with the Python service's
// /internal/rowing/read. CreateRowing itself needs a database and a real
// multipart photo with EXIF, so what is covered is the call: the request the
// Python side receives, and how each kind of reply comes back.
func rowingReader(t *testing.T, handler http.HandlerFunc) *Store {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return &Store{PythonURL: srv.URL}
}
func TestReadRowingDisplayRequestAndReply(t *testing.T) {
var got struct {
MediaType string `json:"media_type"`
Data string `json:"data"`
}
var path string
var forwarded bool
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
// The Python route treats either header as "came through nginx" and
// answers 404, so this call must never carry them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Errorf("decoding request: %v", err)
}
w.Write([]byte(`{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}`))
})
data, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("hello"))
if err != nil {
t.Fatalf("readRowingDisplay: %v", err)
}
if data != (ExtractedRowingData{TimeMinutes: 20, TimeSeconds: 5, Distance: 5000}) {
t.Fatalf("got %+v", data)
}
if path != rowingReadPath {
t.Fatalf("path = %q, want %q", path, rowingReadPath)
}
if forwarded {
t.Fatal("request carried a proxy header the Python route rejects")
}
// "hello" in standard base64, the encoding the Anthropic API expects.
if got.MediaType != "image/jpeg" || got.Data != "aGVsbG8=" {
t.Fatalf("request body = %+v", got)
}
}
func TestReadRowingDisplayErrors(t *testing.T) {
cases := []struct {
name string
status int
body string
wantDetail string // non-empty: a services.PythonError with this message
}{
{"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
{"non-JSON 502 is not relayed", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
{"malformed success body", http.StatusOK, `not json`, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
w.Write([]byte(c.body))
})
_, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("x"))
if err == nil {
t.Fatal("expected an error")
}
var readErr *services.PythonError
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
t.Fatalf("relayed = %v, err = %v", relayed, err)
}
if readErr != nil && readErr.Detail != c.wantDetail {
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
}
})
}
}
+89
View File
@@ -0,0 +1,89 @@
package handlers
import (
"errors"
"log"
"net/http"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Upload backs POST /uploads (login required): the one endpoint the frontend
// stores a file through (vue/src/uploads.js). Multipart form:
//
// file the file (required)
// private "true" to store it as an admin-only chat attachment
//
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
// the file was refused (wrong type, too large) and 500 when storing failed.
// Validation, naming and storage are all services.Uploads.Save; this handler
// only reads the form and decides who may use `private`.
//
// `private` is admin-only because private messages themselves are: an
// attachment URL leaking out is the same disclosure as the message leaking.
func (store *Store) Upload(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
url, err := store.Uploads.Save(ctx.Request.Context(), file, private)
var rejected *services.UploadError
switch {
case errors.As(err, &rejected):
ctx.JSON(http.StatusBadRequest, gin.H{"error": rejected.Message})
case err != nil:
log.Printf("[upload] storing %s failed: %v", file.Filename, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
default:
ctx.JSON(http.StatusOK, gin.H{"url": url})
}
}
// ListUploads backs GET /uploads (admin): every public upload, newest first,
// for the upload picker on the canvas pages (vue/src/components/util/
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
//
// Admin-only because the listing is the one thing that turns unguessable
// upload URLs into known ones; see services.Uploads.List.
func (store *Store) ListUploads(ctx *gin.Context) {
files, err := store.Uploads.List(ctx.Request.Context())
if err != nil {
log.Printf("[upload] listing failed: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list uploads"})
return
}
if files == nil {
files = []services.StoredFile{} // [] rather than null for the frontend
}
ctx.JSON(http.StatusOK, gin.H{"files": files})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+40 -58
View File
@@ -14,23 +14,22 @@ import (
// What is deliberately NOT covered here, and why:
//
// - Every handler method (Login, UploadMessageFile, the radio file movers,
// - Every handler method (Login, Upload, the radio file movers,
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
// multipart request, the container's /backend/... directories, or a paid
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
// CI.
// - The radio/chat upload filename sanitisation itself. It is written inline
// inside the handler bodies rather than in a helper, so testing it would
// mean either driving a full multipart upload against the real upload
// directories or refactoring production code. Neither was in scope, so the
// part that *is* extractable — the extension allow-lists those handlers
// gate on — is covered as a table contract below instead.
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
// reach the database on the refresh path.
// - The radio upload's filename sanitisation. It is written inline in the
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
// the upload allow-list tables.
// the radio allow-list.
// --- Spotify OAuth CSRF nonces -------------------------------------------
@@ -253,57 +252,40 @@ func TestRequestIsAdmin(t *testing.T) {
}
}
// The allow-list tables are the upload trust boundary's data. Testing them as
// data catches the realistic failure: someone adding an executable or markup
// extension, or adding an extension to the MIME map without allowing it (which
// would be dead configuration).
func TestUploadAllowLists(t *testing.T) {
t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) {
// Served by nginx from a public directory with no auth, so anything
// the browser will execute or render as markup must not be storable.
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} {
if allowedExtensions[ext] {
t.Errorf("%q must not be an allowed chat upload extension", ext)
}
}
})
// --- Permission gate ------------------------------------------------------
t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) {
// The handlers look up strings.ToLower(filepath.Ext(...)), so a key in
// any other shape is unreachable.
for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} {
for ext := range m {
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
}
// An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in an nginx
// location shows up as a 404 rather than as a missing grant.
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Store{}
for _, key := range []string{"no-such-service", "admin", ""} {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "permission", Value: key}}
ctx.Request = httptest.NewRequest("GET", "/auth/validate/"+key, nil)
s.ValidatePermission(ctx)
if ctx.Writer.Status() != 404 {
t.Errorf("key %q: status %d, want 404", key, ctx.Writer.Status())
}
})
}
}
t.Run("every MIME-checked extension is also allowed", func(t *testing.T) {
for ext := range extensionToMIMEPrefix {
if !allowedExtensions[ext] {
t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext)
}
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
func TestRadioAllowList(t *testing.T) {
for ext := range allowedAudioExtensions {
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
// any other shape is unreachable.
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
})
t.Run("audio extensions are content-unverified by design", func(t *testing.T) {
// http.DetectContentType is unreliable for these, so a missing entry
// means "extension allowed, content not verified". Adding one would
// start rejecting legitimate uploads.
for _, ext := range []string{".mp3", ".ogg"} {
if _, ok := extensionToMIMEPrefix[ext]; ok {
t.Errorf("%q should not be MIME-checked", ext)
}
}
})
t.Run("radio allow-list is audio only", func(t *testing.T) {
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
}
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
})
}
}
+9 -3
View File
@@ -8,7 +8,6 @@ import (
"time"
"adam-french.co.uk/backend/services"
"github.com/anthropics/anthropic-sdk-go"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
"gorm.io/gorm"
@@ -30,11 +29,18 @@ type Store struct {
DB *gorm.DB
SpotifyAuth *spotifyauth.Authenticator
SpotifyClient *spotify.Client
ClaudeClient *anthropic.Client
Auth *services.Auth
Notes *services.Notes
LoginLimiter *services.RateLimiter
EmailSync *services.EmailSyncService
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string
// Stores uploaded files and says where they are served
// (services.Uploads.Save). Used by the Upload handler.
Uploads *services.Uploads
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
+50 -51
View File
@@ -1,7 +1,6 @@
package main
import (
"context"
"fmt"
"io"
"log"
@@ -27,8 +26,9 @@ import (
// 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.
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
// directives in its schema instead of by middleware. See backend/README.md
// for the wider picture.
func main() {
// Logs go to both stdout (so `docker compose logs` works) and a file in a
// mounted volume (so they survive the container).
@@ -89,10 +89,10 @@ func main() {
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
// CLAUDE
claudeAPIKey := os.Getenv("CLAUDE_API_KEY")
claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey}
claudeClient := services.InitClaude(&claudeConfig)
// No Claude client here: the site's one Claude call, the rowing photo
// reader, is made by the Python service, which is the only container of
// the site's own that reads CLAUDE_API_KEY. The backend reaches it at
// pythonURL, below. (The job tracker, a separate container, makes its own.)
authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
@@ -114,37 +114,41 @@ func main() {
steamAPIKey := os.Getenv("STEAM_API_KEY")
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 {
emailSyncInterval = parsed
}
// PYTHON SERVICE
// Called directly over the Docker network, not through nginx, for its
// /internal/ Claude route (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" {
pythonHost = "python"
}
emailSyncConfig := services.EmailSyncConfig{
Backend: os.Getenv("EMAIL_BACKEND"),
ClientID: os.Getenv("MSGRAPH_CLIENT_ID"),
ClientSecret: os.Getenv("MSGRAPH_CLIENT_SECRET"),
TenantID: os.Getenv("MSGRAPH_TENANT_ID"),
RedirectURI: os.Getenv("MSGRAPH_REDIRECT_URI"),
IMAP: &services.IMAPConfig{
Host: os.Getenv("IMAP_HOST"),
Port: os.Getenv("IMAP_PORT"),
Email: os.Getenv("IMAP_EMAIL"),
Password: os.Getenv("IMAP_PASSWORD"),
},
SyncInterval: emailSyncInterval,
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
pythonPort := os.Getenv("PYTHON_PORT")
if pythonPort == "" {
pythonPort = "8000"
}
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// UPLOADS
// Public uploads go to the Garage bucket (and to the shared `uploads`
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
// private ones to the volume. See services/uploads.go. Region and bucket
// default to what garage/garage.toml and garage/bootstrap.sh set up.
s3Region := os.Getenv("S3_REGION")
if s3Region == "" {
s3Region = "garage"
}
s3Bucket := os.Getenv("S3_BUCKET")
if s3Bucket == "" {
s3Bucket = "uploads"
}
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
// 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}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
@@ -163,10 +167,7 @@ func main() {
r.GET("/auth/check", store.CheckToken)
r.POST("/auth/logout", store.Logout)
r.GET("/auth/validate-admin", store.ValidateAdmin)
// EMAIL SYNC
r.GET("/email/callback", store.CompleteEmailAuth)
admin.POST("/email/sync", store.TriggerEmailSync)
r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY
// The callback must be open — Spotify redirects a logged-out browser to
@@ -189,24 +190,29 @@ func main() {
// /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)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile)
// ADMIN DIAGNOSTICS: env-var checklist and log tail for the admin panel.
admin.GET("/admin/config", store.ConfigCheck)
admin.GET("/admin/logs", store.Logs)
// 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.
// Note the whole API is one POST route with no middleware guard.
// Authorisation is declared in the schema instead: a field marked @admin
// or @signedIn is refused by the matching function in graph.Directives()
// before its resolver runs. A field with neither is PUBLIC, so a new
// mutation needs one — graph/directives_test.go fails until it has one or
// is added to the list of deliberately public fields there.
//
// Directives must stay wired here: gqlgen fails closed on a nil directive
// (the field errors with "directive admin is not implemented"), so
// dropping this line breaks every guarded field rather than opening it.
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
Resolvers: &graph.Resolver{Store: &store},
Resolvers: &graph.Resolver{Store: &store},
Directives: graph.Directives(),
}))
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
gqlSrv.AddTransport(transport.Options{})
@@ -240,13 +246,6 @@ func main() {
c.JSON(200, gin.H{"message": "Hello World"})
})
// 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 until the server stops. Any return is a failure — a port clash,
// most often — so it must exit non-zero, or Docker sees a clean shutdown
+156 -69
View File
@@ -20,8 +20,9 @@ import (
// 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).
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
// On the wire an id is a quoted decimal string, "12".
// User is an account. There is no public sign-up: users are created by an
// existing admin through the createUser mutation, or by the dev seeder.
@@ -38,6 +39,14 @@ type User struct {
// 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"`
// Permissions names the gated services this non-admin user may use, one
// key each from services.PermissionTypes (admins pass every check
// regardless). Unlike Admin it is never copied into a token: the gate
// reads it from the row, which services.Auth loads on every request
// anyway, so a grant or revoke takes effect on the user's next request.
// Stored as a JSON array in one text column; a row from before the
// column existed reads as NULL, i.e. no permissions.
Permissions []string `gorm:"serializer:json" json:"permissions"`
// TokenVersion is the session generation counter. Every issued JWT
// carries the value current at the time it was minted, and
// services.Auth rejects a token whose value no longer matches, so
@@ -137,57 +146,6 @@ 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"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Category string `gorm:"not null" json:"category"`
Label string `gorm:"not null" json:"label"`
Value string `gorm:"not null" json:"value"`
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"`
// 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"`
// Attempts counts how many times processing this email has been tried.
// A row with Action "error" and Attempts below the cap is retryable: the
// next sync re-processes it instead of skipping it. Once Attempts reaches
// the cap the row becomes terminal, so a genuinely unprocessable email
// (one Claude can never parse) eventually stops consuming API calls.
// Rows written before this column existed default to 1 and so get their
// remaining attempts.
Attempts int `gorm:"not null;default:1" json:"attempts"`
// ReceivedAt is the provider's own timestamp for the email, as distinct
// from CreatedAt (when we processed it). It exists so a retryable failure
// can pull the fetch window back far enough to actually re-fetch the
// email: the window is otherwise anchored to processing time, which would
// have already advanced past it. Zero for rows written before this
// column existed, and for those the clamp is skipped.
ReceivedAt time.Time `json:"receivedAt"`
}
// 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.
@@ -206,24 +164,153 @@ 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 {
// Box is one panel on a canvas page. Page names the canvas it belongs to:
// "index" for the landing page, or a Page.Slug for an admin-created page
// (the home page is the Page "stp") — it is a key, not a foreign key, so the
// built-in landing canvas needs no Page row. Its position and size are in px on a
// fixed 1400px-wide design canvas, which the page scales down on narrower
// screens — so the stored numbers mean the same thing for every visitor. Kind "widget" renders a built-in Vue component named by Widget;
// kind "html" renders HTML in a sandboxed iframe on the front end, which is
// what makes storing admin-authored script here acceptable.
type Box struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
JobTitle string `gorm:"not null" json:"jobTitle"`
Company string `gorm:"not null" json:"company"`
Location *string `json:"location"`
URL *string `json:"url"`
Status string `gorm:"not null" json:"status"`
Notes *string `json:"notes"`
AppliedAt *time.Time `json:"appliedAt"`
// default:stp is what the boxes that predate pages are migrated to.
Page string `gorm:"not null;default:stp;index" json:"page"`
Kind string `gorm:"not null" json:"kind"`
Widget *string `json:"widget"`
HTML *string `json:"html"`
Title *string `json:"title"`
X int `gorm:"not null;default:0" json:"x"`
Y int `gorm:"not null;default:0" json:"y"`
W int `gorm:"not null;default:300" json:"w"`
H int `gorm:"not null;default:200" json:"h"`
Z int `gorm:"not null;default:0" json:"z"`
// No gorm default on Framed: GORM omits zero values for defaulted columns
// on insert, so default:true would turn an explicit false into true.
// CreateBox applies the true default itself.
Framed bool `gorm:"not null" json:"framed"`
// Shadow is a CSS box-shadow value drawn around the box, or "" for none.
// It is independent of Framed, so an unframed box can still cast one.
Shadow string `gorm:"not null;default:''" json:"shadow"`
HideOnMobile bool `gorm:"not null;default:false" json:"hideOnMobile"`
// AdminOnly boxes are never sent to anyone but an admin (the boxes
// resolver filters them out), so they suit private notes.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
// ComponentID links an html box to a Component, whose HTML it shows
// instead of its own: the row's HTML is nil, and the resolvers fill it in
// from the component before answering (graph/component_helpers.go). There
// is deliberately no association field — with one, DB.Save(&box) would
// write the component back too.
ComponentID *uint `gorm:"index" json:"componentId"`
}
// Page is an admin-created canvas page, served by the SPA's catch-all route
// at /<Slug> (e.g. "shrines/evangelion"). Its content is the Boxes whose Page
// equals Slug. The unique index is partial so that a deleted page's slug can
// be reused — a plain uniqueIndex would still collide with the soft-deleted
// row.
type Page struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Slug string `gorm:"not null;index:idx_pages_slug,unique,where:deleted_at IS NULL" json:"slug"`
Title string `gorm:"not null" json:"title"`
// AdminOnly hides the whole page, boxes included, from everyone else.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
}
// Background is the page background behind one canvas (Page is the same page
// key a Box has: "index" for the landing page, or a Page's slug), so
// built-in canvases and admin-created pages are set the same way. A page with
// no row shows the theme's halftone; deleting the row is "reset to default".
// The unique index is partial for the same reason as Page's.
type Background struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Page string `gorm:"not null;index:idx_backgrounds_page,unique,where:deleted_at IS NULL" json:"page"`
// Color is a CSS colour, or "" for the theme's page colour.
Color string `gorm:"not null;default:''" json:"color"`
// Image is a URL, or "" for none. Drawn over Color.
Image string `gorm:"not null;default:''" json:"image"`
// Fit is how Image fills the window: "cover", "contain" or "tile".
Fit string `gorm:"not null;default:cover" json:"fit"`
}
// Layout is a named copy of one canvas page's boxes and background, saved so
// it can be loaded onto any page later (graph/layout_helpers.go). It is a
// snapshot, not a link: loading it creates new boxes that belong to the
// target page, so editing either page afterwards never touches the other or
// the layout. The content is JSON rather than child rows because nothing
// queries inside it — it is only ever written whole and read whole. The
// unique index is partial for the same reason as Page's.
type Layout struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
// SourcePage is the page key it was saved from, for the list only.
SourcePage string `gorm:"not null" json:"sourcePage"`
// Boxes is a JSON array of the boxes' content and geometry, without id
// or page.
Boxes string `gorm:"type:text;not null" json:"-"`
// Background is the page's background as JSON, or nil if it had none.
Background *string `gorm:"type:text" json:"-"`
}
// Component is a named HTML box that can be placed on any canvas page, either
// as a copy (an ordinary box) or linked (a box with ComponentID set). Linked
// boxes share only the HTML — editing it changes every one of them at once —
// while title, geometry, frame and visibility stay each box's own, since
// those are about where it sits on a page rather than what it is. Title, W,
// H, Framed, Shadow and AdminOnly are the defaults a newly placed box starts
// with.
// Widgets are not components: a widget box is just a name, with nothing
// worth sharing. The unique index is partial for the same reason as Page's.
type Component struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_components_name,unique,where:deleted_at IS NULL" json:"name"`
Title *string `json:"title"`
HTML string `gorm:"type:text;not null" json:"html"`
W int `gorm:"not null" json:"w"`
H int `gorm:"not null" json:"h"`
// No gorm default on Framed, for the same reason as Box.Framed.
Framed bool `gorm:"not null" json:"framed"`
Shadow string `gorm:"not null;default:''" json:"shadow"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
}
// CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the
// whole letter as JSON (contact block, sections, paragraphs; the shape is
// views/CV/coverLetter.js's) because only the frontend ever reads inside it —
// the same reasoning as Layout.Boxes. The unique index is partial for the
// same reason as Page's.
type CoverLetter struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_cover_letters_name,unique,where:deleted_at IS NULL" json:"name"`
Body string `gorm:"type:text;not null" json:"body"`
}
// CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into
// a letter as a copy. Section is the title of the section it was written for,
// only used to group the bank; a snippet can be dropped into any section.
type CoverSnippet struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Text string `gorm:"type:text;not null" json:"text"`
Section string `gorm:"not null;default:''" json:"section"`
}
+1 -1
View File
@@ -155,7 +155,7 @@ func tokenVersionOf(v uint) uint {
// verifies the signature and expiry, reads the id claim, loads the row, and
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
+3 -1
View File
@@ -18,7 +18,9 @@ import (
func testAuth() *Auth {
return InitAuth(&AuthConfig{
Secret: []byte("test-secret"),
// InitAuth panics on anything under 32 bytes, so the fixture has to be
// a realistic length even though nothing here depends on its value.
Secret: []byte("test-secret-0123456789abcdef0123456789"),
Domain: "example.test",
AccessTokenLifetime: time.Hour,
RefreshTokenLifetime: 24 * time.Hour,
-24
View File
@@ -1,24 +0,0 @@
package services
import (
"github.com/anthropics/anthropic-sdk-go"
"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
}
+24 -4
View File
@@ -49,17 +49,37 @@ func migrateDatabase(db *gorm.DB) error {
&models.Favorite{},
&models.Rowing{},
&models.Message{},
&models.JobApplication{},
&models.JobAppReference{},
&models.Bookmark{},
&models.Place{},
&models.ProcessedEmail{},
&models.Box{},
&models.Page{},
&models.Background{},
&models.Layout{},
&models.Component{},
&models.CoverLetter{},
&models.CoverSnippet{},
)
if err != nil {
return err
}
return nil
return ensureStpPage(db)
}
// ensureStpPage turns the home page (/stp) into an ordinary canvas Page once.
// It used to be a built-in canvas with its own route; its boxes and
// background were already keyed "stp", so a Page row with that slug is all
// it takes. Unscoped, so that deleting the page on purpose sticks rather than
// bringing it back on the next start.
func ensureStpPage(db *gorm.DB) error {
var count int64
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil
}
return db.Create(&models.Page{Slug: "stp", Title: "STP"}).Error
}
// InitDatabase connects to Postgres and runs the auto-migration.
-420
View File
@@ -1,420 +0,0 @@
package services
import (
"bufio"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"net"
"net/mail"
"strings"
"sync/atomic"
"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
Email string
Password string
}
// imapClient is a minimal, lenient IMAP client that tolerates
// Outlook's non-standard response formatting.
type imapClient struct {
conn net.Conn
reader *bufio.Reader
// 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 {
return nil, err
}
c := &imapClient{
conn: conn,
reader: bufio.NewReader(conn),
}
// Read server greeting
if _, err := c.readLine(); err != nil {
conn.Close()
return nil, fmt.Errorf("reading greeting: %w", err)
}
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 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)
if err != nil {
return nil, "", err
}
for {
line, err := c.readLine()
if err != nil {
return untagged, "", err
}
if strings.HasPrefix(line, tag+" ") {
return untagged, line, nil
}
untagged = append(untagged, line)
}
}
// sendCommandOK sends a command and returns an error if the response is not OK.
func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
untagged, status, err := c.sendCommand(cmd)
if err != nil {
return untagged, err
}
// Status line is "<tag> OK ..." on success, "<tag> NO ..." or
// "<tag> 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)
}
return untagged, nil
}
// 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)
if err != nil {
return "", err
}
return string(buf), nil
}
// fetchPart is one FETCH response line plus the literal payload that followed
// it, if any. Pairing them in the type removes the need for callers to walk an
// interleaved slice and manually skip every second entry — the previous shape,
// where a literal was simply the next element and a caller that forgot to
// advance would parse message bytes as a protocol line.
type fetchPart struct {
Line string
// Literal is the payload that followed Line, valid only when HasLiteral.
Literal string
HasLiteral bool
}
// sendFetch sends a FETCH and collects its response, handling literals.
//
// 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) ([]fetchPart, error) {
tag := c.nextTag()
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
if err != nil {
return nil, err
}
var parts []fetchPart
for {
line, err := c.readLine()
if err != nil {
return parts, err
}
// Check for literal marker {N} at end of line
if idx := strings.LastIndex(line, "{"); idx >= 0 && strings.HasSuffix(line, "}") {
sizeStr := line[idx+1 : len(line)-1]
var size int
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
literal, err := c.readLiteral(size)
if err != nil {
return parts, fmt.Errorf("reading literal of %d bytes: %w", size, err)
}
parts = append(parts, fetchPart{Line: line, Literal: literal, HasLiteral: true})
continue
}
}
if strings.HasPrefix(line, tag+" ") {
// Check for OK
fields := strings.SplitN(line, " ", 3)
if len(fields) >= 2 && fields[1] != "OK" {
return parts, fmt.Errorf("FETCH failed: %s", line)
}
return parts, nil
}
parts = append(parts, fetchPart{Line: line})
}
}
// fetchEmailsIMAP connects to an IMAP server and retrieves emails since the given time.
func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, error) {
addr := fmt.Sprintf("%s:%s", s.Config.IMAP.Host, s.Config.IMAP.Port)
c, err := imapDial(addr)
if err != nil {
return nil, fmt.Errorf("IMAP connect: %w", err)
}
defer c.Close()
// %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)
}
if _, err := c.sendCommandOK("SELECT INBOX"); err != nil {
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
}
// 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 ...". 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") {
parts := strings.Fields(line)
if len(parts) > 2 {
seqNums = append(seqNums, parts[2:]...)
}
}
}
if len(seqNums) == 0 {
log.Printf("[EmailSync/IMAP] No messages found since %s", dateStr)
c.sendCommand("LOGOUT")
return nil, nil
}
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, ",")
fetchParts, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
if err != nil {
return nil, fmt.Errorf("IMAP fetch: %w", err)
}
// Each body arrives as a "... BODY[] {N}" line carrying its literal, so
// the pairing is now part of the value rather than something this loop has
// to reconstruct by skipping entries. A message that fails to parse is
// logged and skipped rather than failing the whole sync.
var messages []graphMessage
for _, part := range fetchParts {
if part.HasLiteral && strings.Contains(part.Line, "BODY[]") {
gm, err := parseRawEmail(part.Literal)
if err != nil {
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
continue
}
messages = append(messages, gm)
}
}
// 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 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 {
return graphMessage{}, fmt.Errorf("parsing message: %w", err)
}
header := msg.Header
// Parse From
var fromName, fromAddr string
if fromList, err := header.AddressList("From"); err == nil && len(fromList) > 0 {
fromName = fromList[0].Name
fromAddr = fromList[0].Address
}
// Parse Date
dateStr := header.Get("Date")
parsedDate, err := mail.ParseDate(dateStr)
if err != nil {
parsedDate = time.Now()
}
// Extract body text
bodyContent := extractTextBody(msg.Header, msg.Body)
// Dedup is keyed on GraphMessageID: a missing Message-ID header would
// yield "", which collides every headerless message onto one shared row
// (the first one processed, forever). Synthesise an id from stable
// message traits instead — hashing because From/Date/Subject/size are not
// unique alone but their combination is stable across retries.
msgID := header.Get("Message-ID")
if msgID == "" {
hash := sha256.Sum256([]byte(fromAddr + "|" + dateStr + "|" + header.Get("Subject") + "|" + bodyContent))
msgID = "synth-" + hex.EncodeToString(hash[:8])
}
return graphMessage{
ID: msgID,
Subject: decodeHeader(header.Get("Subject")),
ReceivedDateTime: parsedDate.Format(time.RFC3339),
From: graphFrom{
EmailAddress: graphEmailAddress{
Name: fromName,
Address: fromAddr,
},
},
Body: graphBody{
ContentType: "text",
Content: bodyContent,
},
}, nil
}
// 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 == "" {
contentType = "text/plain"
}
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
// Try reading as plain text
b, _ := io.ReadAll(body)
return string(b)
}
if strings.HasPrefix(mediaType, "multipart/") {
boundary := params["boundary"]
if boundary == "" {
b, _ := io.ReadAll(body)
return string(b)
}
mr := multipart.NewReader(body, boundary)
var textContent, htmlContent string
for {
part, err := mr.NextPart()
if err != nil {
break
}
partType := part.Header.Get("Content-Type")
partMedia, _, _ := mime.ParseMediaType(partType)
b, err := io.ReadAll(part)
if err != nil {
continue
}
switch partMedia {
case "text/plain":
textContent = string(b)
case "text/html":
htmlContent = string(b)
case "multipart/alternative", "multipart/related", "multipart/mixed":
// Recursively handle nested multipart
nested := extractTextBody(
mail.Header{"Content-Type": {partType}},
strings.NewReader(string(b)),
)
if nested != "" && textContent == "" {
textContent = nested
}
}
}
if textContent != "" {
return textContent
}
return htmlContent
}
b, _ := io.ReadAll(body)
return string(b)
}
// 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)
if err != nil {
return s
}
return decoded
}
-92
View File
@@ -1,92 +0,0 @@
package services
import "testing"
// These tests cover the status progression rule only — statusAdvances, the
// predicate extracted out of updateJobApplication. The rest of
// updateJobApplication (note appending, the DB.Save, the returned counters)
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
// deliberately not exercised here. Nothing in this file touches Claude or the
// Graph API either; email classification is a network call by construction.
func TestStatusAdvances(t *testing.T) {
cases := []struct {
name string
current string
next string
want bool
}{
{"one step forward is the normal case", "applied", "screening", true},
{"skipping intermediate stages still advances", "applied", "offer", true},
{"adjacent step backwards is refused", "interviewing", "assessment", false},
{"a long way backwards is refused", "offer", "applied", false},
{"same status is not progression, so a duplicate email is a no-op", "screening", "screening", false},
// rejected and withdrawn sit at the top of statusOrder: once an
// application lands there, no later email may move it.
{"rejected cannot fall back to interviewing", "rejected", "interviewing", false},
{"rejected cannot fall back to offer", "rejected", "offer", false},
{"rejected cannot repeat", "rejected", "rejected", false},
{"withdrawn cannot fall back to offer", "withdrawn", "offer", false},
{"withdrawn cannot fall back to rejected", "withdrawn", "rejected", false},
{"withdrawn cannot repeat", "withdrawn", "withdrawn", false},
// The one ordering asymmetry between the two terminals: withdrawn
// ranks above rejected, so this single pair is allowed.
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
{"an unknown new status is never applied", "applied", "hired", false},
{"an empty new status is never applied", "applied", "", false},
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
{"a recognised status takes over from an unknown current status", "ghosted", "applied", true},
{"a recognised status takes over from an empty current status", "", "offer", true},
{"unknown to unknown stays put", "ghosted", "hired", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := statusAdvances(c.current, c.next); got != c.want {
t.Errorf("statusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
}
})
}
}
// Guards the claim the other tests rest on: rejected and withdrawn really are
// the top of the ranking, so adding a stage below them cannot silently make
// them non-terminal.
func TestTerminalStatusesRankHighest(t *testing.T) {
for status, order := range statusOrder {
if status == "rejected" || status == "withdrawn" {
continue
}
if order >= statusOrder["rejected"] {
t.Errorf("%q ranks %d, at or above rejected (%d)", status, order, statusOrder["rejected"])
}
}
}
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
// ("Interview", "on hold") out of the status column: an unrecognised value
// stored verbatim makes statusAdvances treat the row's current status as
// unknown, which switches the forward-only rule off for that row entirely.
func TestNormalizeStatus(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"a tracked status passes through", "interviewing", "interviewing"},
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
{"surrounding whitespace is trimmed", " offer ", "offer"},
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
{"the UI's old Title Case value is recognised once lowered", "Rejected", "rejected"},
{"a value the UI once allowed but the pipeline never had is rejected", "Interview", "applied"},
{"empty falls back rather than storing a blank status", "", "applied"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := NormalizeStatus(c.in); got != c.want {
t.Errorf("NormalizeStatus(%q) = %q, want %q", c.in, got, c.want)
}
})
}
}
-968
View File
@@ -1,968 +0,0 @@
package services
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"adam-french.co.uk/backend/models"
"github.com/anthropics/anthropic-sdk-go"
"golang.org/x/oauth2"
"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
ClientSecret string
TenantID string
RedirectURI string
IMAP *IMAPConfig
SyncInterval time.Duration
Enabled bool
}
// EmailSyncService owns the sync pipeline.
type EmailSyncService struct {
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 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"`
ReceivedDateTime string `json:"receivedDateTime"`
From graphFrom `json:"from"`
Body graphBody `json:"body"`
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"`
}
// 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"`
Company string `json:"company"`
JobTitle string `json:"jobTitle"`
Status string `json:"status"`
Location *string `json:"location"`
URL *string `json:"url"`
AppliedAt *string `json:"appliedAt"`
Notes *string `json:"notes"`
}
// 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",
"thank you for applying", "we regret", "move forward",
"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",
"jobvite.com", "taleo.net", "breezy.hr", "recruitee.com",
"applytojob.com", "jazz.co", "dover.com",
}
// 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,
"assessment": 2,
"interviewing": 3,
"offer": 4,
"rejected": 5,
"withdrawn": 6,
}
// 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"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Expiry time.Time `json:"expiry"`
}{
AccessToken: tok.AccessToken,
RefreshToken: tok.RefreshToken,
TokenType: tok.TokenType,
Expiry: tok.Expiry,
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("creating token directory: %w", err)
}
jsonBytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
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 {
return nil, err
}
var saved struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Expiry time.Time `json:"expiry"`
}
if err := json.Unmarshal(data, &saved); err != nil {
return nil, err
}
return &oauth2.Token{
AccessToken: saved.AccessToken,
RefreshToken: saved.RefreshToken,
TokenType: saved.TokenType,
Expiry: saved.Expiry,
}, nil
}
// persistingTokenSource wraps an oauth2.TokenSource to save refreshed tokens to disk.
type persistingTokenSource struct {
base oauth2.TokenSource
path string
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 {
return nil, err
}
// Save only when the token actually changed (i.e. was refreshed)
if p.lastToken == nil || tok.AccessToken != p.lastToken.AccessToken {
p.lastToken = tok
if saveErr := SaveMSGraphToken(p.path, tok); saveErr != nil {
log.Printf("[EmailSync] Warning: failed to persist refreshed token: %v", saveErr)
}
}
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,
DB: db,
ClaudeClient: claudeClient,
}
switch config.Backend {
case "imap":
if config.IMAP == nil || config.IMAP.Email == "" {
log.Println("[EmailSync] IMAP backend selected but not configured")
return svc
}
// IMAP connects per-sync, no persistent client needed.
// Mark as ready by setting a non-nil HTTPClient (used as readiness flag).
svc.HTTPClient = http.DefaultClient
log.Printf("[EmailSync] Configured with IMAP backend (%s)", config.IMAP.Host)
case "graph":
oauthConfig := &oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/authorize", config.TenantID),
TokenURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", config.TenantID),
},
RedirectURL: config.RedirectURI,
Scopes: []string{"https://graph.microsoft.com/Mail.Read", "offline_access"},
}
svc.OAuthConfig = oauthConfig
token, err := LoadMSGraphToken(MSGRAPH_TOKEN_JSON_PATH)
if err != nil || token == nil {
authURL := oauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
log.Println("[EmailSync] No token saved. Authenticate Microsoft Graph with:")
log.Println(authURL)
return svc
}
baseSource := oauthConfig.TokenSource(context.Background(), token)
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
svc.HTTPClient = oauth2.NewClient(context.Background(), persistSource)
log.Println("[EmailSync] Authenticated with Microsoft Graph")
default:
log.Printf("[EmailSync] Unknown backend %q, defaulting to disabled", config.Backend)
}
return svc
}
// AuthURL returns the OAuth2 authorization URL for initial setup.
func (s *EmailSyncService) AuthURL() string {
return s.OAuthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
}
// CompleteAuth exchanges an authorization code for a token and initializes the HTTP client.
func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error {
token, err := s.OAuthConfig.Exchange(ctx, code)
if err != nil {
return fmt.Errorf("token exchange failed: %w", err)
}
if err := SaveMSGraphToken(MSGRAPH_TOKEN_JSON_PATH, token); err != nil {
return fmt.Errorf("saving token: %w", err)
}
baseSource := s.OAuthConfig.TokenSource(ctx, token)
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
s.HTTPClient = oauth2.NewClient(ctx, persistSource)
log.Println("[EmailSync] Authentication completed successfully")
return nil
}
// 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")
return
}
if s.HTTPClient == nil {
log.Println("[EmailSync] Not authenticated, skipping scheduler")
return
}
log.Printf("[EmailSync] Starting scheduler, interval: %s", s.Config.SyncInterval)
// Run once immediately on startup
if err := s.SyncEmails(ctx); err != nil {
log.Printf("[EmailSync] Initial sync error: %v", err)
}
ticker := time.NewTicker(s.Config.SyncInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
log.Println("[EmailSync] Scheduler stopped")
return
case <-ticker.C:
if err := s.SyncEmails(ctx); err != nil {
log.Printf("[EmailSync] Sync error: %v", err)
}
}
}
}
// 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)
}
}()
log.Println("[EmailSync] Starting sync...")
// Window start comes from the newest email we have ever *received* (one of
// two clocks in play) rather than from when we processed it: receive time
// lags processing time by up to one sync duration, and a later window
// anchored to processing time would start AFTER mail that arrived just at
// the previous fetch — a permanent hole (the overlap the code always meant
// to have is produced only when both edges speak the same clock).
// Anchoring on ReceivedAt keeps the window behind the fetch, the
// ProcessedEmail dedup absorbs the deliberate re-fetch overlap, and on a
// cold database 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.Where("received_at > ?", time.Time{}).Order("received_at DESC").First(&latest).Error; err == nil {
// Pull the window back one slack period so mail delivered a second or
// two after the last fetch (or indexed late by the provider) is still
// inside the next window; dedup makes re-processing it harmless.
since = latest.ReceivedAt.Add(-fetchSlack)
}
// Pull the window back to cover any still-retryable failure. Without this
// the clamp above would have advanced past a failed email — the error row
// is written now, so the next window starts after it — and the retry
// below could never see the email again. Rows predating ReceivedAt have
// a zero value and are ignored rather than dragging the window to 0001.
//
// Old failures are age-capped: attempts only advance when the email is
// actually re-fetched, so a message that has left the mailbox would stay
// under the cap forever and rewind every sync on this day's fetch. After
// maxRewindAge the email is treated as gone, like any abandoned retry.
var oldestRetryable models.ProcessedEmail
if err := s.DB.
Where("action = ? AND attempts < ? AND received_at > ? AND received_at > ?",
"error", maxEmailAttempts, time.Time{}, time.Now().Add(-maxRewindAge)).
Order("received_at ASC").
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
oldestRetryable.ReceivedAt.Format(time.RFC3339))
since = oldestRetryable.ReceivedAt
}
// Fetch emails from Microsoft Graph
emails, err := s.fetchEmails(ctx, since)
if err != nil {
return fmt.Errorf("fetching emails: %w", err)
}
log.Printf("[EmailSync] Fetched %d emails since %s", len(emails), since.Format(time.RFC3339))
// Filter by subject/sender patterns
filtered := s.filterEmails(emails)
log.Printf("[EmailSync] %d emails passed filters", len(filtered))
var created, updated, skipped, errored int
for _, email := range filtered {
// Dedup check. A row is terminal — and so genuinely skippable — if it
// succeeded, or if it failed the maximum number of times. A row that
// failed but has attempts left is deliberately NOT skipped: it is
// reprocessed below and the same row updated, so a transient Claude
// or network outage no longer drops the email permanently.
var existing models.ProcessedEmail
found := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error == nil
if found && !retryableFailure(&existing) {
skipped++
continue
}
if found {
log.Printf("[EmailSync] Retrying previously failed email %q (attempt %d of %d)",
email.Subject, existing.Attempts+1, maxEmailAttempts)
}
action, jobAppID, processErr := s.processEmail(ctx, email)
// The row carries the outcome either way. On failure the attempt
// counter advances, so repeated failures walk the row towards the cap
// and it eventually stops being retried. A cancelled sync (the admin
// closed the tab mid-backlog, or nginx cut the request) is not a
// failure of the email, though: attempts must not advance for it, or
// two closed tabs would strand a healthy email at the cap and skip it
// forever. Writing nothing preserves the existing row untouched, so it
// is simply retried at the next sync.
if processErr != nil && errors.Is(processErr, context.Canceled) {
skipped++
continue
}
record := models.ProcessedEmail{
GraphMessageID: email.ID,
Subject: truncate(email.Subject, 255),
Action: action,
JobAppID: jobAppID,
ReceivedAt: parseReceivedAt(email.ReceivedDateTime),
Attempts: existing.Attempts + 1,
}
if processErr != nil {
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
record.Action = "error"
record.JobAppID = nil
if record.Attempts >= maxEmailAttempts {
log.Printf("[EmailSync] Email %q has failed %d times; giving up on it",
email.Subject, record.Attempts)
}
s.saveProcessed(found, &existing, &record)
errored++
continue
}
s.saveProcessed(found, &existing, &record)
switch action {
case "created":
created++
case "updated":
updated++
default:
skipped++
}
}
log.Printf("[EmailSync] Sync complete: %d fetched, %d filtered, %d created, %d updated, %d skipped, %d errors",
len(emails), len(filtered), created, updated, skipped, errored)
return nil
}
// 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)
}
return s.fetchEmailsGraph(ctx, since)
}
// fetchEmailsGraph retrieves emails from the Microsoft Graph API since the given time.
func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time) ([]graphMessage, error) {
var all []graphMessage
sinceStr := since.UTC().Format("2006-01-02T15:04:05Z")
params := url.Values{
"$filter": {fmt.Sprintf("receivedDateTime ge %s", sinceStr)},
"$select": {"id,subject,from,receivedDateTime,body,bodyPreview"},
"$top": {"50"},
"$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 != "" {
req, err := http.NewRequestWithContext(ctx, "GET", nextURL, nil)
if err != nil {
return nil, err
}
resp, err := s.HTTPClient.Do(req)
if err != nil {
return nil, err
}
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))
}
if err != nil {
return nil, err
}
var result graphMessagesResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("parsing response: %w", err)
}
all = append(all, result.Value...)
nextURL = result.NextLink
}
return all, nil
}
// filterEmails returns only emails that match subject keywords or sender domains.
func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
var matched []graphMessage
for _, email := range emails {
if s.matchesFilter(email) {
matched = append(matched, email)
}
}
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 {
if strings.Contains(subjectLower, kw) {
return true
}
}
senderAddr := strings.ToLower(email.From.EmailAddress.Address)
for _, domain := range senderDomains {
if strings.HasSuffix(senderAddr, "@"+domain) || strings.HasSuffix(senderAddr, "."+domain) {
return true
}
}
return false
}
// processEmail sends a single email to Claude and creates/updates a JobApplication.
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
email.Subject,
email.From.EmailAddress.Name,
email.From.EmailAddress.Address,
email.ReceivedDateTime,
cleaned,
)
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeHaiku4_5,
MaxTokens: 512,
System: []anthropic.TextBlockParam{
{Text: emailClassificationPrompt},
},
Messages: []anthropic.MessageParam{
{
Role: "user",
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
},
},
})
if err != nil {
return "", nil, fmt.Errorf("Claude API error: %w", err)
}
if len(message.Content) == 0 {
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.
raw := StripMarkdownFence(message.Content[0].Text)
var analysis EmailAnalysis
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
}
if !analysis.IsJobEmail {
return "skipped", nil, nil
}
if analysis.Company == "" || analysis.JobTitle == "" {
return "skipped", nil, nil
}
// 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.
// The lookup is Unscoped: a deleted-with-notes row is stored, not purged
// (see models.JobApplication), so invisibility here makes the matcher
// believe the application never existed and a follow-up email in the same
// thread re-creates it — the admin deletes it, it comes back. A hit on a
// deleted row instead becomes a suppression: nothing is updated, nothing
// is created, and the pipeline leaves the deletion to stand.
var existing models.JobApplication
found := s.DB.Unscoped().Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
analysis.Company, analysis.JobTitle).
Order("created_at DESC").
First(&existing).Error == nil
if found && existing.DeletedAt.Valid {
return "skipped", nil, nil
}
if found && analysis.Action == "update" {
return s.updateJobApplication(&existing, &analysis)
}
if !found {
return s.createJobApplication(&analysis)
}
// Found but action is "create" — the record already exists, skip
return "skipped", &existing.ID, nil
}
// NormalizeStatus coerces Claude's status guess into the tracked vocabulary,
// lowering the case it occasionally drifts on and rejecting anything outside
// statusOrder. An unrecognised status stored verbatim would disable the
// forward-only guard for that row (updateJobApplication allows any recognised
// status over an unknown one), so the safe fallback is the pipeline's default.
func NormalizeStatus(s string) string {
lowered := strings.ToLower(strings.TrimSpace(s))
if _, ok := statusOrder[lowered]; ok {
return lowered
}
return "applied"
}
// createJobApplication inserts a new application from Claude's analysis.
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
app := models.JobApplication{
Company: analysis.Company,
JobTitle: analysis.JobTitle,
Status: NormalizeStatus(analysis.Status),
Location: analysis.Location,
URL: analysis.URL,
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
} else if t, err := time.Parse("2006-01-02", *analysis.AppliedAt); err == nil {
app.AppliedAt = &t
}
}
if app.Status == "" {
app.Status = "applied"
}
if err := s.DB.Create(&app).Error; err != nil {
return "", nil, fmt.Errorf("creating job application: %w", err)
}
log.Printf("[EmailSync] Created job application: %s at %s (status: %s)", app.JobTitle, app.Company, app.Status)
return "created", &app.ID, nil
}
// statusAdvances reports whether next is a forward move from current 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. An unknown next status is never applied;
// an unknown current status is treated as "anywhere before the start", so any
// recognised status can take over from it.
func statusAdvances(current, next string) bool {
nextOrder, nextExists := statusOrder[next]
currentOrder, currentExists := statusOrder[current]
return nextExists && (!currentExists || nextOrder > currentOrder)
}
// updateJobApplication advances an existing application's status, but only
// ever forwards (see statusAdvances).
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
if !statusAdvances(existing.Status, analysis.Status) {
return "skipped", &existing.ID, nil
}
existing.Status = analysis.Status
// Append to notes if Claude provided any
if analysis.Notes != nil && *analysis.Notes != "" {
if existing.Notes != nil && *existing.Notes != "" {
combined := *existing.Notes + "\n" + *analysis.Notes
existing.Notes = &combined
} else {
existing.Notes = analysis.Notes
}
}
if err := s.DB.Save(existing).Error; err != nil {
return "", nil, fmt.Errorf("updating job application: %w", err)
}
log.Printf("[EmailSync] Updated job application: %s at %s (status: %s)", existing.JobTitle, existing.Company, existing.Status)
return "updated", &existing.ID, nil
}
// 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 <script>/<style> content and mis-handle
// tags inside attribute values. That is acceptable because the output is only
// ever read by a language model, never rendered.
func cleanEmailBody(content string, contentType string) string {
text := content
if strings.EqualFold(contentType, "html") {
// Strip HTML tags
tagRegex := regexp.MustCompile(`<[^>]*>`)
text = tagRegex.ReplaceAllString(text, " ")
// Decode common HTML entities
replacer := strings.NewReplacer(
"&nbsp;", " ",
"&amp;", "&",
"&lt;", "<",
"&gt;", ">",
"&quot;", `"`,
"&#39;", "'",
"&apos;", "'",
)
text = replacer.Replace(text)
}
// Collapse whitespace
spaceRegex := regexp.MustCompile(`[ \t]+`)
text = spaceRegex.ReplaceAllString(text, " ")
nlRegex := regexp.MustCompile(`\n{3,}`)
text = nlRegex.ReplaceAllString(text, "\n\n")
text = strings.TrimSpace(text)
// Cut everything from the first signature marker onwards. The idx > 0
// test (not >= 0) means a body that begins with a marker is left alone,
// which avoids blanking the whole message.
sigPatterns := []string{
"\n-- \n",
"\nSent from my iPhone",
"\nSent from my iPad",
"\nGet Outlook for",
}
for _, pattern := range sigPatterns {
if idx := strings.Index(text, pattern); idx > 0 {
text = text[:idx]
}
}
// Remove forwarded email chains
lines := strings.Split(text, "\n")
var cleaned []string
for _, line := range lines {
if strings.HasPrefix(strings.TrimSpace(line), ">") {
continue
}
cleaned = append(cleaned, line)
}
text = strings.Join(cleaned, "\n")
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
// and leave an invalid UTF-8 tail; harmless for a model prompt.
if len(text) > 4000 {
text = text[:4000]
}
return strings.TrimSpace(text)
}
// truncate caps a string at maxLen bytes (not runes) before it is stored in
// ProcessedEmail.Subject.
func truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen]
}
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
// every key it names is a field there, and the status values it lists are the
// keys of statusOrder.
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
Return ONLY a JSON object with these exact keys:
- "isJobEmail": boolean - true if this email is about a job application
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
- "company": string - the company name
- "jobTitle": string - the job title/position
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
- "location": string or null - job location if mentioned
- "url": string or null - any application portal URL
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
// StripMarkdownFence removes a surrounding markdown code fence from a model's
// response, so text that should have been bare JSON can be unmarshalled
// whether or not the model wrapped it.
//
// The two TrimPrefix calls are ordered so that "```json" is removed first and
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
// returned unchanged apart from surrounding whitespace.
//
// Shared with handlers.CreateRowing, which prompts for bare JSON in the same
// way and gets the same fenced output.
func StripMarkdownFence(raw string) string {
raw = strings.TrimSpace(raw)
raw = strings.TrimPrefix(raw, "```json")
raw = strings.TrimPrefix(raw, "```")
raw = strings.TrimSuffix(raw, "```")
return strings.TrimSpace(raw)
}
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
// attempt costs a Claude call, so the cap is what stops one permanently
// unparseable email billing on every sync forever. Three gives a transient
// outage two further chances across subsequent syncs.
const maxEmailAttempts = 3
// fetchSlack pulls each sync's window edge back by this much so mail that was
// delayed between fetch and filter (or index-registered late) is still caught
// by the next window. Consumers pay for it with deliberate re-fetches, which
// the ProcessedEmail dedup makes free.
const fetchSlack = 30 * time.Second
// maxRewindAge stops a stuck retry from pinning the window open forever. A
// failed email is only rewound for while it is younger than this; past that it
// has probably been deleted from the mailbox or fallen out of the provider's
// returns, so re-fetching for it would never yield anything.
const maxRewindAge = 7 * 24 * time.Hour
// retryableFailure reports whether a previously recorded email should be
// processed again. Only failures are retried, and only while they have
// attempts left; anything that succeeded is terminal.
func retryableFailure(row *models.ProcessedEmail) bool {
return row.Action == "error" && row.Attempts < maxEmailAttempts
}
// parseReceivedAt converts the provider's timestamp to a time.Time, returning
// the zero value if it is missing or malformed. A zero value is safe: it only
// means this row cannot pull the fetch window back, so the email is retried
// on the next sync that happens to cover it rather than being chased.
func parseReceivedAt(raw string) time.Time {
if raw == "" {
return time.Time{}
}
received, err := time.Parse(time.RFC3339, raw)
if err != nil {
log.Printf("[EmailSync] Unparseable receivedDateTime %q: %v", raw, err)
return time.Time{}
}
return received
}
// saveProcessed writes the outcome of an attempt: updating the existing row
// when this was a retry, inserting when it is the first attempt. Update is
// used rather than Save so the row keeps its original CreatedAt, which the
// fetch window depends on.
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
var err error
if found {
err = s.DB.Model(existing).Updates(map[string]any{
"action": record.Action,
"job_app_id": record.JobAppID,
"attempts": record.Attempts,
"received_at": record.ReceivedAt,
}).Error
} else {
err = s.DB.Create(record).Error
}
// Logged rather than returned: a bookkeeping failure must not abort the
// rest of the batch. It does mean the email is reprocessed next sync,
// which the dedup treats as a first attempt.
if err != nil {
log.Printf("[EmailSync] Failed to record processed email %q: %v", record.Subject, err)
}
}
-232
View File
@@ -1,232 +0,0 @@
package services
import (
"strings"
"testing"
"time"
"adam-french.co.uk/backend/models"
)
// These tests cover only the pure helpers of the email sync: body cleaning,
// truncation, fence stripping, timestamp parsing, the retry predicate and the
// filter. Everything else in email_sync.go — token acquisition, the Graph
// paging loop, processEmail and the create/update paths — needs either a live
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
// in a test run, so they are deliberately not exercised here.
//
// matchesFilter is a method but reads no field of the receiver (it matches
// against the package-level subjectKeywords/senderDomains), which is why a
// zero-value &EmailSyncService{} is a legitimate receiver below.
func TestCleanEmailBody(t *testing.T) {
cases := []struct {
name string
content string
contentType string
want string
}{
{
"html tags are stripped and entities decoded",
"<p>Hi&nbsp;Adam &amp; team</p><b>thanks</b>",
"html",
"Hi Adam & team thanks",
},
{
"contentType match is case-insensitive",
"<p>hello</p>",
"HTML",
"hello",
},
{
// Entities are only decoded on the HTML path, so plain text keeps
// them verbatim rather than being silently rewritten.
"text bodies are not entity-decoded",
"a &amp; b",
"text",
"a &amp; b",
},
{
"runs of spaces and tabs collapse to one space",
"one \t two",
"text",
"one two",
},
{
"three or more newlines collapse to a blank line",
"a\n\n\n\n\nb",
"text",
"a\n\nb",
},
{
"signature marker cuts the tail",
"body text\n-- \nAdam French\n07000",
"text",
"body text",
},
{
"Sent from my iPhone is treated as a signature",
"see attached\nSent from my iPhone",
"text",
"see attached",
},
{
// idx > 0, not >= 0: a body that is nothing but a signature would
// otherwise be blanked entirely, losing the only content there is.
"a body starting with a signature marker is left intact",
"Sent from my iPhone\nreal content",
"text",
"Sent from my iPhone\nreal content",
},
{
"quoted lines are dropped",
"my reply\n> their mail\n > indented quote\nmore reply",
"text",
"my reply\nmore reply",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := cleanEmailBody(c.content, c.contentType); got != c.want {
t.Fatalf("cleanEmailBody(%q, %q) = %q, want %q", c.content, c.contentType, got, c.want)
}
})
}
}
// The 4000-byte cap is what bounds the prompt cost, so it gets its own test:
// the cut is by bytes and is applied before the final TrimSpace.
func TestCleanEmailBodyCap(t *testing.T) {
got := cleanEmailBody(strings.Repeat("a", 5000), "text")
if len(got) != 4000 {
t.Fatalf("len = %d, want 4000", len(got))
}
// A body exactly at the cap must pass through untouched.
exact := strings.Repeat("b", 4000)
if got := cleanEmailBody(exact, "text"); got != exact {
t.Fatalf("body at the cap was modified: len = %d", len(got))
}
}
func TestTruncate(t *testing.T) {
cases := []struct {
name string
s string
maxLen int
want string
}{
{"shorter than the cap is unchanged", "abc", 10, "abc"},
{"exactly at the cap is unchanged", "abcde", 5, "abcde"},
{"longer is cut to the cap", "abcdef", 3, "abc"},
{"zero cap yields the empty string", "abc", 0, ""},
{"empty input", "", 5, ""},
// Bytes, not runes: the cut can land mid-rune. Asserted so the
// behaviour is a documented choice rather than a lurking surprise.
{"multi-byte runes are cut by byte", "é", 1, "\xc3"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := truncate(c.s, c.maxLen); got != c.want {
t.Fatalf("truncate(%q, %d) = %q, want %q", c.s, c.maxLen, got, c.want)
}
})
}
}
func TestStripMarkdownFence(t *testing.T) {
cases := []struct {
name string
raw string
want string
}{
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
{"empty input", "", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := StripMarkdownFence(c.raw); got != c.want {
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
}
})
}
}
func TestParseReceivedAt(t *testing.T) {
cases := []struct {
name string
raw string
want time.Time
}{
{"valid RFC3339", "2024-03-15T10:30:00Z", time.Date(2024, 3, 15, 10, 30, 0, 0, time.UTC)},
{"empty means no timestamp", "", time.Time{}},
{"malformed falls back to zero rather than failing the sync", "15/03/2024", time.Time{}},
{"a date without a time is not RFC3339", "2024-03-15", time.Time{}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := parseReceivedAt(c.raw); !got.Equal(c.want) {
t.Fatalf("parseReceivedAt(%q) = %v, want %v", c.raw, got, c.want)
}
})
}
}
func TestRetryableFailure(t *testing.T) {
cases := []struct {
name string
action string
attempts int
want bool
}{
{"a failure with attempts left is retried", "error", maxEmailAttempts - 1, true},
{"a failure at the cap is abandoned", "error", maxEmailAttempts, false},
{"a failure past the cap is abandoned", "error", maxEmailAttempts + 1, false},
{"a success is terminal even with attempts left", "created", 0, false},
{"a skip is terminal too", "skipped", 0, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
row := &models.ProcessedEmail{Action: c.action, Attempts: c.attempts}
if got := retryableFailure(row); got != c.want {
t.Fatalf("retryableFailure(%s, %d) = %v, want %v", c.action, c.attempts, got, c.want)
}
})
}
}
func TestMatchesFilter(t *testing.T) {
cases := []struct {
name string
subject string
sender string
want bool
}{
{"subject keyword anywhere in the line", "Your application to Acme", "[email protected]", true},
{"subject keyword is case-insensitive", "INTERVIEW CONFIRMED", "[email protected]", true},
{"sender on a tracked ATS domain", "hello", "[email protected]", true},
{"sender on a subdomain of a tracked domain", "hello", "[email protected]", true},
{"sender domain match is case-insensitive", "hello", "[email protected]", true},
// The rule is an @ or . boundary, so a lookalike domain that merely
// ends in the same letters must not match.
{"lookalike domain does not match", "hello", "[email protected]", false},
{"neither subject nor sender matches", "lunch tomorrow?", "[email protected]", false},
}
s := &EmailSyncService{}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
email := graphMessage{Subject: c.subject}
email.From.EmailAddress.Address = c.sender
if got := s.matchesFilter(email); got != c.want {
t.Fatalf("matchesFilter(%q, %q) = %v, want %v", c.subject, c.sender, got, c.want)
}
})
}
}
+49
View File
@@ -0,0 +1,49 @@
package services
import (
"slices"
"adam-french.co.uk/backend/models"
)
// Per-service permissions: how a non-admin account is let into one gated
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
Label string
Path string
}
// PermissionTypes is the full set of grantable permissions, in display order.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
}
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key
})
}
// HasPermission reports whether user may use the service gated on key. It
// reads the row, not a token, so Admin here is the current database value.
func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key)
}
+54
View File
@@ -0,0 +1,54 @@
package services
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidPermission(t *testing.T) {
for _, p := range PermissionTypes {
if !ValidPermission(p.Key) {
t.Errorf("listed key %q reported invalid", p.Key)
}
}
for _, key := range []string{"", "admin", "Receipt", "receipt "} {
if ValidPermission(key) {
t.Errorf("unlisted key %q reported valid", key)
}
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
if seen[p.Key] {
t.Errorf("duplicate key %q", p.Key)
}
seen[p.Key] = true
for _, r := range p.Key {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
t.Errorf("key %q has %q; use lowercase letters, digits and '-'", p.Key, r)
}
}
}
}
func TestHasPermission(t *testing.T) {
cases := []struct {
name string
user models.User
want bool
}{
{"admin passes without a grant", models.User{Admin: true}, true},
{"granted user passes", models.User{Permissions: []string{"receipt"}}, true},
{"other grant does not count", models.User{Permissions: []string{"other"}}, false},
{"no grants (NULL column) fails", models.User{}, false},
}
for _, c := range cases {
if got := HasPermission(&c.user, "receipt"); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}

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