Author SHA1 Message Date
renovate 4bdb5991e8 Update npm (non-major)
renovate/stability-days Updates have met minimum release age requirement
renovate/artifacts Artifact file update failure
Test and deploy / test (push) Successful in 1m38s
Test and deploy / deploy (push) Has been skipped
2026-11-09 04:05:30 +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
adamfandClaude Opus 5.5 7ce86f08ec Replace Quartz with a read-only SilverBullet for public /notes/
/notes/ is now served by silverbullet-public: the same SilverBullet 2.11.0
image as the /sb/ editor, run with SB_READ_ONLY over a read-only mount of
the vault. Quartz is retired (quartz/ kept with a STATUS header).

Keeping private/ off the public site needs nginx, not just SilverBullet:
SB_SPACE_IGNORE only filters the file listing. Verified with curl that
2.11.0 still serves ignored paths via /.fs/<path>, via server-rendered page
URLs, and exposes the vault's .git through /.fs/.git/. nginx now 404s any
private/ or templates/ segment at any depth and any nested dot-folder under
/notes/. SB_REVISIONS=disabled stops /.revisions serving git history, and
nginx blocks it as a second layer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 20:37:10 +01:00
adamf 78324bf7a3 remove auth validation on quartz
Deploy with Docker Compose / deploy (push) Successful in 57s
2026-09-30 18:22:23 +01:00
adamfandClaude Code 6dcb6b1384 Add stopwatch tab to Timer widget
Deploy with Docker Compose / deploy (push) Successful in 52s
Weekly Maintenance / maintenance (push) Successful in 3m40s
Co-Authored-By: Claude Code <[email protected]>
2026-09-23 16:28:24 +01:00
adamfandClaude Code ac8b3dadf3 Revert site-wide CSP from shared security headers
Deploy with Docker Compose / deploy (push) Successful in 26s
03e10be introduced the CSP before it was tested against the SPA's wasm
loader and the Gitea proxy. Gitea's own templates emit inline <script>
blocks, so the shared script-src would need 'unsafe-inline' to keep it
working — a CSP that weak nulls out most of its protection. Drop the
header site-wide; the /uploads/ locked-down CSP stays.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 23:29:00 +01:00
adamfandClaude Code a3bf0b26e5 csp: allow wasm-unsafe-eval so Rust AutoScroll WASM loads
Deploy with Docker Compose / deploy (push) Successful in 47s
03e10be added a CSP to the SPA document; default-src 'self' without
'wasm-unsafe-eval' blocks WebAssembly.instantiateStreaming, killing the
wasm port of AutoScroll. Keyword permits wasm compilation only, not JS eval.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 23:26:16 +01:00
adamfandClaude Code 4c49f5e177 Readable traffic log: drop heartbeat noise, surface visitors and errors
Deploy with Docker Compose / deploy (push) Successful in 50s
Replaces gin's default logger with a custom formatter:

- /auth/validate-admin (nginx auth_request subrequests — the 5-seconds
  flood that is not a user), /auth/refresh and /auth/check no longer log
  a line at all on success; their failures are kept.
- Human latency units (15ms, not 153020ns).
- Lines for requests from outside the docker subnet carry the client IP
  — the "who is using my site" line — while internal infrastructure
  successes stay lean.
- 4xx lines carry " !!", 5xx " !!! SERVER ERROR", both greppable.

The admin panel's Diagnostics log pane gains a "visitors only" filter
that keeps just the IP-suffixed and error lines (on by default).

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 23:20:22 +01:00
adamfandClaude Code a362d12ebc Fix AutoScroll stopping a viewport short of the end
Deploy with Docker Compose / deploy (push) Successful in 24s
scrollTop saturates at scrollHeight - clientHeight, so scaling pos by the
full scrollHeight meant the drift ran out of travel before pos reached 1.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 23:14:19 +01:00
adamfandClaude Code 03e10be2e4 Security audit fixes: JWT secret guard, WS revocation, nginx headers/TLS, loopback Gitea
Deploy with Docker Compose / deploy (push) Successful in 59s
- auth: panic at init if BACKEND_SECRET missing/short — HS256 would happily
  start with an empty key, making admin tokens forgeable by anyone
- websocket: admin check now goes through AuthenticateTokenWithClaims so the
  "tv" token-version revocation applies on /ws too; a logged-out or
  password-changed token no longer keeps it alive for its full lifetime
- admin diagnostics: check BACKEND_SECRET not the nonexistent AUTH_SECRET
- rowing upload: 10MB cap before buffering + base64 (admin-only route, but
  unbounded read = easy memory exhaustion + huge paid Claude call)
- nginx: shared security_headers.conf (XFO/nosniff/Referrer-Policy/HSTS/CSP)
  included in every location that sets its own add_header — nginx drops the
  parent's whole set otherwise; CSP added to the SPA document;
  ssl_protocols pinned to TLSv1.2/1.3; HSTS on apex redirect
- compose: Gitea HTTP bound to 127.0.0.1 (plain HTTP was LAN-exposed);
  autoheal docker socket mount read-only

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 23:12:56 +01:00
adamfandClaude Code 8bd93cbd8e Add admin diagnostics: env-var config check and log tail
Deploy with Docker Compose / deploy (push) Successful in 45s
Two admin-only REST endpoints and a Diagnostics tab in the admin panel:

- GET /admin/config reports which known environment variables are set,
  what each is for, and the value only for non-credential vars. Secrets
  are never returned, only their presence.
- GET /admin/logs returns the tail of backend/logs/go.log (Gin traffic
  plus application lines), bounded to 256 KiB and 500 lines so the read
  is constant-size however large the file has grown.

tailLogFile is split out from the handler and tested for the line cap,
the partial-first-line rule, and the empty/missing cases.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 23:02:57 +01:00
adamfandClaude Code 49909037db Document Microsoft Graph email auth env vars; newest bookmarks first
Deploy with Docker Compose / deploy (push) Successful in 1m4s
Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:55:35 +01:00
adamfandClaude Code ff186f04a7 Spotify unauthenticated: throttled log + admin reconnect on Listening widget
Deploy with Docker Compose / deploy (push) Successful in 40s
- Backend logs a rate-limited (1/h) "not authenticated" line when a resolver
  finds the Spotify client nil instead of silently degrading to null.
- New public-but-gated spotifyNeedsReauth query: false for everyone except
  an admin session whose backend has no client.
- The /stp Listening widget offers admins a "Reconnect Spotify" button that
  hits /api/spotify/auth and navigates to the returned authorisation URL;
  non-admins still see the widget degrade as before.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:54:48 +01:00
adamfandClaude Code 241acb82d9 Install wget in backend image so the healthcheck can run
Deploy with Docker Compose / deploy (push) Successful in 48s
The compose healthcheck probes with `wget`, but the runtime image only
installed ca-certificates, so every probe died as "executable file not
found" and autoheal restarted the container in a ~90s loop.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:46:02 +01:00
adamfandClaude Code 50c2fdfdd1 Harden job-application tracker: backend fixes, tests, UI rework
Deploy with Docker Compose / deploy (push) Successful in 1m8s
Backend (email sync + resolvers):
- Sync window anchored on latest received_at with slack + rewind age-out
- Skip ctx-cancelled per-email side effects
- Soft-deleted applications no longer block pipeline matching
- Status normalization shared between pipeline and resolvers, with tests
- Reject empty jobTitle/company on create/update
- IMAP fallback synthesizes Message-ID from stable message traits
- Consistent list ordering with id tie-break

Frontend (JobApplications.vue):
- Unified status vocabulary with pipeline (lowercase keys)
- Emptied optional fields now clear on save; row stays open on failure
- URL editable, notes textarea, appliedAt defaults to today
- Error banner, delete confirmations, inline status select
- Search, sortable columns, status-count filter tiles, stale-row marker
- CSV export with UTF-8 BOM + CRLF

Tests: stdlib table-driven tests for sync, status, auth, handlers.

Co-Authored-By: Claude Code <[email protected]>
2026-09-22 22:31:30 +01:00
adamfandClaude Code 8effc3de83 Add Bad Apple ASCII intro tile, wire into home grid
Deploy with Docker Compose / deploy (push) Successful in 22s
Co-Authored-By: Claude Code <[email protected]>
2026-09-22 21:58:11 +01:00
adamfandClaude Opus 5 fea22871cf Stop hiding private/ and templates/ from the notes editor
Deploy with Docker Compose / deploy (push) Successful in 9s
SB_SPACE_IGNORE was set to quartz's ignorePatterns, which was the wrong thing
to copy. The two settings answer different questions: quartz hides private/
because it must never be published, whereas SilverBullet is the editor, behind
the admin gate, and hiding notes from it only stops them being edited.

Now ignores .obsidian alone, which is editor config and plugin JS rather than
notes. Quartz keeps its own ignorePatterns, so /notes/ publishes exactly what
it did before; these files were already tracked in the notes repo, so nothing
becomes newly reachable.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BCQFvkvorAw1xwhd5gL2qZ
2026-09-22 13:44:48 +01:00
adamfandClaude Opus 5 507bdb5939 Let the editor request an immediate notes sync
Deploy with Docker Compose / deploy (push) Successful in 9s
Waiting out SILVERBULLET_GIT_INTERVAL is annoying when you want a note on
another device now. The sidecar's sleep is now split into short slices that
watch sync-request.md in the vault; when its modification time changes, it
syncs on the spot. The "Sync notes" toolbar button in the vault's Sync.md
writes that file.

The trigger file is deliberately never deleted here. Deleting it would fight
SilverBullet's client sync, which would re-upload its cached copy and produce
a delete/recreate loop while a tab is open; only the mtime is significant. It
is gitignored in the notes repo, so it never reaches a commit.

Signalling through a file in the shared vault rather than shell.run or a
docker socket: both containers already have that directory, so this adds no
capability to either, which is the same reasoning behind using a sidecar
instead of SilverBullet's own shell backend.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BCQFvkvorAw1xwhd5gL2qZ
2026-09-22 13:40:51 +01:00
adamfandClaude Opus 5 e5e43f3e0b Make post-login redirect leave the SPA for proxied containers
Deploy with Docker Compose / deploy (push) Successful in 27s
nginx's admin auth_request gate bounces /notes/, /sb/ and /hasura/ to
/admin/login?redirect=<path>, but Login.vue completed that with
router.push(). Those paths are other containers, not Vue routes, so the
push matched the catch-all 404 route and the user never left the SPA.

Resolve the destination first: if it lands on the route named "404" there
is no Vue route for it, so use a real document request and let nginx
proxy it. Also reject non-site-relative destinations, since the value
comes straight from the query string.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-22 13:32:51 +01:00
adamf afac428229 remove up button
Deploy with Docker Compose / deploy (push) Successful in 23s
2026-09-22 13:29:07 +01:00
adamfandClaude Opus 5 a9961217e3 Move the admin private chat into its own tab
Deploy with Docker Compose / deploy (push) Successful in 25s
The private channel was a toggle in the composer, which meant private
messages interleaved into the public feed (italic, with a lock icon) and
the send target was a piece of state separate from what you were reading.

Admins now get a Public/Private tab strip. The tab filters the list and
also decides whether a send or an upload is marked private, so you cannot
post into a channel you are not looking at. Non-admins see no tabs and no
change at all — the server already only sends private messages to admin
connections, so this is a view split, not a new trust boundary.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-22 13:12:21 +01:00
adamfandClaude Opus 5 85ab27d241 Fix silverbullet-git push failing with "No user exists for uid 1000"
Deploy with Docker Compose / deploy (push) Successful in 28s
The sidecar runs as uid 1000 so its commits match the vault's ownership on
the host, but alpine/git has no passwd entry for that uid. ssh resolves the
calling uid before it does anything else and aborts when it cannot, so every
push failed at "No user exists for uid 1000" without reaching the deploy key.

Mount a minimal passwd file that defines the uid. SilverBullet's own entrypoint
creates the user at boot for the same reason; this container has no entrypoint
of its own, so the entry is supplied as a file.

Verified on the Pi: with the mount, ssh authenticates as the silverbullet-git
deploy key; without it, the uid error reproduces.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BCQFvkvorAw1xwhd5gL2qZ
2026-09-21 15:37:27 +01:00
adamfandClaude Opus 5 fdf76f75e9 Add SilverBullet as a web editor for the Obsidian vault
Deploy with Docker Compose / deploy (push) Successful in 2m17s
Quartz renders the vault but has no write path, so editing a note meant
editing files on the Pi or pushing through git. SilverBullet serves the same
vault as an editable PWA at /sb/, behind the same nginx admin gate /notes/
uses. Quartz stays as the read view; its --serve watcher picks up SilverBullet's
writes, so /notes/ follows within seconds.

The vault is now the `notes` repo rather than `obsidian_vault`, and the
silverbullet-git sidecar commits and pushes what the editor writes while
pulling what Obsidian pushes from elsewhere. The vault's own deploy workflow
has been removed in that repo: it pulled from the old remote and restarted
quartz, and a second git process in the same clone would race the sidecar.

Notes on the configuration:

- Single-space mode, auto-detected because the mounted folder is not empty.
  SilverBullet writes no database or metadata into the vault, so the folder
  stays plain markdown that quartz and Obsidian still understand.
- /sb/ is the one proxied app whose prefix is NOT stripped. SB_URL_PREFIX=/sb
  tells the PWA its own base path and its service-worker scope is built from
  that; stripping the prefix serves a blank page with nothing in the log.
- SB_SPACE_IGNORE mirrors quartz's ignorePatterns and must be newline
  separated. A comma separated list is accepted silently and does nothing.
- No SB_USER is set, so the container is open to anything reaching it on
  app-network. The nginx auth_request gate is the only protection.
- The sidecar runs as uid 1000 to match the vault's ownership, and is a
  separate container rather than SilverBullet's own shell backend, which would
  hand anyone past the nginx gate command execution inside the container.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BCQFvkvorAw1xwhd5gL2qZ
2026-09-21 15:33:28 +01:00
adamfandClaude Opus 5 5f78628c36 Update CV work history to match current experience
Deploy with Docker Compose / deploy (push) Successful in 47s
Correct the dates on the hospitality roles in the live CV template and
name the employers behind each venue (Rose Pubs Group, Greene King,
Benugo), including the second Rose Pubs site, The Montpelier.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-20 17:25:46 +01:00
adamfandClaude Opus 5 22c6229c42 Add first test suite; fix Timer resume, scraper silent failure
Deploy with Docker Compose / deploy (push) Successful in 1m0s
Weekly Maintenance / maintenance (push) Successful in 19m9s
- backend/services/auth_test.go: token-version normalisation, the
  revocation rule, GenerateJWT/VerifyJWT claim handling. The happy path
  of AuthenticateTokenWithClaims still needs a DB driver we don't have.
- python/tests: travelodge.py's pure functions and the NDJSON event
  contract. pytest is a commented-out dev dep so the image stays slim.
- Timer.vue: the Paused screen now offers Resume, reaching pauseTimer's
  previously unreachable un-pause branch.
- travelodge.py: warn when upstream parses but yields nothing usable, so
  a field rename is distinguishable from sold-out inventory.
- CoverLetters.vue moved out of views/unused/ — it is live on /cv.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-17 02:55:18 +01:00
adamfandClaude Opus 5 25ac1cde1c Fix security issues, bugs, and convoluted code across the stack
Security:
- Token revocation. User gains a TokenVersion counter embedded in both
  tokens as a "tv" claim; AuthenticateToken rejects a token whose version
  no longer matches the row. Logout bumps it, so logging out now kills
  outstanding tokens rather than only clearing cookies. Costs one
  primary-key SELECT per authenticated request, which is the price of
  having revocation at all.
- Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by
  a per-request one-shot nonce, verified and consumed on callback.
- Private chat attachments. Attachments on private messages are written to
  /backend/uploads/private/ and served at /uploads/private/, gated by the
  same nginx auth_request admin check used for /hasura/ and /notes/.
  Private uploads are rejected from non-admin callers.
- The icecast admin UI (/radio/admin/) is behind the admin gate; listener
  traffic is untouched.
- Store caches are mutex-guarded, so -race is clean.

Bugs:
- The email pipeline no longer drops emails permanently on transient
  failure. Failures record an attempt counter and are retried up to 3
  times; the fetch window rewinds to the oldest retryable email's
  ReceivedAt, without which a retry could never re-fetch it.
- Rowing duplicate detection distinguishes ErrRecordNotFound from a real
  DB error, so a transient failure no longer causes a duplicate insert
  plus a paid Claude call.
- DeletePost propagates its delete error instead of reporting success.
- RecentlyPlayed populates the cache it reads.
- main.go exits non-zero if r.Run fails, so a port conflict is visible.
- Python: the scan truncation flag is set on every deadline path;
  timed_out is reported by the worker rather than inferred from the clock;
  date validation uses Europe/London rather than server-local time.
- Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue
  guards a missing author; Timer.vue gets an explicit state machine and
  compares total elapsed seconds; Elle.vue's comma-operator call and
  per-frame console.log are fixed.

Simplification:
- One TTLCache replaces three near-identical cache implementations, with
  the differing eviction rules as explicit parameters.
- run_scan's transport index no longer uses one object as both ordering
  record and live output; its three phases are separate functions.
- _price_hotels submits all work to a single pool, so the nested-executor
  deadlock hazard is gone by construction.
- The NDJSON event generators share one implementation.
- IMAP FETCH responses pair each line with its literal in the type, so
  callers no longer hand-skip alternate entries.
- Shared helpers for slice-of-pointers, markdown fences and auth cookies.
- Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm,
  useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks.
- nginx dev config's duplicated :80/:443 bodies share one partial.

Infra: certbot passes --deploy-hook touching a sentinel that nginx's
watcher reloads on, so renewed certs are served without a restart, and the
watcher also removes the manual restart after first issuance. db is gated
on service_healthy, autoheal is pinned, and the unused envsubst entries
are dropped.

Verified: go build/vet, npx vite build, py_compile, docker compose config
for both overlays, bash -n on all scripts, and an envsubst render of every
nginx template (no leftover placeholders, runtime vars preserved, braces
balanced).

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-16 16:12:21 +01:00
adamfandClaude Opus 5 64df70e5d2 Document codebase: comments, per-area READMEs, deployment guide
Readability pass across all four areas of the stack. Comments explain why
rather than what, concentrated at the points where behaviour is non-obvious:
concurrency, caching, auth, scraping and nginx templating.

Backend: doc comments on every exported declaration across handlers,
services, models and resolvers. Resolver commentary lives inside function
bodies so gqlgen does not strip it on regeneration; schema files use #
comments rather than description blocks so introspection output is
unchanged. Extracted the duplicated auth-cookie blocks into helpers.

Frontend: header comments on every component, store and view, including
STATUS: notes marking which of the parallel/legacy views are still live.
Documented the non-reactive animation-state pattern, the homeData hub and
the WebSocket stale-socket guard. Removed a few dead imports and named the
reconnect-backoff and poll-interval constants.

Python: module and function docstrings covering the Travelodge scraping
contract, the deadline threading, the two-executor concurrency and the
NDJSON streaming protocol.

Infra: header blocks on every compose file, nginx template, Dockerfile and
entrypoint, covering the config selection, envsubst allow-lists, rate-limit
semantics and volume persistence. Hoisted the duplicated envsubst variable
list in nginx/entrypoint.sh.

New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example,
backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which
stated a 24h access token where main.go sets 7 days.

No behaviour change. go build/vet, vite build, py_compile and docker
compose config all pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-16 15:57:48 +01:00
adamfandClaude Fable 5.1 a1102b4aa1 Fix duplicate chat messages and image reloads on reconnect
Deploy with Docker Compose / deploy (push) Successful in 1m7s
The chat store bound its handlers to the shared socket ref, so when
Chat.vue reconnected after auth resolved (isAdmin flipping), the old
socket's onclose fired after the new socket existed, nulled it, and
scheduled another reconnect. Two live sockets then pushed every
broadcast, showing each sent message or upload twice.

Handlers now check they belong to the current socket. History is sent
as a single batch event so the message list is replaced in place
instead of being emptied and refilled, which kept unmounting and
reloading every image and jumping the scroll position.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-16 15:36:06 +01:00
adamf b0822b1513 update intro
Deploy with Docker Compose / deploy (push) Successful in 20s
2026-09-16 15:32:03 +01:00
adamfandClaude Fable 5.1 6037729edd Add admin-only private chat messages and message deletion
Deploy with Docker Compose / deploy (push) Successful in 58s
Admins can flag a chat message as private so only other admin
connections receive it, and can delete any message. Admin status is
read from the auth cookies on the WebSocket upgrade request.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-16 15:22:26 +01:00
adamfandClaude Opus 5 ebb28532c3 Require sign-in for places
Deploy with Docker Compose / deploy (push) Successful in 56s
Gate the places query behind an authenticated user so the list is no
longer public, and relax the place mutations from admin-only to any
signed-in user. Hide the Places tab and skip the fetch entirely for
anonymous visitors.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UKvnE448c1FeepmxZkTezz
2026-09-14 19:58:43 +01:00
adamfandClaude Opus 5 fe6fc02b6b Open home widget create forms in popup modals
Deploy with Docker Compose / deploy (push) Successful in 23s
Weekly Maintenance / maintenance (push) Successful in 1m19s
The Places tab already popped its create form up over the page; every other
/stp widget swapped its contents for the form instead, which meant losing
sight of the list you were adding to and a cramped form inside a grid cell.

Extract the Places modal into a shared components/util/Modal.vue (teleported
backdrop, click-outside and Escape to close) and use it for the Feed, Bookmarks,
Favorites, Consumption and Rowing create forms as well. Widget headers keep
their normal titles now that each form carries its own heading in the modal.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KcFtkisHcKJuTZAnv3fVzA
2026-09-12 18:50:17 +01:00
adamfandClaude Opus 5 894c158afd Add places / things-to-do list with admin management
Deploy with Docker Compose / deploy (push) Successful in 16m21s
Backend: new Place GORM model (title, location, notes, image, category,
cost, priority, done) with auto-migration, a place.graphql schema, and
resolvers for the places query plus admin-only create/update/delete.
Regenerate gqlgen output against gqlgen v0.17.95, which requires Go 1.26 —
bump go.mod and the builder image to match.

Frontend: a places Pinia store, a CreatePlace admin form, and a
PlacesTable rendered as a new tab in the Collage cell, with inline
done-toggle and delete for admins. Rework the Admin page into a
sidebar-navigated panel layout (picking up the previously unreachable
CreateBookmark form) and give Login proper field labels, submit state,
and error feedback.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KcFtkisHcKJuTZAnv3fVzA
2026-09-12 18:10:41 +01:00
adamfandClaude Fable 5.1 f83d683180 Add cheapest-night date-range scan to the Travelodge finder
Deploy with Docker Compose / deploy (push) Successful in 52s
A second "Cheapest night" tab on /hotels scans every candidate check-in
between two dates (filtered by weekday, 1-7 nights, up to ~3 months),
keeps the N cheapest hotels per night, and prices TfL transport once per
unique hotel so the whole range fits in the streaming window.

Backend
- travelodge.py: extract _shortlist/_make_row/_price_hotels/_apply_transport
  from run_search; add a 30-minute per-(location, dates, rooms) Travelodge
  result cache, a deadline on page fetches, and run_scan (parallel date
  fetches with per-date failure isolation, one TfL lookup per hotel).
- main.py: HotelRequestBase shared by search and scan requests,
  HotelScanRequest with weekday/range validation, scan event models,
  _guarded slot wrapper, POST /hotels/scan/stream (NDJSON).
- nginx: the streaming location now matches /py/hotels/(search|scan).

Frontend
- Split CheapHotels.vue into SingleStayPanel, CheapestNightPanel,
  SharedFields, HotelRows, a shared form composable, stream/format helpers
  and hotels-shared.css; shared fields keep their values across tabs.
- Vite dev server proxies /py to the Python API.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01H5P3C1HbbEwLZEYsjwr7uV
2026-09-08 01:38:30 +01:00
adamfandClaude Fable 5.1 e445892259 Give TfL cycle lookups a single attempt
TfL can take over 15s to return 404 for destinations with no cycle route
(motorway services), and retrying that three times stalled a hotel for
almost a minute. The distance estimate covers the gap.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dphx7LL5JC8dAFYU7MMpoA
2026-09-08 00:54:33 +01:00
adamfandClaude Fable 5.1 44c08850ed Tighten TfL timeout and overlap cycle lookups
Deploy with Docker Compose / deploy (push) Successful in 34s
A hung TfL call could stall one hotel for 40s before retrying. Time out
at 15s instead, and submit the cycle-route query alongside the fare
queries so a keyed search prices each hotel in one round trip.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dphx7LL5JC8dAFYU7MMpoA
2026-09-08 00:51:18 +01:00
adamfandClaude Fable 5.1 20e958c124 Speed up cheap Travelodge finder and stream results
Deploy with Docker Compose / deploy (push) Successful in 59s
Backend: fetch Travelodge pages in parallel batches, price TfL journeys
from a worker pool throttled to the anonymous 50/min limit (500/min with
TFL_APP_KEY), cache TfL journeys for two hours, and expose a streaming
NDJSON endpoint (/hotels/search/stream) that sends the hotel list first
and one line per hotel as fares arrive. A 20-hotel search now takes
about 10 seconds instead of minutes. Every hotel also gets a cycling
time from the origin (TfL cycle routing with an app key, otherwise a
distance estimate).

Frontend: consume the stream so hotels appear immediately with a
progress bar, show three picks (best value, cheapest room, quickest
cycle) instead of one, add a rank-by toggle (stay + transport, stay
only, cycle time, travel time) and a Cycle column, and raise the hotel
cap to 40.

Nginx: match both search routes and disable proxy buffering and gzip so
the stream reaches the browser as it is produced.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dphx7LL5JC8dAFYU7MMpoA
2026-09-08 00:29:37 +01:00
adamfandClaude Fable 5.1 152f60ee32 Add Python FastAPI service, cheap hotels page, and Tailwind theme refactor
Deploy with Docker Compose / deploy (push) Successful in 1m29s
- Replace searxng and open-webui with a FastAPI `python/` service proxied
  at /py/ (Travelodge hotel search, rate-limited in nginx)
- Add CheapHotels view and CreateToggle component
- Move design tokens into Tailwind @theme in styles.css and migrate
  components/views to utility classes; CVLayout re-points tokens for light theme
- Update README, CLAUDE.md, and .gitignore accordingly

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dphx7LL5JC8dAFYU7MMpoA
2026-09-08 00:06:04 +01:00
adamf d777ea4b7d update CV
Deploy with Docker Compose / deploy (push) Successful in 46s
2026-09-07 23:35:00 +01:00
adamf fb6b4799b9 added way to write cover letters
Deploy with Docker Compose / deploy (push) Successful in 29s
Weekly Maintenance / maintenance (push) Successful in 15m15s
2026-08-18 17:45:16 +01:00
adamf 64672dfdc8 Speed up deploy times
Deploy with Docker Compose / deploy (push) Successful in 5m30s
2026-08-18 17:27:48 +01:00
adamf 557f92b39a Update CV and add mobile automata simulator
Deploy with Docker Compose / deploy (push) Successful in 19m2s
2026-08-18 12:20:07 +01:00
adamfandClaude Fable 5 127ce95473 Fix mismatched closing strong tag
Deploy with Docker Compose / deploy (push) Successful in 22m22s
Weekly Maintenance / maintenance (push) Successful in 8m40s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-11 20:35:47 +01:00
adamfandClaude Fable 5 9a7fdc6e30 Update CV: add profile section, dissertation, and receipt_maker project
Deploy with Docker Compose / deploy (push) Has been cancelled
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-11 20:35:27 +01:00
adamf eaad5c3ef3 Update CV
Deploy with Docker Compose / deploy (push) Successful in 32s
Weekly Maintenance / maintenance (push) Successful in 23m10s
2026-07-07 13:24:22 +01:00
adamf b58a46d20b Add waterloo transcript to website
Deploy with Docker Compose / deploy (push) Successful in 6m42s
2026-07-07 12:20:25 +01:00
adamf 4f16b000bc Update CV, make programming first selected CV and hide others
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-07-07 12:19:23 +01:00
adamf 3e25b3d51f Add education header
Deploy with Docker Compose / deploy (push) Successful in 20s
Weekly Maintenance / maintenance (push) Failing after 25m25s
2026-06-22 19:53:43 +01:00
adamf f272bd7920 Add education header
Deploy with Docker Compose / deploy (push) Successful in 34s
2026-06-22 19:51:31 +01:00
adamfandClaude Opus 4.7 09e991580c Add weekly maintenance workflow
Deploy with Docker Compose / deploy (push) Successful in 19m38s
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-22 16:05:48 +01:00
adamf c773098d32 Move education to top
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-06-22 15:48:46 +01:00
adamfandClaude Opus 4.7 aa14b4c185 Pin Listening header so only song content scrolls
Deploy with Docker Compose / deploy (push) Successful in 4m36s
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-28 10:53:43 +01:00
adamfandClaude Opus 4.7 06a18eac3d Remove link from Daisy Green Holland Park entry
Deploy with Docker Compose / deploy (push) Has been cancelled
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-28 10:50:16 +01:00
adamfandClaude Opus 4.7 a8debe2f51 Remove Air Cadet Force qualification from Programming CV
Deploy with Docker Compose / deploy (push) Successful in 22m38s
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-26 12:25:32 +01:00
adamfandClaude Opus 4.7 548f2350d2 Add Daisy Green Holland Park to hospitality experience
Deploy with Docker Compose / deploy (push) Has been cancelled
Adds the new Daisy Green Holland Park role (May 2026 – Present) to
CVHospitality, and expands CVProgramming's hospitality section to
list each venue individually.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-26 12:24:20 +01:00
adamf 3f5803d4fc Hatsune miku menu first commit
Deploy with Docker Compose / deploy (push) Successful in 4m3s
2026-05-19 14:57:36 +01:00
adamfandClaude Opus 4.7 60bd906251 Add school grades and Air Cadets to Programming CV
Deploy with Docker Compose / deploy (push) Successful in 3m41s
Adds University Academy of Engineering Southbank section with A-Level
and GCSE grades, plus CVQO Level 2 BTEC via the Air Cadet Force.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-18 22:46:49 +01:00
adamf 7d888ea4cb Adding hatsune miku images
Deploy with Docker Compose / deploy (push) Successful in 38s
2026-05-14 12:42:49 +01:00
adamf 3b14c3453c Include grades
Deploy with Docker Compose / deploy (push) Successful in 1m1s
2026-05-13 09:45:50 +01:00
adamfandClaude Opus 4.7 842943e7e8 Add Analyst CV template
Deploy with Docker Compose / deploy (push) Successful in 27m35s
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-05-13 08:56:51 +01:00
adamfandClaude Opus 4.7 aa6de883be Move Open-WebUI to chat.${DOMAIN} subdomain
Deploy with Docker Compose / deploy (push) Successful in 34s
Open-WebUI's SvelteKit frontend hardcodes asset/API paths at build time,
so subpath hosting under /openwebui/ produced 404s on /_app/... assets.
Move it to its own subdomain so it can run at root.

- certbot: request cert with chat.${DOMAIN} as a third SAN via --expand
- nginx (prod): drop /openwebui blocks; add chat.${DOMAIN} HTTP redirect
  + HTTPS server with the existing admin auth gate
- nginx (dev): drop /openwebui blocks (no chat.localhost in dev)
- compose: WEBUI_URL points to https://chat.${DOMAIN}

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-04-30 17:29:29 +01:00
adamfandClaude Opus 4.7 26a35719eb Add Open-WebUI service behind /openwebui/ admin gate
Deploy with Docker Compose / deploy (push) Successful in 13m13s
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-04-30 15:51:27 +01:00
adamf 3844a32751 Big formatting spree
Deploy with Docker Compose / deploy (push) Successful in 3m50s
2026-04-29 09:06:41 +01:00
adamf b41e67fe1a Making all CV's abide by same styling
Deploy with Docker Compose / deploy (push) Successful in 16s
2026-04-27 11:45:15 +01:00
adamf 9bcb21910d Making all CV's abide by same styling
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-04-27 11:45:01 +01:00
adamfandClaude Sonnet 4.6 a116ec2614 Add Programming CV and revise General CV layout and content
Deploy with Docker Compose / deploy (push) Successful in 24s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-25 16:58:56 +01:00
adamfandClaude Opus 4.6 6f204d4164 Revise Electrical CV layout and content
Deploy with Docker Compose / deploy (push) Successful in 18s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-24 03:51:55 +01:00
adamfandClaude Opus 4.6 de803dea9f Add To The Rise Bakery to Hospitality CV and trim interests
Deploy with Docker Compose / deploy (push) Successful in 33s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-23 14:59:48 +01:00
adamfandClaude Opus 4.6 a520944fe3 Align Hospitality CV layout with General CV style
Deploy with Docker Compose / deploy (push) Successful in 4m36s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-23 14:53:49 +01:00
adamf 22a836cb95 Add other CVs back
Deploy with Docker Compose / deploy (push) Successful in 21m27s
2026-04-23 13:58:55 +01:00
adamfandClaude Opus 4.7 12967c573b Rewrite Electrical CV in a more natural voice
Deploy with Docker Compose / deploy (push) Successful in 18s
Drop the Crown and Anchor entry and rework Profile, Key Strengths,
Experience and Additional so the copy reads more like something I'd
actually write rather than polished boilerplate.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-04-21 12:21:40 +01:00
adamfandClaude Opus 4.7 14233e88a8 Generalize Electrical CV and drop Why Electrical section
Deploy with Docker Compose / deploy (push) Successful in 21s
Rework the apprenticeship-specific profile into a general electrical
apprenticeship pitch, folding in the useful framing from Why Electrical,
and tighten experience and Additional copy.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-04-21 12:12:10 +01:00
adamfandClaude Opus 4.7 2bcb47a1a1 Add Electrical CV template for apprenticeship applications
Deploy with Docker Compose / deploy (push) Successful in 23s
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-04-21 12:08:17 +01:00
adamfandClaude Opus 4.6 8636dfedb9 Replace go-imap library with custom IMAP client, simplify CV layout styles, bump vite, move SEED_DB to backend
Deploy with Docker Compose / deploy (push) Successful in 5m19s
- Rewrite email_imap.go to use a minimal hand-rolled IMAP client instead of go-imap/go-message,
  for better compatibility with Outlook's non-standard responses
- Consolidate and simplify CVLayout.vue CSS overrides
- Bump vite from 7.1.11 to 7.3.2
- Move SEED_DB env var from nginx to backend in dev compose
- Add /app/src/wasm volume exclusion in dev compose

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-18 08:53:34 +01:00
adamfandClaude Opus 4.6 c20b1c2691 Fix CV layout colors: force transparent bg on links, inherit color on td/textarea
Deploy with Docker Compose / deploy (push) Successful in 11m24s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-18 08:14:47 +01:00
adamfandClaude Opus 4.6 0b6ffedb70 Add padding below headers in Listening/Steam and adjust layout sizing
Deploy with Docker Compose / deploy (push) Successful in 27s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-16 02:57:54 +01:00
adamfandClaude Opus 4.6 a14b78a1b9 Add CreateBookmark form with toggle in Bookmarks header
Deploy with Docker Compose / deploy (push) Successful in 25s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-16 02:51:51 +01:00
adamfandClaude Opus 4.6 254541a370 Center ToggleHeader button vertically in LinkTable
Deploy with Docker Compose / deploy (push) Successful in 20s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-16 02:49:38 +01:00
adamf f390bf82cc Resize bookmark headers
Deploy with Docker Compose / deploy (push) Successful in 20s
2026-04-16 00:42:53 +01:00
adamfandClaude Opus 4.6 b96b7d7a93 Split schema.graphql and schema.resolvers.go into per-domain files
Deploy with Docker Compose / deploy (push) Successful in 3m36s
Move Query/Mutation field declarations from the monolithic schema.graphql
into each domain's .graphql file using extend type, so gqlgen places
resolvers in the matching *.resolvers.go files. Extract helper functions
into *_helpers.go files to prevent gqlgen from commenting them out.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-15 18:57:23 +01:00
adamf 37171478b1 refactored code, removed *_helper.go files and placed them in *.resolvers.go files for uniformity
Deploy with Docker Compose / deploy (push) Successful in 3m23s
2026-04-15 18:33:19 +01:00
adamfandClaude Opus 4.6 00364aca23 Fix nginx stale DNS caching causing backend to appear down after restarts
Deploy with Docker Compose / deploy (push) Successful in 22s
Use Docker's embedded DNS resolver (127.0.0.11) with nginx variables in
proxy_pass directives so upstream hostnames are re-resolved at runtime
instead of being cached forever at startup.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-15 16:29:50 +01:00
adamfandClaude Opus 4.6 3d97ccf38c Switch IMAP library from go-imap/v2 to v1 for Outlook compatibility
Deploy with Docker Compose / deploy (push) Successful in 4m16s
go-imap/v2's strict wire parser rejects Outlook's non-standard IMAP
login responses. v1 is more lenient and handles these gracefully.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-15 14:16:04 +01:00
adamfandClaude Opus 4.6 1e22bacdc9 Add email sync service for automated job application tracking
Deploy with Docker Compose / deploy (push) Successful in 4m40s
Background poller fetches emails via IMAP or Microsoft Graph API,
classifies them with Claude Haiku, and creates/updates JobApplication
records automatically. Includes manual sync endpoint and OAuth callback.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-15 13:59:24 +01:00
adamf 8d10f75f2b Move bookmarks to home folder, reduce header size and fix import link
Deploy with Docker Compose / deploy (push) Successful in 28s
2026-04-14 17:31:53 +01:00
adamfandClaude Sonnet 4.6 68dca953f2 Restore JS scroll animations, move WASM AutoScroll to util/wasm/
Deploy with Docker Compose / deploy (push) Successful in 17s
Revert AutoScroll and Headline components to their original JS
requestAnimationFrame implementations. Keep the WASM-based AutoScroll
as an alternative at util/wasm/AutoScroll.vue.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 16:53:32 +01:00
adamfandClaude Sonnet 4.6 c684fcb858 Reduce toggle button size by half
Deploy with Docker Compose / deploy (push) Successful in 22s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 16:49:37 +01:00
adamfandClaude Sonnet 4.6 2b5745b946 Move scroll animations to Rust/WASM, enable Hasura, and move bookmarks to home sidebar
Deploy with Docker Compose / deploy (push) Successful in 12m7s
Port AutoScroll and Headline scroll logic from Vue/JS to Rust compiled
to WASM via wasm-pack. Add multi-stage Docker build for WASM compilation,
Vite WASM plugins, and top-level await for WASM init. Enable Hasura
service in docker-compose. Move bookmarks from a separate route to an
inline sidebar component on the home page. Fix ToggleHeader click
propagation.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 16:34:24 +01:00
adamfandClaude Sonnet 4.6 b56f8253d9 Harden backend against critical and high security vulnerabilities
Deploy with Docker Compose / deploy (push) Successful in 3m51s
- Fix WebSocket CheckOrigin to use proper url.Parse instead of string stripping
- Add admin auth checks to Users/User GraphQL queries
- Remove GraphQL GET transport to prevent CSRF via cross-site links
- Add application-level IP-based login rate limiting (5 attempts/min)
- Add path traversal bounds check on radio file upload
- Require DEV_MODE for GraphQL introspection and playground
- Move notes backend endpoint behind admin middleware
- Add dedicated Nginx rate limit zone for GraphQL (10r/s)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 13:27:33 +01:00
adamfandClaude Opus 4.6 798c8e7f50 Fix horizontal scrollbar and style slim themed scrollbars for Chrome/Edge
Deploy with Docker Compose / deploy (push) Successful in 22s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-14 13:18:13 +01:00
adamfandClaude Sonnet 4.6 0e7f34edc7 Update README with recent features and route changes
Deploy with Docker Compose / deploy (push) Successful in 3m34s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 11:08:42 +01:00
adamfandClaude Sonnet 4.6 7aff171ef8 Remove REST handlers superseded by GraphQL resolvers
Deploy with Docker Compose / deploy (push) Has been cancelled
Deleted handle_activity.go, handle_favorites.go, handle_post.go, and
handle_user.go — all logic already exists in schema.resolvers.go.
Removed corresponding REST routes from main.go. Moved UserCredentials
struct (used by Login handler) into handle_auth.go.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 11:08:09 +01:00
adamfandClaude Sonnet 4.6 cc6a423ef0 Add backend healthcheck and autoheal for automatic restart
Deploy with Docker Compose / deploy (push) Successful in 19s
Adds a Docker healthcheck to the backend service (polling GET / every 30s)
and the willfarrell/autoheal container to automatically restart any unhealthy containers.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-14 10:59:48 +01:00
adamfandClaude Opus 4.6 759614e92d Add job application quick reference for storing profile links and experience
Deploy with Docker Compose / deploy (push) Successful in 3m34s
Auth-protected CRUD for personal info (LinkedIn, GitHub, etc.) and
experience entries, stored in the database so nothing sensitive is in
the public repo. Displayed as a categorized panel on the Job Applications page.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-13 12:38:53 +01:00
adamfandClaude Opus 4.6 81c5684102 Fix appliedAt date format to RFC3339 for GraphQL mutations
Deploy with Docker Compose / deploy (push) Successful in 15s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-13 12:34:12 +01:00
adamfandClaude Sonnet 4.6 a911e6ca69 Add inline admin create forms to home page components
Deploy with Docker Compose / deploy (push) Successful in 28s
Lazy-load create forms (Post, Activity, Favorite, Rowing) directly
into their corresponding home components with an admin-only toggle
button, replacing the need to navigate to the admin page.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 12:13:13 +01:00
adamfandClaude Sonnet 4.6 66f32cdbd2 Add database-backed bookmarks via GraphQL
Deploy with Docker Compose / deploy (push) Successful in 3m47s
Replace hardcoded bookmarks in the frontend with a GORM-backed Bookmark
model exposed through GraphQL query and admin-only create/delete mutations.
Frontend groups bookmarks by category dynamically from the store.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 12:04:13 +01:00
adamfandClaude Sonnet 4.6 390f69858c Redirect to original URL after admin login
Deploy with Docker Compose / deploy (push) Successful in 3m49s
Pass the requested URI as ?redirect= when nginx denies access, so the
login page can forward the user to their intended destination on success.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:55:42 +01:00
adamfandClaude Sonnet 4.6 c3db00abf2 Fix logout not clearing cookies due to missing path and domain
Deploy with Docker Compose / deploy (push) Has been cancelled
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:53:42 +01:00
adamfandClaude Sonnet 4.6 4a0300d4b4 Fix auth guard watcher to use Vue 3 watch instead of $watch
Deploy with Docker Compose / deploy (push) Successful in 19s
$watch is a Vue 2 instance method not available on Pinia stores.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:48:27 +01:00
adamfandClaude Sonnet 4.6 18b50f1ce6 Split admin login into its own route and add auth guard to /admin
Deploy with Docker Compose / deploy (push) Successful in 28s
- Add /admin/login route for Login.vue as a standalone page
- Add requiresAdmin guard to /admin route
- Update auth guard redirect to /admin/login with redirect query param
- Update nginx @auth_denied to redirect to /admin/login
- Remove Login component from Admin.vue; drop v-if auth checks (guard handles access)
- Remove stale view files from old views/ structure (moved in prior commit)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:19:10 +01:00
adamfandClaude Sonnet 4.6 4d154ff837 Reorganise views/ directory structure to match routes
Deploy with Docker Compose / deploy (push) Successful in 16s
Move shrines and bookmarks under home/, landing and 404 into own
subdirectories, and retire Notes.vue (served by external service).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:15:46 +01:00
adamfandClaude Sonnet 4.6 869d9a168e Move admin auth guard to Vue Router
Deploy with Docker Compose / deploy (push) Successful in 24s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:09:12 +01:00
adamfandClaude Sonnet 4.6 fc9d3c97bf Add Jobs link to CV and fix auth race on job applications page
Deploy with Docker Compose / deploy (push) Successful in 19s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 11:03:00 +01:00
adamfandClaude Sonnet 4.6 0dc1c278c2 Move job applications to /cv/jobs route and add layout system
Deploy with Docker Compose / deploy (push) Successful in 3m41s
- Add DefaultLayout and CVLayout with nested routing
- Job applications is now a standalone page at /cv/jobs with a back link
- Remove JobApplications embed from CV.vue

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 10:09:22 +01:00
adamfandClaude Sonnet 4.6 a0f99d9fba Add CSV export to job applications tracker
Deploy with Docker Compose / deploy (push) Successful in 3m29s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 09:53:30 +01:00
adamfandClaude Sonnet 4.6 8f3c369ed8 Add job application tracker (admin-only)
Deploy with Docker Compose / deploy (push) Has been cancelled
Full CRUD GraphQL API for tracking job applications with status workflow.
Frontend component in CV view, hidden from print. Login now redirects to
intended route after auth via query param.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-13 09:51:31 +01:00
adamfandClaude Opus 4.6 81f5fafb61 Redirect auth-denied users to /admin login page instead of homepage
Deploy with Docker Compose / deploy (push) Successful in 23s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-12 22:05:22 +01:00
adamfandClaude Opus 4.6 c335bf14d6 Add token refresh to ValidateAdmin for seamless session renewal
Deploy with Docker Compose / deploy (push) Successful in 3m55s
When the access token is missing or expired, the handler now falls back
to the refresh token, verifies the user is still admin via DB lookup,
and issues fresh cookies in the subrequest response.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-12 21:35:45 +01:00
adamfandClaude Opus 4.6 d344497393 Gate searxng, notes, and hasura behind admin auth via nginx auth_request
Deploy with Docker Compose / deploy (push) Has been cancelled
Add ValidateAdmin endpoint that checks JWT admin claim for use as an
nginx auth_request subrequest. Widen cookie path from backend endpoint
to "/" so the access_token is sent on all paths. Extend access token
lifetime from 24h to 7 days. Disable hasura service by default via
Docker profile.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-12 21:33:41 +01:00
adamfandClaude Opus 4.6 ee97ec9b23 Pin app-network subnet to match trusted proxy CIDR
Deploy with Docker Compose / deploy (push) Successful in 38s
Gin's trusted proxies list is hardcoded to 172.28.0.0/16, but Docker was
assigning the bridge network whatever subnet was free, so c.ClientIP()
often returned nginx's container IP instead of the real client.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-11 00:43:29 +01:00
adamfandClaude Opus 4.6 34934e7d13 Enable gin release mode outside dev
Deploy with Docker Compose / deploy (push) Successful in 3m53s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-11 00:38:44 +01:00
adamf 1d472d382b Remove padding beneath header
Deploy with Docker Compose / deploy (push) Successful in 15s
2026-04-08 01:33:26 +01:00
adamf 4ebe886579 Remove padding beneath header
Deploy with Docker Compose / deploy (push) Successful in 24s
2026-04-08 01:32:02 +01:00
adamf dd5412cb79 Fix sidebar on mobile
Deploy with Docker Compose / deploy (push) Successful in 15s
2026-04-08 01:30:03 +01:00
adamf 4000baf755 Fix mobile heights
Deploy with Docker Compose / deploy (push) Successful in 20s
2026-04-08 01:26:00 +01:00
adamfandClaude Opus 4.6 a15aa040f4 Remove horizontal side-scrolling on Home page
Deploy with Docker Compose / deploy (push) Successful in 5m35s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-08 00:35:17 +01:00
adamf a03cce3e04 Comment on AI slop and fix ai slop
Deploy with Docker Compose / deploy (push) Successful in 7s
2026-04-07 16:46:31 +01:00
adamfandClaude Opus 4.6 400d100426 Consolidate readme.md and README.md into single comprehensive README
Deploy with Docker Compose / deploy (push) Successful in 7s
Merges both files and adds full endpoint reference, .env variable table,
setup guides (Spotify, Certbot, Obsidian/Quartz, Icecast), deprecated
endpoint notes, and updated architecture with all services.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 16:16:37 +01:00
adamfandClaude Opus 4.6 7afd1be81b Add Gitea entrypoint to generate app.ini from template on startup
Deploy with Docker Compose / deploy (push) Successful in 6s
Since app.ini is gitignored, the container needs to create it at
runtime. The entrypoint copies the template on first start, then
Gitea's env var overrides handle secrets.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:40:38 +01:00
adamfandClaude Opus 4.6 cdcef5ba96 Gitignore gitea app.ini and remove INTERNAL_TOKEN from template
Runtime config (app.ini) should not be tracked since secrets are
injected via env vars in docker-compose. The template remains as
source of truth. INTERNAL_TOKEN is removed from the template as
it is set exclusively via GITEA__security__INTERNAL_TOKEN env var.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:37:30 +01:00
adamfandClaude Opus 4.6 494f61f9c6 Reduce secret syncing to just .env
Deploy with Docker Compose / deploy (push) Successful in 7s
Strip hardcoded secrets from gitea/config/app.ini (already injected
via GITEA__ env vars) and commit it to git. Add download.sh to fetch
the act_runner binary on demand instead of syncing it. Everything else
(searxng settings, certbot certs, runner registration, Spotify tokens)
is generated at runtime.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:22:50 +01:00
adamfandClaude Opus 4.6 67771777cd Fix searxng upstream entrypoint path
Deploy with Docker Compose / deploy (push) Successful in 10s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:11:39 +01:00
adamfandClaude Opus 4.6 c4c642073d Replace envsubst with sed in searxng entrypoint to avoid extra dependencies
Deploy with Docker Compose / deploy (push) Successful in 9s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:10:03 +01:00
adamfandClaude Opus 4.6 8da6364e6e Fix searxng Dockerfile: use xbps-install for Void Linux base image
Deploy with Docker Compose / deploy (push) Failing after 6s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:09:19 +01:00
adamfandClaude Opus 4.6 6f2a32aabb Install gettext in searxng container for envsubst support
Deploy with Docker Compose / deploy (push) Failing after 6s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 14:07:57 +01:00
adamfandClaude Opus 4.6 75f4608d34 Fix searxng entrypoint: use sh instead of bash for Alpine compatibility
Deploy with Docker Compose / deploy (push) Successful in 7s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:45:56 +01:00
adamfandClaude Opus 4.6 2e3d5f4dbe Use fetch+reset in deploy workflow to avoid merge conflicts
Deploy with Docker Compose / deploy (push) Successful in 48s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:40:08 +01:00
adamfandClaude Opus 4.6 258d97757c Add README documenting untracked files and sync-secrets script
Deploy with Docker Compose / deploy (push) Failing after 1s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:39:00 +01:00
adamfandClaude Opus 4.6 4edc5b1b22 Remove uptime-kuma and wallabag services, fix searxng base URL
Deploy with Docker Compose / deploy (push) Failing after 1s
Remove unused uptime-kuma and wallabag services from docker-compose,
nginx configs, and vite proxy. Use BASE_URL env var in searxng
settings template instead of hardcoded URL.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:37:24 +01:00
adamfandClaude Opus 4.6 bfefbb1d2a Skip SSH host key check for localhost in deploy workflow
Deploy with Docker Compose / deploy (push) Successful in 7s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:24:15 +01:00
adamfandClaude Opus 4.6 5d3c73d537 Fix deploy: use localhost instead of Docker-internal hostname for git pull
Deploy with Docker Compose / deploy (push) Has been cancelled
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:23:32 +01:00
adamfandClaude Opus 4.6 4c8573767d Secure gitea-runner: remove tracked secrets, use SSH for deploy
Deploy with Docker Compose / deploy (push) Failing after 1s
- Untrack .runner (contains registration token), act_runner binary, and nohup.out
- Add gitea-runner sensitive files to .gitignore
- Auto-register runner from env var if .runner is missing
- Switch deploy workflow git pull from HTTP to SSH

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:19:45 +01:00
adamf 4d16dd8d17 Use binary gitea runner to avoid stress
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-04-07 13:15:35 +01:00
adamfandClaude Opus 4.6 d04496ad11 Remove gitea-runner service and related files
Deploy with Docker Compose / deploy (push) Waiting to run
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:14:17 +01:00
adamfandClaude Opus 4.6 6edca785ff Fix proxy_pass path stripping for wallabag and uptime-kuma
Add trailing slash to proxy_pass so nginx strips the subpath prefix
before forwarding requests to the upstream containers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:10:41 +01:00
adamfandClaude Opus 4.6 74f606459f Build gitea-runner with docker CLI installed natively
Deploy with Docker Compose / deploy (push) Waiting to run
Mounting host docker binary failed due to glibc/musl incompatibility.
Instead, extend the act_runner image and install docker-cli and
docker-cli-compose via apk.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:02:06 +01:00
adamfandClaude Opus 4.6 ce1a1ee757 Mount docker CLI and compose plugin into gitea-runner
Deploy with Docker Compose / deploy (push) Failing after 0s
The act_runner container had the Docker socket but not the docker
binary, so deploy workflow steps using docker compose failed.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 13:00:50 +01:00
adamfandClaude Opus 4.6 68b9985d99 Use HTTP URL for git pull in deploy workflow
Deploy with Docker Compose / deploy (push) Failing after 0s
The act_runner container lacks SSH, so pull via HTTP using the
Docker network hostname instead of the named SSH remote.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-07 12:59:51 +01:00
adamf a967a249c2 Add base url to new containers
Deploy with Docker Compose / deploy (push) Failing after 0s
2026-04-07 12:57:16 +01:00
adamfandClaude Sonnet 4.6 8a6e34dd69 Fix gitea-runner compatibility for deploy workflow
Deploy with Docker Compose / deploy (push) Failing after 1s
Mount the deploy directory at the same absolute path in the runner
container so docker compose bind mounts resolve correctly on the host
Docker daemon. Add git safe.directory config to avoid ownership errors
when the runner (root) operates on host-owned files.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-07 12:45:52 +01:00
adamf f027506c87 Add label to gitea runner
Deploy with Docker Compose / deploy (push) Failing after 2s
2026-04-07 12:22:04 +01:00
adamf 54ab64c67d Remove CI-CD and use Deploy
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-04-07 12:19:26 +01:00
adamfandClaude Sonnet 4.6 108f58e527 Add UptimeKuma, Searxng, Wallabag services
CI/CD / Deploy (push) Has been cancelled
CI/CD / Build Frontend (push) Has been cancelled
CI/CD / Build & Test Backend (push) Has been cancelled
Deploy with Docker Compose / deploy (push) Has been cancelled
- Add uptime-kuma, searxng, and wallabag Docker services with Postgres integration for wallabag
- Add nginx reverse proxy location blocks for /uptime-kuma/, /searxng/, /wallabag/ in both prod and dev templates
- Update entrypoint.sh envsubst to include new HOST/PORT vars
- Add Vite dev proxy entries for all three services
- Update gitea-runner config: add self-hosted label and allow all volumes
- Add Gitea CI/CD workflow

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-07 12:14:56 +01:00
adamfandClaude Opus 4.6 e62424368b Fix Quartz layout export name to match v4.4.0 expected import
Deploy with Docker Compose / deploy (push) Successful in 8s
Rename sharedLayout to sharedPageComponents to fix build errors in
Quartz emitters (contentPage, tagPage, folderPage, 404).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-04-06 23:14:10 +01:00
adamfandClaude Sonnet 4.6 e17a7a9807 Remove graph component from Quartz to fix browser crash
Deploy with Docker Compose / deploy (push) Successful in 10s
Add custom quartz.layout.ts overriding the default layout to remove
Component.Graph(), the D3 force-directed graph known to crash browsers
on large note sets.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-06 23:10:35 +01:00
adamf 67f3895a1e Fix quartz causing browser crash
Deploy with Docker Compose / deploy (push) Successful in 10s
2026-04-06 23:05:33 +01:00
adamf 058ae3b3f1 Change /notes/ to be a normal link instead of routerlink
Deploy with Docker Compose / deploy (push) Successful in 18s
2026-04-06 22:59:37 +01:00
adamf 282454140f Remove max height from image in chat and change breakpoint for mobile
Deploy with Docker Compose / deploy (push) Successful in 14s
2026-04-06 22:55:46 +01:00
adamf 6029066a94 Update notes link to quartz
Deploy with Docker Compose / deploy (push) Successful in 22s
2026-04-06 14:04:16 +01:00
adamf 01adee7941 Revert quartz changes
Deploy with Docker Compose / deploy (push) Successful in 9s
2026-04-06 13:58:57 +01:00
adamfandClaude Sonnet 4.6 1f6c540c1c Fix Quartz not reading mounted content directory
Deploy with Docker Compose / deploy (push) Successful in 15s
Pass --directory /content so quartz build reads from the volume mount
instead of the default /quartz/content path.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-06 13:53:04 +01:00
adamf fa79fe9cdb Fix path
Deploy with Docker Compose / deploy (push) Successful in 9s
2026-04-06 13:46:36 +01:00
adamf 83c130b5c3 Fix path
Deploy with Docker Compose / deploy (push) Successful in 10s
2026-04-06 13:42:55 +01:00
adamfandClaude Sonnet 4.6 b6623de23a Add Quartz service for serving Obsidian notes at /notes/
Deploy with Docker Compose / deploy (push) Successful in 2m28s
Replaces the custom Go/Vue notes system with Quartz v4, a polished
static site generator for Obsidian vaults. Mounts OBSIDIAN_DIR as the
Quartz content directory and serves it at /notes/ with hot-reload via
`npx quartz build --serve`.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-04-06 13:27:10 +01:00
adamf 7e8e50f80a Remove tailwind css from stylesheet and updated CV general to conform to ATS standards
Deploy with Docker Compose / deploy (push) Successful in 25s
2026-04-01 20:25:58 +01:00
adamfandClaude Opus 4.6 a44011bf0b Add disable/enable toggle for radio fallback songs
Deploy with Docker Compose / deploy (push) Successful in 3m27s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 16:47:04 +01:00
adamfandClaude Opus 4.6 d215333128 Add admin UI for managing radio fallback music
Deploy with Docker Compose / deploy (push) Successful in 3m44s
Upload, list, and delete fallback music files from the admin page.
Backend handlers validate file type/size and prevent path traversal.
Nginx max body size increased to 50M to support large audio files.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 16:19:10 +01:00
adamfandClaude Opus 4.6 179f52d1d7 Make CV pages responsive for mobile viewports
Deploy with Docker Compose / deploy (push) Successful in 20s
Add flex-wrap, stacked layouts on small screens, and mobile-friendly
a4page/skills-grid styles across all CV variants.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 03:11:42 +01:00
adamfandClaude Opus 4.6 08c29a77a0 Separate Links header from justify-between layout
Deploy with Docker Compose / deploy (push) Successful in 15s
Move site and social link groups into their own flex container
so justify-between spaces them apart without including the header.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 03:04:22 +01:00
adamfandClaude Opus 4.6 e69942a7e8 Cap image max-width in CommitHistory and Steam for responsive layout
Deploy with Docker Compose / deploy (push) Successful in 18s
Prevents avatar and game images from stretching too wide when sidebars
expand to 95vw at the 1360px breakpoint.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 03:00:16 +01:00
adamfandClaude Opus 4.6 d268fea4be Fix Listening component preventing grid from shrinking and improve responsive layout
Deploy with Docker Compose / deploy (push) Successful in 14s
Remove fixed width/height attributes from album art image that set a minimum
intrinsic size, add fluid image styles, and improve mobile grid layout.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 02:57:09 +01:00
adamfandClaude Opus 4.6 d7178ac60a Refactor home grid layout to use grid-template-areas
Deploy with Docker Compose / deploy (push) Successful in 14s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 02:46:28 +01:00
adamfandClaude Opus 4.6 b48a273916 Match sidebar margin and gap to grid on home page
Deploy with Docker Compose / deploy (push) Successful in 14s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 02:43:06 +01:00
adamfandClaude Opus 4.6 24fd4dd00c Improve home page responsive layout and overflow handling
Deploy with Docker Compose / deploy (push) Successful in 19s
Rework media query breakpoints and grid placement for better
tablet/mobile display. Add overflow-auto to Radio, Links, and
Listening components. Add Links header. Simplify Intro2 animation
initial positions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-30 02:38:21 +01:00
adamfandClaude Opus 4.6 75cede3b1b Fix security vulnerabilities across backend, frontend, and infra
Deploy with Docker Compose / deploy (push) Successful in 4m44s
- Fix auth bypass in UpdatePost/DeletePost (missing return after auth check)
- Remove Spotify access token from callback response
- Replace internal error messages with generic responses in all handlers
- Harden GraphQL: complexity limit, disable playground/introspection in prod
- Add security headers (X-Frame-Options, HSTS, etc.) to nginx
- Disable Hasura console/dev mode in production
- Add DOMPurify sanitization to Markdown component
- Fix cookie removal to use correct domain/path from auth config
- Fix nil dereference in rowing handler when Claude API errors
- Fix wildcard CORS on stamp endpoint
- Pin nginx and certbot Docker image versions

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-29 23:59:10 +01:00
adamfandClaude Opus 4.6 091bfcaef6 Add Hasura GraphQL Engine container with nginx proxy
Deploy with Docker Compose / deploy (push) Successful in 1m31s
Adds Hasura v2.44.0 service connected to the existing Postgres database,
proxied through nginx at /hasura/ with WebSocket support for the console.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-29 20:06:19 +01:00
adamf 24bb0195e9 small fixes
Deploy with Docker Compose / deploy (push) Successful in 24s
2026-03-29 19:52:53 +01:00
adamfandClaude Opus 4.6 ce091d3918 Update readme with Steam integration, landing page, and architecture changes
Deploy with Docker Compose / deploy (push) Successful in 10s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-28 12:40:37 +00:00
adamf 461729809e Fixing template by removing margins and spacing nicely
Deploy with Docker Compose / deploy (push) Successful in 16s
2026-03-27 15:16:43 +00:00
adamf 89119c1702 Fix halftone acroll whole app
Deploy with Docker Compose / deploy (push) Successful in 24s
2026-03-27 14:30:48 +00:00
adamf 0f9695b8aa Increase size of breakpoint on footer
Deploy with Docker Compose / deploy (push) Successful in 14s
2026-03-27 14:26:16 +00:00
adamfandClaude Sonnet 4.6 7007f8292d Add hide-sm utility class to Footer for responsive module hiding
Deploy with Docker Compose / deploy (push) Successful in 15s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-27 14:25:13 +00:00
adamfandClaude Sonnet 4.6 f7d69f048e Polish CV components: add print button, fade transition, and list styling
Deploy with Docker Compose / deploy (push) Successful in 19s
- Add Print button and fade transition between CV variants in CV.vue
- Fix bullet point styling with list-disc list-inside across all CV variants
- Minor content tweaks: reorder modules, fix date range, reformat text

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-27 14:21:42 +00:00
adamfandClaude Sonnet 4.6 31d4b4c268 Refactor CV into separate role-specific components and misc frontend tweaks
Deploy with Docker Compose / deploy (push) Successful in 4m6s
Split CV.vue into CVGeneral, CVBackend, CVFrontend, and CVHospitality variants.
Also adds halftone body class, reformats index.html, and minor style/layout fixes.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-27 14:03:00 +00:00
adamf 7f01b1a296 Finishing touches
Deploy with Docker Compose / deploy (push) Successful in 15s
2026-03-26 11:49:16 +00:00
adamf 89d3d8eefb Fix mid screen breakpoint because spotify img would glitch
Deploy with Docker Compose / deploy (push) Successful in 17s
2026-03-26 11:43:22 +00:00
adamfandClaude Opus 4.6 31a8c93c86 Fix home page alignment and add border to main grid container
Deploy with Docker Compose / deploy (push) Successful in 19s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 11:32:43 +00:00
adamfandClaude Opus 4.6 932e257152 Add HTTPS support in dev mode and fix mobile layout issues
Deploy with Docker Compose / deploy (push) Successful in 4m19s
Generate self-signed certs for local HTTPS, add port 443 and full SSL
server block to dev nginx config, add Spotify redirect URI env var,
improve Spotify token error handling, and fix Chat/Steam mobile sizing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 11:18:32 +00:00
adamfandClaude Opus 4.6 619692687f Hide sidebar images on screens narrower than 1200px
Deploy with Docker Compose / deploy (push) Successful in 23s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 11:17:14 +00:00
adamf f1750a8b3e Remove a5 class from Admin cause it was too small 2026-03-26 10:21:53 +00:00
adamfandClaude Opus 4.6 3c9d19d185 Improve PageSpeed accessibility, SEO, and performance scores
Deploy with Docker Compose / deploy (push) Successful in 34s
Add alt attributes, width/height for CLS, aria-labels, meta description,
preconnect hints, LCP fetchpriority, and sound/stamp cache headers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 02:38:08 +00:00
adamfandClaude Opus 4.6 474f14b1e5 Add performance optimizations: gzip, cache headers, WOFF2 fonts, lazy loading
Deploy with Docker Compose / deploy (push) Successful in 38s
Enable gzip compression in nginx, add cache-control headers for static assets,
convert fonts to WOFF2 with font-display swap, preload fonts, add lazy loading
to below-fold images, and remove unused font files.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 02:29:37 +00:00
adamfandClaude Opus 4.6 7798b54391 Fix Steam game transition jumping to top of container
Deploy with Docker Compose / deploy (push) Successful in 3m28s
Wrap Transition in a relative-positioned game-container div so the
leaving element's absolute positioning is scoped to the game area,
not the full wrapper. Use flex layout so the container fills only
the space below the header.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 02:10:21 +00:00
adamfandClaude Opus 4.6 d4a6343d5e Add fade transition and game cycling to Steam component
Deploy with Docker Compose / deploy (push) Successful in 3m43s
Matches the Listening component pattern with auto-rotating games every
5 seconds, click to advance, and crossfade transitions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 02:00:52 +00:00
adamfandClaude Opus 4.6 264df132df Add Steam integration showing online status and recent games
Deploy with Docker Compose / deploy (push) Has been cancelled
Fetches player summary and recently played games from Steam API with
5-minute server-side caching. Displays in the home sidebar with online
indicator and game artwork.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-26 01:59:34 +00:00
adamf 747563c6c9 Slow down animation on stamps cause it was crazy
Deploy with Docker Compose / deploy (push) Successful in 15s
2026-03-25 21:54:05 +00:00
adamf fabd92bf36 Remove class for main
Deploy with Docker Compose / deploy (push) Successful in 15s
2026-03-25 21:52:41 +00:00
adamfandClaude Opus 4.6 ac5f47fcaa Add Waybar-style footer with sticky navbar/footer layout
Deploy with Docker Compose / deploy (push) Successful in 26s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 21:45:46 +00:00
adamfandClaude Opus 4.6 a8ef10498e Add slide transition for route navigation
Deploy with Docker Compose / deploy (push) Successful in 15s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 21:35:41 +00:00
adamf 0f801a864c Remove Probability & stats because its very low on the page looks gross
Deploy with Docker Compose / deploy (push) Successful in 17s
2026-03-25 21:31:22 +00:00
adamfandClaude Opus 4.6 f9a8127714 Fix white background on curved mobile screen edges
Deploy with Docker Compose / deploy (push) Successful in 19s
Set body background-color to --bg_secondary so areas outside
the halftone main element match instead of showing white.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 21:29:29 +00:00
adamfandClaude Opus 4.6 8f57c15c24 Improve stamps bounce animation with explicit position tracking
Deploy with Docker Compose / deploy (push) Successful in 14s
Use dedicated posX/posY variables instead of reading scroll position
directly, preventing drift at boundaries. Add more demo stamps.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 21:26:48 +00:00
adamfandClaude Opus 4.6 b2042ffe78 Add bouncing auto-scroll animation to stamps section
Deploy with Docker Compose / deploy (push) Successful in 16s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 21:24:40 +00:00
adamfandClaude Opus 4.6 4e7377d9f0 Improve AutoScroll reliability with mouseenter/mouseleave
Deploy with Docker Compose / deploy (push) Successful in 15s
Replace mouseover (which fires repeatedly on child elements) with
mouseenter/mouseleave so hover cleanly stops scrolling. On mouse leave,
sync scroll position from scrollTop so manual scrolling is respected.
Fix inverted top/bottom boundary checks.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 21:22:58 +00:00
adamf 8406582b2b Make miku fixed height so it doesn't messup Chat scrolling
Deploy with Docker Compose / deploy (push) Successful in 24s
2026-03-25 17:17:25 +00:00
adamf 283e02657e Update screenshot url
Deploy with Docker Compose / deploy (push) Successful in 6s
2026-03-25 17:13:59 +00:00
adamfandClaude Opus 4.6 7a737f6d10 Handle missing Spotify auth gracefully instead of returning errors
Deploy with Docker Compose / deploy (push) Successful in 3m42s
Return nil/empty results when Spotify client is not authenticated,
preventing GraphQL errors from breaking the home page data query.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 17:02:11 +00:00
adamfandClaude Opus 4.6 29350af2e0 Fix WebSocket 403 in dev mode by allowing localhost origins
Deploy with Docker Compose / deploy (push) Has been cancelled
The CheckOrigin function only accepted the production domain, rejecting
localhost connections in dev. Also removed redundant error response after
a failed upgrade since the upgrader already writes its own HTTP response.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 16:59:13 +00:00
adamfandClaude Opus 4.6 d3d3269d49 Extract Vue frontend into separate container and add stp_wasm crate
Deploy with Docker Compose / deploy (push) Successful in 4m58s
Move Vue app from nginx/vue/ to top-level vue/ with its own Dockerfile,
update docker-compose configs and nginx proxy to serve from the new
container, and add initial Rust WASM crate (stp_wasm). Also fix .gitignore
to exclude Rust target/ directories.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 16:40:45 +00:00
adamfandClaude Opus 4.6 2b84730126 Fix Slideshow layout shift affecting Chat during image transitions
Deploy with Docker Compose / deploy (push) Successful in 55s
Use CSS grid stacking instead of absolute positioning so both
entering and leaving images occupy the same grid cell, keeping the
container height stable during crossfade transitions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 03:16:28 +00:00
adamf 8c2e9ba9a5 Remove horizontal scroll from commit history (sry bad claude naughty)
Deploy with Docker Compose / deploy (push) Successful in 1m6s
2026-03-25 03:13:56 +00:00
adamfandClaude Opus 4.6 6a6b9536ba Remove horizontal scroll from CommitHistory component
Deploy with Docker Compose / deploy (push) Successful in 59s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 03:10:56 +00:00
adamfandClaude Opus 4.6 d3e948d558 Add lazy loading for images and videos in Chat
Deploy with Docker Compose / deploy (push) Has been cancelled
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 03:10:18 +00:00
adamfandClaude Opus 4.6 bbb493b544 Improve Chat scroll-to-bottom reliability with ResizeObserver
Deploy with Docker Compose / deploy (push) Successful in 1m1s
Replace ad-hoc nextTick and media load handlers with a ResizeObserver
on an inner content wrapper, which fires after layout for all content
changes (new messages, image/video loads, window resize). Add scroll
position tracking so auto-scroll only triggers when user is near
bottom, and conditionally show the Bottom button only when scrolled up.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 03:06:27 +00:00
adamfandClaude Opus 4.6 3afcee2011 Limit stamps component height on small screens
Deploy with Docker Compose / deploy (push) Successful in 56s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:57:34 +00:00
adamfandClaude Opus 4.6 7d74a2fc07 Fix small-screen layout issues for Home tables and sidebar images
Deploy with Docker Compose / deploy (push) Successful in 1m1s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:54:49 +00:00
adamfandClaude Opus 4.6 570a823426 Improve responsive layout for Home sidebar and utility components
Deploy with Docker Compose / deploy (push) Successful in 4m50s
Switch sidebar to CSS grid, constrain images on mobile, add max-height to Chat, and improve Radio/Time/Timer compact styling.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:43:37 +00:00
adamfandClaude Opus 4.6 6dddcd4d7a Replace raw anchor tags with Link component across views
Use Link component in Chat, CommitHistory, Stamps, Demoman, and fix Navbar to use span instead of nested anchors. Also updates Navbar inHome check for /stp route.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:43:32 +00:00
adamfandClaude Opus 4.6 69e158b871 Add Landing page and move Home to /stp route
New professional landing page at / with bio, about section, and nav links. Previous home page now lives at /stp.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:43:27 +00:00
adamfandClaude Opus 4.6 d857cce5dc Consolidate OptionalLinkTable and ToggleLinkTable into LinkTable
LinkTable now supports variant (list/table) and optional title toggle, replacing the need for separate components. Updates all consumers to use the unified API.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:43:24 +00:00
adamfandClaude Opus 4.6 c2bbd7ad88 Add Link and InlineLink reusable components
Link wraps RouterLink or <a> with consistent styling and automatic rel attributes. InlineLink adds bold italic inline link styling.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-25 02:43:12 +00:00
adamf 8627a7945e Fix sidebars and make them not expand
Deploy with Docker Compose / deploy (push) Successful in 6m7s
2026-03-19 01:16:10 +00:00
adamf 08125204c5 Format CommitHistory and fix overflow on chat
Deploy with Docker Compose / deploy (push) Successful in 1m11s
2026-03-17 01:02:20 +00:00
adamf a0215f7810 Make images and video smaller in chat
Deploy with Docker Compose / deploy (push) Successful in 55s
2026-03-17 00:53:37 +00:00
adamfandClaude Sonnet 4.6 c1ce3c31ba Update readme with GraphQL API details and tech stack specifics
Deploy with Docker Compose / deploy (push) Successful in 4s
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-17 00:39:25 +00:00
adamfandClaude Sonnet 4.6 2becda2bd8 Add CLAUDE.md and update frontend README
Deploy with Docker Compose / deploy (push) Successful in 39s
Add Claude Code guidance file with build commands, architecture overview,
and key patterns. Replace default Vite scaffold README with project-specific
documentation including dev proxy config and deployment notes.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-17 00:37:19 +00:00
adamfandClaude Sonnet 4.6 7381cda7b8 Move Gitea feed from frontend to backend with cached GraphQL proxy
Deploy with Docker Compose / deploy (push) Successful in 4m39s
Replaces direct browser-to-Gitea API calls with a backend service that
proxies and caches the feed (1-min TTL), served via the existing GraphQL
HomeData query. Commit message parsing now happens server-side.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-17 00:14:59 +00:00
adamf 5999eccc21 Merge branch 'main' of ssh://adam-french.co.uk:2222/adamf/web_server
Deploy with Docker Compose / deploy (push) Successful in 59s
2026-03-16 16:47:22 +00:00
adamf 7155255733 Add rowing to store 2026-03-16 16:44:02 +00:00
adamf 6ff30a37f7 Add rowing to store 2026-03-16 16:41:30 +00:00
adamf a4514ad98d Upgrade go version
Deploy with Docker Compose / deploy (push) Successful in 11s
2026-03-16 16:22:11 +00:00
adamf 84e18dddfa Update go version to 1.25 2026-03-16 15:45:34 +00:00
adamfandClaude Opus 4.6 b4ddb4d402 Stop tracking app.ini to prevent runtime secrets from blocking git pull
Deploy with Docker Compose / deploy (push) Failing after 1s
Gitea populates secret fields (LFS_JWT_SECRET, SECRET_KEY, etc.) at
startup, causing app.ini to always show as modified. Since secrets are
already passed via environment variables, the tracked file is replaced
with an ignored app.ini and a tracked app.ini.template for reference.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-16 15:35:43 +00:00
adamfandClaude Opus 4.6 0360b1f7f1 Consolidate frontend REST calls with GraphQL
Deploy with Docker Compose / deploy (push) Failing after 1s
Replace 5 separate REST calls on home page load with a single GraphQL
query. Add homeData store that fetches posts, favorites, activities,
spotify, and auth in one request. Convert all admin mutations and
auth flows to use GraphQL. Add album images to Spotify GraphQL schema.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-16 15:29:22 +00:00
adamf 36817277f9 Revert "Don't use internal tokens"
Deploy with Docker Compose / deploy (push) Failing after 0s
This reverts commit a03ce26824.
2026-03-16 09:54:25 +00:00
adamf a03ce26824 Don't use internal tokens
Deploy with Docker Compose / deploy (push) Failing after 1s
2026-03-16 09:39:48 +00:00
adamf a10706506e Make navbar sticky
Deploy with Docker Compose / deploy (push) Successful in 2m5s
2026-03-13 17:58:52 +00:00
adamfandClaude Opus 4.6 f29e937307 Fix layout so content divs fill remaining space and scroll on overflow
Deploy with Docker Compose / deploy (push) Successful in 1m47s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-13 17:52:27 +00:00
adamfandClaude Opus 4.6 81cb2bc4b5 Move Gitea secrets to environment variables
Deploy with Docker Compose / deploy (push) Successful in 41s
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-13 17:46:18 +00:00
adamf 8b5ed9abec Don't make header scroll
Deploy with Docker Compose / deploy (push) Successful in 1m34s
2026-03-13 17:37:03 +00:00
adamf 8cdab593ae Okay this is the fix, please don't judge me for how long this took for me too look at, I think I really should just set a fixed height for the parent container.
Deploy with Docker Compose / deploy (push) Successful in 1m43s
2026-03-13 16:39:12 +00:00
adamf b63cc911a7 Should defo be the fix please god
Deploy with Docker Compose / deploy (push) Successful in 2m24s
2026-03-13 16:35:02 +00:00
adamf e1fe281586 Should defo be the fix please god
Deploy with Docker Compose / deploy (push) Successful in 1m42s
2026-03-13 16:31:47 +00:00
adamf 887d23af5b Make only messages scroll
Deploy with Docker Compose / deploy (push) Successful in 1m54s
2026-03-13 16:25:34 +00:00
adamf 36aa7ed907 Fix overextending flexbox & abandon ship on flex-1 approach, and probably should just use fixed height for parent container
Deploy with Docker Compose / deploy (push) Successful in 1m22s
2026-03-13 15:47:43 +00:00
adamf d5065d19e0 Make sidebars take up full space
Deploy with Docker Compose / deploy (push) Successful in 2m2s
2026-03-13 15:30:34 +00:00
adamf 15c721ea56 Make commit scroll
Deploy with Docker Compose / deploy (push) Successful in 1m47s
2026-03-13 15:12:59 +00:00
adamf b47d1a3df3 Fix checkStream function and useTemplateRef instead of implicit
Deploy with Docker Compose / deploy (push) Successful in 1m35s
2026-03-10 22:40:15 +00:00
adamf 5b3cd267b6 Clear messages on reconnect
Deploy with Docker Compose / deploy (push) Successful in 1m48s
2026-03-10 22:28:13 +00:00
adamf 6033a952af Automatically reconnect to websocket
Deploy with Docker Compose / deploy (push) Successful in 1m27s
2026-03-10 22:12:42 +00:00
adamf 0ad7f4e009 Radio is too damn loud, change frontend instead of server
Deploy with Docker Compose / deploy (push) Successful in 1m27s
2026-03-10 21:41:45 +00:00
adamf 6bf773487a Radio is too damn loud
Deploy with Docker Compose / deploy (push) Successful in 19s
2026-03-10 21:29:44 +00:00
adamf 2916afe206 Add fallback music directory to repo
Deploy with Docker Compose / deploy (push) Successful in 6m30s
2026-03-10 14:02:23 +00:00
adamf 17deec23ba Remove music from git
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-10 13:59:07 +00:00
adamf ad4d02228d Add prune to deploy
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-10 13:56:57 +00:00
adamf d5fbc0ee74 Hide overflow
Deploy with Docker Compose / deploy (push) Successful in 1m6s
2026-03-10 13:44:02 +00:00
adamf 857f66cb37 Make radio check the stream endpoint
Deploy with Docker Compose / deploy (push) Successful in 1m22s
2026-03-10 13:40:51 +00:00
adamf 5b041d7364 Add fallible
Deploy with Docker Compose / deploy (push) Successful in 19s
2026-03-10 13:33:54 +00:00
adamf 4be7e60394 syntax for setting of liquidsoap changed
Deploy with Docker Compose / deploy (push) Successful in 7s
2026-03-10 13:26:19 +00:00
adamf 27f74f6c2a /etc/ permissions for radio user
Deploy with Docker Compose / deploy (push) Successful in 34s
2026-03-10 13:23:59 +00:00
adamf 5a19f09e17 Add fallback music to repository
Deploy with Docker Compose / deploy (push) Successful in 3m54s
2026-03-10 12:59:27 +00:00
adamf 469a225860 Add fallback music to icecast server
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-10 12:58:53 +00:00
adamf cd1bcc7f39 Make chatbox scroll to bottom once all images have loaded
Deploy with Docker Compose / deploy (push) Successful in 1m44s
2026-03-10 12:43:38 +00:00
adamf 14cacec1f5 Correct styles on admin panels and enter triggers submission
Deploy with Docker Compose / deploy (push) Successful in 1m34s
2026-03-10 12:41:45 +00:00
adamf 7991c80176 Allow admin to create user
Deploy with Docker Compose / deploy (push) Successful in 5m22s
2026-03-10 12:32:59 +00:00
adamf bad44a6ddd Separate admin protected endpoints from non-admin endpoints 2026-03-10 12:32:47 +00:00
adamf 0b256863d6 Merge branch 'main' of ssh://adam-french.co.uk:2222/adamf/web_server
Deploy with Docker Compose / deploy (push) Successful in 4m57s
2026-03-10 12:20:00 +00:00
adamf cb326ff8bf Add promote / demote user to admin and reintroduce create user dashboard 2026-03-10 12:18:24 +00:00
adamf 78d6c3d4f0 Add promote / demote user to admin and reintroduce create user dashboard
Deploy with Docker Compose / deploy (push) Failing after 24s
2026-03-10 12:17:07 +00:00
adamf c7dbf5b778 Include make to dependencies
Deploy with Docker Compose / deploy (push) Successful in 3m17s
2026-03-10 12:13:42 +00:00
adamf a8d1b879be Changes to docker configuration to decrease build time
Deploy with Docker Compose / deploy (push) Failing after 1m35s
2026-03-10 12:07:22 +00:00
adamf f82389225c Changes to docker configuration to decrease build time 2026-03-10 12:07:13 +00:00
adamf 165852e738 Remove extra attach and rename bottom button
Deploy with Docker Compose / deploy (push) Successful in 2m18s
2026-03-10 12:02:14 +00:00
adamf c58c19cc1e Make links clickable
Deploy with Docker Compose / deploy (push) Successful in 1m49s
2026-03-10 11:58:06 +00:00
adamf 26ea0108e0 Add scroll to bottom on chat
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-10 11:56:52 +00:00
adamf 604576b46a Only show attach button if user is admin
Deploy with Docker Compose / deploy (push) Successful in 2m4s
2026-03-09 18:11:03 +00:00
adamf 33d72fd20a Fix side scrolling for iphones
Deploy with Docker Compose / deploy (push) Successful in 2m1s
2026-03-09 18:03:19 +00:00
adamf d3cbc687d5 Fix sidebar on first breakpoint
Deploy with Docker Compose / deploy (push) Successful in 1m55s
2026-03-09 18:00:51 +00:00
adamf d7b76e4742 open port 3000 for gitea runner
Deploy with Docker Compose / deploy (push) Failing after 2m36s
2026-03-09 17:55:10 +00:00
adamf 64c2ba5562 Fix page height on first breakpoint
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 17:50:49 +00:00
adamf 6796367dbe Fix page height on first breakpoint
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 17:40:00 +00:00
adamf c2580c984d Allow chat to get videos
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 17:30:54 +00:00
adamf 68db930049 Don't use SaveUploadedFile (causing permission issues)
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 17:21:26 +00:00
adamf 63da086da2 Removed setting own permissions, let dockerfile entryhost do it
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 17:10:24 +00:00
adamf 6326a438dc Halftone + mask reduces performance alot, change background
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 16:56:20 +00:00
adamf 7c980f1b1f Fix file permissions, still
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 16:53:45 +00:00
adamf 141ceab7e6 Reduce performance lost on large screens
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 16:41:55 +00:00
adamf d03f9668ad Add error handling 2026-03-09 16:41:38 +00:00
adamf 41d6cf0dac omg fix undefined variable
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 16:29:56 +00:00
adamf 1e3c6adf5e Fix file permissions on image upload
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 16:23:44 +00:00
adamf 99ddd7d494 Fix file permissions
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 16:20:47 +00:00
adamf 8e50537333 Get AI to fix vunerabilities in site
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 14:12:29 +00:00
adamf 85a2325683 change file permissions to /uploads
Deploy with Docker Compose / deploy (push) Successful in 4m0s
2026-03-09 13:59:59 +00:00
adamf 0a8a752433 Add file upload to website and integrate into chat
Deploy with Docker Compose / deploy (push) Successful in 5m12s
2026-03-09 13:47:45 +00:00
adamf 4c396ef30f Add file upload to website and integrate into chat
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-09 13:47:38 +00:00
adamf 77e2c272cb Update mobile layout adjustments
Deploy with Docker Compose / deploy (push) Successful in 1m53s
2026-03-09 13:06:17 +00:00
adamf 1578a05762 Remove extra whitespace on CV.vue and stopped height becoming 0 on image transitions
Deploy with Docker Compose / deploy (push) Successful in 1m28s
2026-03-09 12:07:05 +00:00
adamf a6bc1d5126 Add transcript to site
Deploy with Docker Compose / deploy (push) Successful in 1m30s
2026-03-09 11:58:44 +00:00
adamf 2737b4f0d0 Avoid panic on spotify if not authed
Deploy with Docker Compose / deploy (push) Successful in 3m35s
2026-03-07 17:46:55 +00:00
adamf 9fa953c969 Add local dev mode with HTTP-only nginx and DB seeding)
Deploy with Docker Compose / deploy (push) Successful in 5m11s
2026-03-07 17:36:54 +00:00
adamf 5a45f1f427 Revert "Update notes component to reflect obsidian notes"
Deploy with Docker Compose / deploy (push) Successful in 28s
This reverts commit 4458844029.
2026-03-07 17:07:21 +00:00
adamf 4458844029 Update notes component to reflect obsidian notes
Deploy with Docker Compose / deploy (push) Successful in 1m54s
2026-03-07 17:04:23 +00:00
adamf 3200ef5bee make text size even larger
Deploy with Docker Compose / deploy (push) Successful in 1m42s
2026-03-07 16:57:46 +00:00
adamf 0da6d3f0ed check duplicates before making claude request
Deploy with Docker Compose / deploy (push) Successful in 3m31s
2026-03-07 16:51:11 +00:00
adamf 88ce32abeb make popup text size larger
Deploy with Docker Compose / deploy (push) Successful in 4m45s
2026-03-07 16:46:03 +00:00
adamf adcf1bda48 Check that paces are reasonable
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-07 16:43:08 +00:00
adamf 7450b5a624 Add gym chart to show rowing results
Deploy with Docker Compose / deploy (push) Successful in 1m45s
2026-03-07 16:31:15 +00:00
adamf ab2b0a1e3d Add padding to chat
Deploy with Docker Compose / deploy (push) Successful in 1m47s
2026-03-06 16:09:14 +00:00
adamf ff82b8bdf9 Change author ID colour
Deploy with Docker Compose / deploy (push) Successful in 1m48s
2026-03-06 16:02:37 +00:00
adamf 1429a6a5cb Change author ID colour
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-03-06 16:01:44 +00:00
adamf 7a71484ecc Show author id in chat log
Deploy with Docker Compose / deploy (push) Successful in 1m57s
2026-03-06 15:56:12 +00:00
adamf e1563b55f4 remove todo make persistent chatlog from readme
Deploy with Docker Compose / deploy (push) Successful in 8s
2026-03-06 13:29:59 +00:00
adamf 4fbeabc3ae Make chat longer
Deploy with Docker Compose / deploy (push) Successful in 1m43s
2026-03-05 21:57:54 +00:00
adamf a83b98eb2b Make chat persistent across reboot
Deploy with Docker Compose / deploy (push) Successful in 3m25s
2026-03-05 21:43:04 +00:00
adamf 5346b24999 Make chat component autoscroll
Deploy with Docker Compose / deploy (push) Successful in 1m30s
2026-03-05 21:31:00 +00:00
adamf 3779a1cbcc Add important todo to site
Deploy with Docker Compose / deploy (push) Successful in 4s
2026-03-05 20:38:24 +00:00
adamf 3f39f6327c Lookmaxing
Deploy with Docker Compose / deploy (push) Successful in 1m54s
2026-03-05 20:32:14 +00:00
adamf 9dc9a3a063 Pose max message limit on chat function so no crash ^_^
Deploy with Docker Compose / deploy (push) Successful in 3m30s
2026-03-05 20:07:08 +00:00
adamf a6b543cf65 Make chat component look nicer
Deploy with Docker Compose / deploy (push) Successful in 1m36s
2026-03-05 19:58:07 +00:00
adamf 4a65836210 Make chat component look nicer and upgrade websocket connection
Deploy with Docker Compose / deploy (push) Successful in 1m47s
2026-03-05 19:51:33 +00:00
adamf 95635c86b3 Fix up live chat
Deploy with Docker Compose / deploy (push) Successful in 4m26s
2026-03-05 19:14:05 +00:00
adamf 3056b23b50 nicer name
Deploy with Docker Compose / deploy (push) Successful in 3s
2026-03-05 19:04:50 +00:00
adamf 72013f5cdd update readme
Deploy with Docker Compose / deploy (push) Successful in 3s
2026-03-05 19:03:40 +00:00
adamf 7aa62659e5 remove silly background
Deploy with Docker Compose / deploy (push) Successful in 1m35s
2026-03-05 17:35:25 +00:00
adamf aa3f0a189d refactor slideshow code to its component and added Miku & miku background
Deploy with Docker Compose / deploy (push) Successful in 1m42s
2026-03-05 13:31:28 +00:00
adamf 646f93136d update rowing information to non fricken nanoseconds who though time.Durations should be nanoseconds
Deploy with Docker Compose / deploy (push) Successful in 3m45s
2026-03-04 16:48:21 +00:00
adamf 54852eba82 Update CV
Deploy with Docker Compose / deploy (push) Successful in 1m47s
2026-03-04 16:21:30 +00:00
adamf e43c07b30a more verbose error response
Deploy with Docker Compose / deploy (push) Successful in 3m17s
2026-03-04 16:10:52 +00:00
adamf 190bc6076b remove json boilerplate, log error and return response
Deploy with Docker Compose / deploy (push) Successful in 2m45s
2026-03-04 15:58:14 +00:00
adamf 88884121ab allow multiple files to be uploaded to rowing endpoint
Deploy with Docker Compose / deploy (push) Successful in 1m51s
2026-03-04 15:26:17 +00:00
adamf e25fc5f1d1 implement create rowing component
Deploy with Docker Compose / deploy (push) Successful in 1m39s
2026-03-04 14:45:50 +00:00
adamf 5bcc65668e move admin component files and add rowing component 2026-03-04 14:40:56 +00:00
adamf 2c1ecce99a Merge remote-tracking branch 'gitea/rowing'
Deploy with Docker Compose / deploy (push) Successful in 3m48s
2026-03-04 14:32:34 +00:00
adamf f2ba3494b1 remove no slip
Deploy with Docker Compose / deploy (push) Successful in 1m35s
2026-03-03 10:32:38 +00:00
adamf d56bd5783d eliminate the wretched hiding console.log, filthy log......
Deploy with Docker Compose / deploy (push) Successful in 1m20s
2026-02-24 22:48:13 +00:00
adamf f60636942f eliminate the wretched hiding console.log, filthy log......
Deploy with Docker Compose / deploy (push) Successful in 1m31s
2026-02-24 22:40:55 +00:00
adamf b087172bb1 slowed down the whole animation industry
Deploy with Docker Compose / deploy (push) Successful in 1m30s
2026-02-24 22:31:54 +00:00
adamf 0c93c6bc27 make colors match
Deploy with Docker Compose / deploy (push) Successful in 1m41s
2026-02-23 16:16:09 +00:00
adamf 48ae2f59ea adding important context
Deploy with Docker Compose / deploy (push) Successful in 1m37s
2026-02-23 16:06:05 +00:00
adamf c9faa90abd adding important context
Deploy with Docker Compose / deploy (push) Successful in 1m43s
2026-02-23 16:03:52 +00:00
adamf ef78974744 stamps width fix, also screw mobile even more
Deploy with Docker Compose / deploy (push) Successful in 1m39s
2026-02-23 15:56:52 +00:00
adamf 49499052b0 add link to feed
Deploy with Docker Compose / deploy (push) Successful in 1m49s
2026-02-23 15:51:56 +00:00
adamf dbb4914745 fix mobile, nobody likes mobile......... hate mobile
Deploy with Docker Compose / deploy (push) Successful in 1m28s
2026-02-23 15:49:04 +00:00
adamf 34fa96ddab adding git feed
Deploy with Docker Compose / deploy (push) Successful in 1m24s
2026-02-23 15:45:46 +00:00
adamf 8a9f3c373d Update links
Deploy with Docker Compose / deploy (push) Successful in 1m27s
2026-02-23 14:23:43 +00:00
adamf dc05ade798 update readme
Deploy with Docker Compose / deploy (push) Successful in 1m29s
2026-02-23 14:15:32 +00:00
adamf 1e47919a40 update readme
Deploy with Docker Compose / deploy (push) Successful in 3s
2026-02-23 13:23:50 +00:00
adamf 8e9734fca7 update cv
Deploy with Docker Compose / deploy (push) Successful in 3m27s
2026-02-23 13:14:41 +00:00
adamf da9a083f2d eddy fix
Deploy with Docker Compose / deploy (push) Successful in 3m34s
2026-02-21 20:06:59 +00:00
adamf 3c40eb9f08 I should seriously look at what I'm commiting before I commit it.... >_< dw I won't do this in professional context
Deploy with Docker Compose / deploy (push) Successful in 1m26s
2026-02-20 16:28:16 +00:00
adamf e016e3af46 fix infinite loop :( shouldn't have existed, silly programmer
Deploy with Docker Compose / deploy (push) Failing after 50s
2026-02-20 16:26:22 +00:00
adamf 0c91f512b4 adding more detail to cv
Deploy with Docker Compose / deploy (push) Successful in 1m23s
2026-02-20 16:24:15 +00:00
adamf f63b61431b maybe bedroom is not professional
Deploy with Docker Compose / deploy (push) Successful in 1m24s
2026-02-20 16:22:39 +00:00
adamf f3ea83c477 changed cv
Deploy with Docker Compose / deploy (push) Successful in 1m28s
2026-02-20 16:13:01 +00:00
adamf 4b5ed4787a center text and fullwidth button
Deploy with Docker Compose / deploy (push) Successful in 1m30s
2026-02-19 21:41:49 +00:00
adamf 747a403bcb idk what this changes
Deploy with Docker Compose / deploy (push) Successful in 3s
2026-02-18 21:45:17 +00:00
adamf fe16ccab97 add ignore to webpack future content
Deploy with Docker Compose / deploy (push) Successful in 10s
2026-02-18 21:43:51 +00:00
adamf 7bcb485fc6 move radio and add to homepage
Deploy with Docker Compose / deploy (push) Has been cancelled
2026-02-18 21:42:37 +00:00
adamf a3d73b12f4 Adding gitea link
Deploy with Docker Compose / deploy (push) Successful in 1m28s
2026-02-18 21:29:30 +00:00
adamf 47a8e6c35e Adding gitea link
Deploy with Docker Compose / deploy (push) Successful in 1m22s
2026-02-18 21:27:43 +00:00
adamf f885ff9175 Adding gitea link
Deploy with Docker Compose / deploy (push) Successful in 1m25s
2026-02-18 21:22:41 +00:00
adamf d574fa7692 change intro
Deploy with Docker Compose / deploy (push) Successful in 1m20s
2026-02-18 21:13:32 +00:00
adamf ac171f7846 yes
Deploy with Docker Compose / deploy (push) Successful in 1m24s
Merge branch 'main' of ssh://adam-french.co.uk:2222/adamf/web_server
2026-02-18 21:09:20 +00:00
adamf b5b86a2a37 revert to old website intro 2026-02-18 21:08:33 +00:00
adamf cfdb5b4d50 Update .gitea/workflows/deploy.yaml
Deploy with Docker Compose / deploy (push) Successful in 3s
2026-02-18 16:38:06 +00:00
adamf 37580cdc42 Stop da haxxers
Deploy with Docker Compose / deploy (push) Successful in 3s
2026-02-18 16:26:52 +00:00
adamf 711236b776 fix actions
Deploy with Docker Compose / deploy (push) Successful in 2m35s
2026-02-18 16:21:52 +00:00
adamf 75454c2ed8 fix actions
Deploy with Docker Compose / deploy (push) Failing after 5s
2026-02-18 16:19:58 +00:00
adamf 78c824c4c8 remove mountpoint
Deploy with Docker Compose / deploy (push) Failing after 2m56s
2026-02-17 18:37:46 +00:00
adamf ba3b933068 remove mountpoint
Deploy with Docker Compose / deploy (push) Failing after 5s
2026-02-17 18:36:23 +00:00
adamf 14c430bbad adding gitea actions
Deploy with Docker Compose / deploy (push) Failing after 2s
2026-02-17 18:34:55 +00:00
adamf 26c7422e34 adding gitea-runner service 2026-02-17 18:10:19 +00:00
adamf 470b1c79d8 fix ssh domain for gitea 2026-02-16 16:57:20 +00:00
adamf d849b606ec fix certbot env vars 2026-02-16 15:07:44 +00:00
adamf 46a9da4c90 gitea runner 2026-02-16 14:52:33 +00:00
adamf 398a610cb2 fix root of gitea 2026-02-16 13:58:09 +00:00
adamf b506bae515 fix gitea 2026-02-16 13:57:28 +00:00
adamf 11ad0b5a83 reverse proxy to gitea 2026-02-16 13:21:11 +00:00
adamf d7393e1419 Revert "Revert "idk what I changed""
This reverts commit 0d32333c0c.
2026-02-16 13:03:13 +00:00
adamf 0d32333c0c Revert "idk what I changed"
This reverts commit 7dc3f49273.
2026-02-16 13:02:31 +00:00
adamf 050a38a76f Merge branch 'main' of /home/adamf/repos/web_server 2026-02-16 12:56:23 +00:00
adamf bc43e9ed02 add gitea 2026-02-16 12:52:08 +00:00
adamf 75b8b02825 ignore gitea volume 2026-02-16 12:51:48 +00:00
adamf 5c69a1d0a7 adding gitea 2026-02-16 11:46:49 +00:00
adamf aa915e1071 Merge branch 'main' of 192.168.178.24:~/repos/web_server
ye
2026-02-14 22:03:47 +00:00
adamf 7dc3f49273 idk what I changed 2026-02-14 22:03:32 +00:00
adamf 21d3997a16 remove ts 2026-02-10 17:04:52 +00:00
adamf c56ba217dd remove tsconfig 2026-02-10 17:01:26 +00:00
adamf 91804f1fe7 adding vueuse 2026-02-10 17:00:59 +00:00
adamf 7e74ce5a2a adding typescript 2026-02-10 16:57:00 +00:00
adamf e92ac49140 new components 2026-02-10 16:46:49 +00:00
511 changed files with 59441 additions and 4943 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";
}
+49
View File
@@ -0,0 +1,49 @@
# =============================================================================
# Quartz image — builds the Obsidian notes site.
#
# STATUS: RETIRED (not live). /notes/ is now served by the read-only
# silverbullet-public service; this directory is no longer referenced by
# docker-compose.yml or nginx. Kept for reference / rollback: restoring it means
# re-adding the service, the QUARTZ_* vars to nginx/entrypoint.sh's allow-list,
# and pointing /notes/ back at it (with the prefix-strip rewrite Quartz needs).
#
# HOW THE SOURCE IS OBTAINED: Quartz is not an npm package you depend on, it is
# an application you clone and configure. So the image `git clone`s the
# upstream repo at build time, which is why `git` is installed. --depth 1
# --branch pins to an exact tag (QUARTZ_VERSION, overridable as a build ARG)
# and fetches no history — a shallow clone is much faster on a Pi and the
# history is of no use here.
#
# Because this clone happens at build time, upstream Quartz is only updated
# when the image is rebuilt with a bumped QUARTZ_VERSION. The tag pin is the
# thing stopping an upstream change from breaking the notes site on a routine
# redeploy.
#
# gettext-base supplies `envsubst` for rendering quartz.config.ts from its
# template at container start (see quartz/entrypoint.sh).
#
# quartz.config.ts.template and quartz.layout.ts are copied in AFTER the clone
# so they land on top of the upstream defaults — layout is used as-is, config
# is templated at runtime because it needs DOMAIN.
#
# node:22-slim is multi-arch, so this builds unchanged on the Pi.
# =============================================================================
FROM node:22-slim
RUN apt-get update \
&& apt-get install --yes git gettext-base \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /quartz
ARG QUARTZ_VERSION=v4.4.0
RUN git clone --depth 1 --branch ${QUARTZ_VERSION} \
https://github.com/jackyzha0/quartz.git . \
&& npm ci
COPY quartz.config.ts.template /quartz/quartz.config.ts.template
COPY quartz.layout.ts /quartz/quartz.layout.ts
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# =============================================================================
# quartz entrypoint — render the config, then build-and-serve the notes site.
#
# WHAT IT DOES
# Quartz turns the Obsidian vault into a static site. Its config is a
# TypeScript file that has to know the public base URL, which is only known
# at runtime, so quartz.config.ts is generated from a template on each start.
#
# THE envsubst ALLOW-LIST
# Only ${DOMAIN} is substituted. This matters more here than elsewhere: the
# template is TypeScript and full of `${...}` -shaped syntax and dollar signs
# that must NOT be touched. Restricting envsubst to a single name guarantees
# it can only ever rewrite the one intended line (baseUrl).
#
# WHY build --serve RATHER THAN A STATIC BUILD
# --serve leaves Quartz running as an HTTP server AND watching the content
# directory, so editing a note in Obsidian on the host re-renders the site
# live with no container restart. The vault is bind-mounted READ-ONLY
# (docker-compose.yml), so Quartz can watch it but never write to it.
# The trade-off is that this is a long-running Node process on a Pi rather
# than pre-built static files nginx could serve for free.
#
# ACCESS CONTROL
# None here — Quartz is wide open on its port inside app-network. The site is
# private because nginx gates /notes/ behind an `auth_request` admin check
# before proxying. Never publish this container's port to the host.
#
# ENV VARS
# DOMAIN required; becomes baseUrl "www.<DOMAIN>/notes"
# QUARTZ_PORT optional, defaults to 8080; must match the QUARTZ_PORT nginx
# builds its upstream from, or /notes/ 502s.
#
# `exec` so the Node process becomes PID 1 and receives docker's signals.
# =============================================================================
set -e
envsubst '${DOMAIN}' \
</quartz/quartz.config.ts.template \
>/quartz/quartz.config.ts
exec npx quartz build --serve --port "${QUARTZ_PORT:-8080}"
@@ -0,0 +1,99 @@
// =============================================================================
// quartz.config.ts.template — Quartz site config, rendered to quartz.config.ts
// by quartz/entrypoint.sh at container start.
//
// ONLY the DOMAIN placeholder is substituted (envsubst is given a one-name allow-list), so
// every other dollar sign and backtick-template-looking construct in this
// TypeScript file survives untouched. That restriction is deliberate: a bare
// envsubst over a .ts file would corrupt it.
//
// baseUrl must keep pointing at www.<DOMAIN>/notes — it has to match the path nginx
// proxies (/notes/) or every internal link, the sitemap and the RSS feed point
// at the wrong place.
//
// enableSPA / enablePopovers are off because this site is embedded under a
// path inside another SPA; Quartz's own client-side router would fight with it.
//
// ignorePatterns keeps "private", "templates" and ".obsidian" out of the build
// — the vault is mounted whole, so this list is the only thing stopping
// private notes being published. Check it before adding vault folders.
//
// This file is committed with real content (no secrets). quartz.layout.ts sits
// alongside it and is COPY'd in by quartz/Dockerfile without templating.
// =============================================================================
import { QuartzConfig } from "./quartz/cfg"
import * as Plugin from "./quartz/plugins"
const config: QuartzConfig = {
configuration: {
pageTitle: "Notes",
pageTitleSuffix: "",
enableSPA: false,
enablePopovers: false,
analytics: null,
locale: "en-GB",
baseUrl: "www.${DOMAIN}/notes",
ignorePatterns: ["private", "templates", ".obsidian"],
defaultDateType: "modified",
theme: {
fontOrigin: "googleFonts",
cdnCaching: true,
typography: {
header: "Schibsted Grotesk",
body: "Source Sans Pro",
code: "IBM Plex Mono",
},
colors: {
lightMode: {
light: "#faf8f8",
lightgray: "#e5e5e5",
gray: "#b8b8b8",
darkgray: "#4e4e4e",
dark: "#2b2b2b",
secondary: "#284b63",
tertiary: "#84a98c",
highlight: "rgba(143, 159, 169, 0.15)",
textHighlight: "#fff23688",
},
darkMode: {
light: "#161618",
lightgray: "#393639",
gray: "#646464",
darkgray: "#d4d4d4",
dark: "#ebebec",
secondary: "#7b97aa",
tertiary: "#84a98c",
highlight: "rgba(143, 159, 169, 0.15)",
textHighlight: "#b3aa0288",
},
},
},
},
plugins: {
transformers: [
Plugin.FrontMatter(),
Plugin.CreatedModifiedDate({ priority: ["frontmatter", "filesystem"] }),
Plugin.SyntaxHighlighting(),
Plugin.ObsidianFlavoredMarkdown({ enableInHtmlEmbed: false }),
Plugin.GitHubFlavoredMarkdown(),
Plugin.TableOfContents(),
Plugin.CrawlLinks({ markdownLinkResolution: "shortest" }),
Plugin.Description(),
Plugin.Latex({ renderEngine: "katex" }),
],
filters: [Plugin.RemoveDrafts()],
emitters: [
Plugin.AliasRedirects(),
Plugin.ComponentResources(),
Plugin.ContentPage(),
Plugin.FolderPage(),
Plugin.TagPage(),
Plugin.ContentIndex({ enableSiteMap: true, enableRSS: true }),
Plugin.Assets(),
Plugin.Static(),
Plugin.NotFoundPage(),
],
},
}
export default config
+46
View File
@@ -0,0 +1,46 @@
import { PageLayout, SharedLayout } from "./quartz/cfg"
import * as Component from "./quartz/components"
// components shared across all pages
export const sharedPageComponents: SharedLayout = {
head: Component.Head(),
header: [],
afterBody: [],
footer: Component.Footer({
links: {},
}),
}
// components for pages that display a single page (e.g. a single note)
export const defaultContentPageLayout: PageLayout = {
beforeBody: [
Component.Breadcrumbs(),
Component.ArticleTitle(),
Component.ContentMeta(),
Component.TagList(),
],
left: [
Component.PageTitle(),
Component.MobileOnly(Component.Spacer()),
Component.Search(),
Component.Darkmode(),
Component.DesktopOnly(Component.Explorer()),
],
right: [
Component.DesktopOnly(Component.TableOfContents()),
Component.Backlinks(),
],
}
// components for pages that display lists of pages (e.g. tags or folders)
export const defaultListPageLayout: PageLayout = {
beforeBody: [Component.Breadcrumbs(), Component.ArticleTitle(), Component.ContentMeta()],
left: [
Component.PageTitle(),
Component.MobileOnly(Component.Spacer()),
Component.Search(),
Component.Darkmode(),
Component.DesktopOnly(Component.Explorer()),
],
right: [],
}
+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
+324
View File
@@ -0,0 +1,324 @@
# =============================================================================
# .env.example — template for the real ./.env, which is GITIGNORED.
#
# HOW ENV REACHES THE CONTAINERS — two separate mechanisms, both reading this
# same file, and it is worth knowing which is which:
# 1. ${VAR} interpolation in docker-compose.yml. Done by the compose CLI when
# it parses the file, before any container exists. This is how container
# names 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` 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.
# 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,
# check `docker compose config` shows what you expect.
#
# NOTHING IN THIS FILE HAS A REAL VALUE. Values are blank or obviously
# placeholder on purpose; never commit a filled-in copy.
# =============================================================================
# --- Postgres ----------------------------------------------------------------
# One instance, 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.
# The three secrets below are passed as GITEA__section__KEY overrides so the
# committed app.ini.template can keep those fields blank. Generate each as a
# long random hex string.
GITEA_HOST=gitea
GITEA_PORT=3000
GITEA_INTERNAL_TOKEN=
GITEA_LFS_JWT_SECRET=
GITEA_OAUTH2_JWT_SECRET=
POSTGRES_GITEA_DB=gitea
# The host's Tailscale MagicDNS name (e.g. stpvm.tailf20278.ts.net), shown in
# Gitea's SSH clone URLs. Not the public domain: 2222 is reachable only over
# the tailnet. Becomes Gitea's SSH_DOMAIN and DOMAIN. Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
# The registration token is SINGLE-USE: it is exchanged for a permanent
# identity in gitea-runner/.runner on first registration, after which this
# value is ignored. Mint it in Site Administration -> Actions -> Runners.
GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=pi-runner
GITEA_RUNNER_REGISTRATION_TOKEN=
# --- Email ingest (job tracker) -----------------------------------------------
# EMAIL_BACKEND selects the mail source: "graph" (Microsoft Graph API, OAuth)
# or "imap" (fallback; Microsoft has retired IMAP basic auth for outlook.com,
# so imap+app-password only works with non-Microsoft providers like Gmail).
# For "graph": register an Entra "app registration" for a personal Microsoft
# account at azure.microsoft.com > Microsoft Entra ID > App registrations
# (default tenant = "consumers"); add a delegated Mail.Read permission with
# admin/user consent, and create a client secret. Redirect URI type "Web",
# value must live behind the site's real HTTPS origin, e.g.
# https://<YOUR_DOMAIN>/jobs/api/email/callback (served by the job tracker,
# which exchanges the code there). TenantID must be "consumers" for a personal
# outlook.com account.
# The tracker's Settings page (/jobs/settings) shows the authorisation link
# until you sign in; the refresh token is persisted to
# jobs-data/msgraph_token.json.
# OAuth flow reference: https://learn.microsoft.com/en-us/graph/auth-v2-user
EMAIL_BACKEND=
MSGRAPH_CLIENT_ID=
MSGRAPH_CLIENT_SECRET=
MSGRAPH_TENANT_ID=consumers
MSGRAPH_REDIRECT_URI=
# IMAP_PASSWORD should be an app-specific password, not the account password.
# Only read when EMAIL_BACKEND=imap.
IMAP_HOST=
IMAP_PORT=993
IMAP_EMAIL=
IMAP_PASSWORD=
EMAIL_SYNC_INTERVAL=
EMAIL_SYNC_ENABLED=
# --- Job leads (job tracker) --------------------------------------------------
# The lead fetcher polls the sources listed on /jobs/leads and files new
# postings in the leads inbox. JOB_LEADS_ENABLED=true runs it on a timer;
# "Check now" on that page works whether or not it is set. JOB_LEADS_INTERVAL
# is a Go duration (default 6h). Scoring uses CLAUDE_API_KEY, above.
# The board sources (Greenhouse, Lever, Ashby) need no key. The two search
# sources do, both free:
# Adzuna: https://developer.adzuna.com/ (an application id and a key)
# Reed: https://www.reed.co.uk/developers/jobseeker
# A search source whose key is blank reports that on the page; nothing else
# is affected.
JOB_LEADS_ENABLED=
JOB_LEADS_INTERVAL=
ADZUNA_APP_ID=
ADZUNA_APP_KEY=
REED_API_KEY=
# --- Services that nginx substitutes but no longer runs -----------------------
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
# compose service uses them today. Harmless if blank.
# --- SilverBullet (notes) ---------------------------------------------------
# Two instances over the same vault: the admin-only editor at /sb/, and the
# public read-only notes site at /notes/ (which replaced Quartz). All four
# default in nginx/entrypoint.sh and docker-compose.yml, so they can be left
# blank.
SILVERBULLET_HOST=silverbullet
SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public
SILVERBULLET_PUBLIC_PORT=3000
# Seconds between notes commit/push cycles (default 300).
SILVERBULLET_GIT_INTERVAL=
# --- Go backend --------------------------------------------------------------
# BACKEND_HOST is the container name and the nginx upstream.
# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then
# strips; the Vue app's GraphQL client assumes /api.
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
# everyone out.
BACKEND_PORT=8080
BACKEND_HOST=backend
BACKEND_SECRET=
BACKEND_ENDPOINT=/api
# --- Obsidian vault ----------------------------------------------------------
# HOST path, interpolated straight into the bind mounts: read-write into the
# backend, silverbullet and silverbullet-git, read-only into
# silverbullet-public. Must be an absolute path that exists on the host or the
# stack will not start.
OBSIDIAN_DIR=
# --- Spotify -----------------------------------------------------------------
# The redirect URI must match EXACTLY what is registered in the Spotify
# developer dashboard. The dev override sets its own localhost value.
# The resulting refresh token is persisted to ./backend/token/ so it survives
# rebuilds.
SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=
SPOTIFY_REDIRECT_URI=
SPOTIFY_AUTH_STATE=
# --- Icecast / liquidsoap radio ----------------------------------------------
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
# with it, and a live-broadcasting client authenticates to the liquidsoap
# harbor port with it. Anyone holding it can take over the stream.
# LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host.
ICECAST_SOURCE_PASSWORD=
ICECAST_RELAY_PASSWORD=
ICECAST_ADMIN_USER=
ICECAST_ADMIN_PASSWORD=
ICECAST_HOST=icecast2
ICECAST_PORT=8000
ICECAST_MOUNT=/stream
LIQUIDSOAP_HARBOR_MOUNT=/live
LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ----------------------------------------------------------
# DOMAIN is the APEX domain with no scheme and no www; certbot requests both
# it and www.DOMAIN on one certificate, and nginx canonicalises to www.
# EMAIL is the Let's Encrypt account address for expiry notices.
DOMAIN=
EMAIL=
# --- 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=
# --- Development-only switch -------------------------------------------------
# Leave EMPTY/false in production. docker-compose.dev.yml sets SEED_DB=true for
# local work; setting it on the Pi would inject test data into the live site.
SEED_DB=
# --- Python FastAPI service (/py/) -------------------------------------------
PYTHON_HOST=python
PYTHON_PORT=8000
# --- 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=
+177
View File
@@ -0,0 +1,177 @@
# =============================================================================
# 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:
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:
COMPOSE_BAKE: "false"
# 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
+64
View File
@@ -0,0 +1,64 @@
name: Weekly Maintenance
on:
schedule:
# 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:
maintenance:
runs-on: self-hosted
steps:
- name: Show disk usage before
run: df -h /
- name: Update apt package index
run: sudo apt-get update
- name: Upgrade system packages
run: sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade
- 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
run: flock .compose.lock docker compose pull
- name: Rebuild and restart containers
working-directory: /home/adamf/deploy/web_server
run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker images
run: docker image prune -af
- name: Prune old Docker build cache
run: docker builder prune -f --filter until=336h
- name: Show running containers
run: docker compose ps
working-directory: /home/adamf/deploy/web_server
- name: Show disk usage after
run: df -h /
- name: Reboot if required
run: |
if [ -f /var/run/reboot-required ]; then
echo "Reboot required — scheduling in 1 minute"
sudo shutdown -r +1
else
echo "No reboot needed"
fi
+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
+37
View File
@@ -1,7 +1,32 @@
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
# Gitea runner
gitea-runner/.runner
gitea-runner/act_runner
gitea-runner/nohup.out
# Python bytecode
__pycache__/
*.pyc
.pytest_cache/
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
/.venv/
# Logs
logs
@@ -41,5 +66,17 @@ coverage
# Vitest
__screenshots__/
.deploy
*.xcf
# Local-only outstanding-work notes, deliberately not published
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/
+120
View File
@@ -0,0 +1,120 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build & Run Commands
### Check everything
```
make check
```
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, 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
```
`.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)
```
docker compose up --build
```
### Frontend only (hot reload)
```
cd vue && npm run dev
```
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets default to `localhost:8080`, `:3000`, `:8000` and `:8000` and are overridden with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (shell or `vue/.env.local`). Compose publishes none of the backend, Python or Icecast ports to the host, and `/py` and `/radio` share a default, so set these to wherever the services really are — see the comment in `vue/vite.config.js`.
### Frontend build
```
cd vue && npm run build
```
`npm run build` is a plain `vite build`.
### Regenerate GraphQL (after editing schema files)
```
cd backend && go run github.com/99designs/gqlgen generate
```
This regenerates `graph/generated.go` and `graph/model/models_gen.go`. Resolver implementations in `*.resolvers.go` files are preserved.
## Architecture
Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubuntu VM; formerly a Raspberry Pi).
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served 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`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
**Job tracker** (`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, Auth, Notes, etc. Passed to all handlers
- `handlers/handle_*.go` — REST handlers grouped by domain
- `graph/schema/*.graphql` — GraphQL schema files (source of truth)
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
- `graph/generated.go` — auto-generated by gqlgen, do not edit
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout, Component, CoverLetter, CoverSnippet)
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more
## Frontend Structure
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
- `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components, coverLetters, coverSnippets. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `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. 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). Note that a `uniqueIndex` still collides with soft-deleted rows.
## Further documentation
Each area has its own README with the detail that doesn't belong here:
- `backend/README.md` — request lifecycle, auth model, GraphQL-vs-REST split and why each REST endpoint isn't GraphQL, service rundown, gotchas.
- `vue/README.md` — app structure, routing, store/GraphQL data flow, the design-token styling system, and a live-vs-legacy map of the views.
- `python/README.md` — endpoints, the NDJSON streaming contract, the hotel pricing method, and the scraper's fragility points.
- `DEPLOYMENT.md` — service topology and ports, dev vs prod boot paths, TLS first-run and renewal, what persists, env vars, and an ops runbook.
- `.env.example` — every environment variable the stack reads, documented, with blank values.
## Conventions
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
- **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating.
- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof.
+703
View File
@@ -0,0 +1,703 @@
# Deployment
How this site is put together and how to operate it. Application code is
documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only
— compose, nginx, TLS, the runner, and the runbook.
Everything runs on a single 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 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
|
:80 :443| :3000 / :2222 :8001
v v v
+--------------+ +--------+ +-------------+
| nginx | | gitea | | liquidsoap |
| (TLS, SPA, | | (git + | | harbor |
| reverse | | CI) | | (live DJ) |
| proxy) | +--------+ +------+------+
+------+-------+ | |
| | |
--------------------------------------------- | (same container
| | | | | | | as icecast2)
v v v v v v | |
/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | |
backend icecast2 gitea sb sb-pub python | |
| ^ | |
| | | |
| +---------------------------------------|---------------+
| |
+----------+--------------------------------------+
v
+------+
| db | postgres:16
+------+ (app database + gitea database)
vue one-shot build container -> writes vue_dist volume -> nginx serves it
certbot no ports; shares ./certbot/conf and ./certbot/www with nginx
```
### 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 |
| 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
in one step — never change one without the other.**
### Things nginx does that are easy to miss
- **Canonical host.** `http://` → `https://`, and apex → `www`. The SPA, the
cookies and the CORS rules all assume `www.<DOMAIN>`.
- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/py` are stripped
— but `/sb/` and `/notes/` deliberately are NOT: SilverBullet is told its own base path via
`SB_URL_PREFIX` and builds its service-worker scope from it, so stripping the
prefix serves a blank page with nothing in the log.
by a `rewrite ... break` before proxying; each upstream serves from `/`.
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
backend down (502s until it appears) instead of refusing to start.
- **Admin gate.** `/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
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
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.
---
## 2. Dev vs prod boot paths
### Production
```
docker compose up --build
```
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
- renders `nginx.conf.template` if the cert is there, else
`nginx_setup.conf.template`;
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
nginx either way.
3. `certbot` obtains or confirms the certificate, then loops renewing.
4. Everything else comes up in parallel; `depends_on` here is the plain list
form, which waits only for _start_, not readiness.
On the 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 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`**.
- **python** — `uvicorn --reload` with `python/app` bind-mounted.
- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt
cannot validate localhost anyway.
Visit `http://localhost`.
**`SEED_DB`** makes the Go backend populate the database with test posts, users
and messages at startup. It is set only in the dev override and must never be
set on the 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.
---
## 3. TLS: first issuance and renewal
### The chicken-and-egg
The production nginx config references
`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port 80. On a brand-new host neither can go first.
`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no
upstreams, nothing that can fail to load. It serves
`/.well-known/acme-challenge/` from `/var/www/certbot` and 404s everything else,
so a half-configured site is never partially exposed.
**First run on a new domain:**
1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx
config.`
2. certbot runs `certbot certonly --webroot` and writes the certificate into
`./certbot/conf` (bind-mounted into both containers — that sharing is what
makes the whole thing work).
3. **`docker compose restart nginx`.** This step is manual. Nothing watches the
cert directory. On restart the entrypoint re-checks, finds the cert, and
renders the production config.
### Renewal
`certbot/entrypoint.sh` loops `certbot renew` every 12 hours. Renewal is a no-op
until the cert is inside its 30-day window, so this is well within Let's Encrypt
rate limits — it just means the window is checked twice a day. Certs are valid 90
days, so renewal lands around day 60.
**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
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
**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` | 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 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. |
| `./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
are all regenerated.
---
## 5. Environment variables
All configuration lives in **`./.env`** at the repo root, which is gitignored.
`.env.example` documents every variable with blank values — start from that.
Two distinct mechanisms read it, and services use both:
- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse
time. Builds container names 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
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` 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
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
Defined once per config in the `http` block, applied per location. Keyed on
`$binary_remote_addr` — the client IP in packed form, so each entry is ~64 bytes
and a `10m` zone holds roughly 160k IPs. `10m` is a safe round number, not a
tuned value.
`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one
request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead
of that drip, and `nodelay` (used everywhere here) serves those N immediately.
So the effective behaviour is _"N instant requests, then throttled to the drip
rate"_. Anything beyond the burst gets an immediate **503**.
| Zone | Rate | Burst | Applied to | Why |
| -------------- | ------ | ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
| `upload` | 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 `$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 host
(`~/deploy/web_server`) unless stated.
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
it. By hand:
```
git pull && docker compose up -d --build --remove-orphans
```
**Rebuild one service** (e.g. after changing only the backend):
```
docker compose up -d --build backend
```
Note: editing `certbot/entrypoint.sh` needs no rebuild (it is bind-mounted over
the stock image's entrypoint) — just `docker compose restart certbot`. Editing
an nginx **template** does need a rebuild, since templates are `COPY`'d into the
image.
**Apply a new nginx config / pick up a renewed certificate:**
```
docker compose up -d --build nginx # template changed
docker compose restart nginx # certificate changed
```
**Renew certificates manually** (then restart nginx so it is actually served):
```
docker compose exec certbot certbot renew --webroot -w /var/www/certbot
docker compose restart nginx
```
Add `--dry-run` to test without burning rate limit.
**Check logs:**
```
docker compose logs -f nginx # follow one service
docker compose logs --tail=200 backend
docker compose ps # note: `vue` Exited(0) is correct
docker compose logs certbot # issuance / renewal outcomes
```
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**:
```
docker compose down
docker volume rm web_server_dbdata # confirm the name with `docker volume ls`
docker compose up -d
```
The app schema is recreated by GORM auto-migration on backend start (there are no
migration files). **Gitea's database is not auto-created** — the Postgres image
only creates `POSTGRES_DB` on first init, so create `${POSTGRES_GITEA_DB}`
manually before Gitea will start:
```
docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB"
```
**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):
```
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
```
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 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_
a fresh token.
**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.
**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
```
---
## 8. Known rough edges
Documented, not fixed — each would change deploy behaviour.
1. **Renewed certificates are not served until nginx restarts.** No
`--deploy-hook` in `certbot/entrypoint.sh`. Fix: add
`--deploy-hook "touch /var/www/certbot/.reloadme"` plus a watcher, or give
certbot the docker socket to send nginx a `HUP`.
2. **First TLS issuance needs a manual `docker compose restart nginx`.** The
entrypoint only re-evaluates cert presence at container start.
3. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be
mounted to the same in-container path as the real wrapper. It is currently
shadowed by an explicit file mount — fragile. Deleting it would be safe but
is a file removal.
4. **The `/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.
+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
+360
View File
@@ -0,0 +1,360 @@
Gay bal;;s
# My Web
![screenshot](vue/public/img/screenshot.png)
Welcome to the source code for my website! Please contact me if you would like to collaborate and thank you for visiting.
This website is self-hosted on my Raspberry Pi. Any interference or hax and the killswitch will activate and stop the UK national grid power system so please don't tamper with my domain :).
## The use of AI
This has been created with a heavy amount of AI. Initially, I began with articles from [medium](https://medium.com/) informing me of how to use Nginx to host static sites and reverse proxy to other services. They were incredible helpful and I wish I were able to give credit them, but sadly they were read too long ago.
After hearing all the hype on LinkedIn and feeling the pressure to keep up a high output without AI, I eventually caved in. There is an immense advantage not having to scan though documentation to find relevant functions, asking how other developers implement their infrastructure and finding what command will achieve your outcome quickly. Sure, it would be good to have that already cached in your own human memory. But my reasoning is that you _will_ have cached it after being reminded by AI enough times, similar to how flashcards work. I may not be an expert in the specific tool, though I've been able to get good enough at it for my own purposes.
## Architecture
All services run in Docker containers orchestrated by Docker Compose behind Nginx as a reverse proxy on a single bridge network.
```
vue ── Frontend build (outputs dist to shared volume)
nginx (80, 443) ── Frontend SPA + Reverse Proxy
backend (8080) ── Go API (GraphQL + REST)
db (5432) ── PostgreSQL 16
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
gitea (3000) ── Self-Hosted Git
silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0)
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
silverbullet-git ── Commits/pushes notes edits to the notes repo
python (8000) ── Python API (FastAPI)
certbot ── SSL Certificate Management (disabled in dev)
```
## Tech Stack
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX)
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
**Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner
## Features
- Spotify integration (currently playing, recently played)
- Steam integration (online status, recent games)
- Public Obsidian notes site via a read-only SilverBullet, editable from any browser via a second, admin-only SilverBullet
- Live radio streaming via Icecast2 + Liquidsoap
- Real-time chat over WebSockets with image/video uploads
- Blog with admin panel (CRUD)
- Activity and rowing session tracking
- AI image processing integration to extract rowing data from images (will be superseeded by openCV scanning)
- Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben)
- Self-hosted Git (Gitea) with CI/CD and commit feed on homepage
- 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)
- 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 (reported in `docker ps`; nothing restarts on it)
## Pages
| Route | Description |
| -------------- | -------------------------------------------------- |
| `/` | Landing page |
| `/stp` | Home dashboard with grid layout |
| `/admin` | Admin login + panel (authenticated) |
| `/cv` | Curriculum Vitae (printable) |
| `/cv/jobs` | Job application tracker (admin-only, hidden print) |
| `/bookmarks` | Bookmarks (database-backed, grouped by category) |
| `/notes/:path` | Obsidian notes (read-only SilverBullet, public; `private/` excluded) |
| `/sb/` | Obsidian note editor (via SilverBullet, admin-only) |
| `/shrines` | Fan shrine index + individual shrines |
## API
### GraphQL
**Endpoint:** `POST /api/graphql`
**Playground:** `GET /api/graphql` (when `GQL_PLAYGROUND=true`)
| Operation | Type | Description |
| ------------------------------------------ | -------- | ----------------------- |
| `users` | Query | Get all users |
| `user(id)` | Query | Get user by ID |
| `me` | Query | Get authenticated user |
| `posts` | Query | Get all posts |
| `post(id)` | Query | Get post by ID |
| `activities` | Query | Get all activities |
| `favorites` | Query | Get all favorites |
| `rowingSessions` | Query | Get all rowing sessions |
| `post(id)` | Query | Get post by ID |
| `activities` | Query | Get all activities |
| `favorites` | Query | Get all favorites |
| `rowingSessions` | Query | Get all rowing sessions |
| `messages` | Query | Get all messages |
| `spotifyListening` | Query | Currently playing track |
| `spotifyRecent` | Query | Recently played tracks |
| `giteaFeed` | Query | Latest Gitea activity |
| `steamStatus` | Query | Steam online status |
| `login` | Mutation | Authenticate user |
| `logout` | Mutation | Logout |
| `refreshToken` | Mutation | Refresh auth token |
| `createPost` / `updatePost` / `deletePost` | Mutation | Post CRUD (admin) |
| `createUser` / `deleteUser` | Mutation | User management (admin) |
| `setUserAdmin` | Mutation | Toggle admin status |
| `createFavorite` | Mutation | Add favorite (admin) |
| `createActivity` | Mutation | Add activity (admin) |
| `bookmarks` | Query | Get all bookmarks |
| `createBookmark` / `deleteBookmark` | Mutation | Bookmark CRUD (admin) |
| `jobApplications` | Query | Get all job applications (admin) |
| `createJobApplication` / `updateJobApplication` / `deleteJobApplication` | Mutation | Job application CRUD (admin) |
### REST Endpoints
**Auth**
| Method | Path | Description |
| --- | --- | --- |
| POST | `/api/auth/login` | Login (rate limited: 5/min) |
| POST | `/api/auth/refresh` | Refresh token |
| GET | `/api/auth/check` | Check token validity |
| POST | `/api/auth/logout` | Logout |
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Nginx auth_request) |
Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry.
**Spotify**
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/spotify/callback` | OAuth callback |
| GET | `/api/spotify/listening` | Currently playing |
| GET | `/api/spotify/recent` | Recently played |
**Public**
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/favorites` | Get all favorites |
| GET | `/api/rowing` | Get all rowing sessions |
| GET | `/api/activity` | Get all activities |
| GET | `/api/posts` | Get all posts |
| GET | `/api/posts/:id` | Get post by ID |
| GET | `/api/user` | Get all users |
| GET | `/api/user/:id` | Get user by ID |
**Protected (auth required)**
| Method | Path | Description |
| --- | --- | --- |
| 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 |
| --- | --- | --- |
| POST | `/api/favorites` | Create favorite |
| POST | `/api/rowing` | Create rowing session |
| POST | `/api/activity` | Create activity |
| POST | `/api/posts` | Create post |
| PUT | `/api/posts/:id` | Update post |
| DELETE | `/api/posts/:id` | Delete post |
| POST | `/api/user` | Create user |
| PUT | `/api/user/:id` | Update user |
| DELETE | `/api/user/:id` | Delete user |
| PATCH | `/api/user/:id/admin` | Set/unset admin |
| POST | `/api/radio/upload` | Upload radio song |
| GET | `/api/radio/songs` | List radio songs |
| DELETE | `/api/radio/songs/:filename` | Delete radio song |
| PATCH | `/api/radio/songs/:filename/disable` | Disable radio song |
| PATCH | `/api/radio/songs/:filename/enable` | Enable radio song |
**WebSocket**
| Method | Path | Description |
| --- | --- | --- |
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
### Nginx Proxy Routes
| Route | Target | Notes |
| ---------- | ------------ | ------------------------------------------ |
| `/api` | backend:8080 | API (rate limited: 30r/s) |
| `/radio` | icecast:8000 | Audio streaming |
| `/gitea` | gitea:3000 | Git service |
| `/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 |
`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
### Deprecated Endpoints
**Backend note API** (`GET /api/notes/*path`) - The backend has a REST endpoint that serves note files directly from the mounted Obsidian vault. This is superseded by the public SilverBullet instance which now handles note rendering at `/notes/`. The backend endpoint still exists in code but is no longer the primary note serving path.
## Setup
### `.env`
Create a `.env` file in the project root. All services read from this file.
| Variable | Description |
| --------------------------------- | ------------------------------------------------------------------------------- |
| `POSTGRES_USER` | PostgreSQL username |
| `POSTGRES_PASSWORD` | PostgreSQL password |
| `POSTGRES_DB` | Main app database name |
| `POSTGRES_PORT` | PostgreSQL port (typically `5432`) |
| `POSTGRES_HOST` | PostgreSQL hostname (use `db` for Docker) |
| `GITEA_HOST` | Gitea hostname (use `gitea` for Docker) |
| `GITEA_PORT` | Gitea HTTP port (typically `3000`) |
| `GITEA_INTERNAL_TOKEN` | Gitea internal API token (generate with `gitea generate secret INTERNAL_TOKEN`) |
| `GITEA_LFS_JWT_SECRET` | Gitea LFS JWT secret (generate with `gitea generate secret LFS_JWT_SECRET`) |
| `GITEA_OAUTH2_JWT_SECRET` | Gitea OAuth2 JWT secret (generate with `gitea generate secret JWT_SECRET`) |
| `POSTGRES_GITEA_DB` | Gitea database name |
| `UPTIMEKUMA_HOST` | Uptime Kuma hostname (planned) |
| `UPTIMEKUMA_PORT` | Uptime Kuma port (planned) |
| `WALLABAG_HOST` | Wallabag hostname (planned) |
| `WALLABAG_PORT` | Wallabag port (planned) |
| `SILVERBULLET_HOST` | SilverBullet hostname (defaults to `silverbullet`) |
| `SILVERBULLET_PORT` | SilverBullet port (defaults to `3000`) |
| `SILVERBULLET_PUBLIC_HOST` | Public notes SilverBullet hostname (defaults to `silverbullet-public`) |
| `SILVERBULLET_PUBLIC_PORT` | Public notes SilverBullet port (defaults to `3000`) |
| `SILVERBULLET_GIT_INTERVAL` | Seconds between notes commit/push cycles (defaults to `300`) |
| `GITEA_RUNNER_HOST` | Gitea runner hostname |
| `GITEA_RUNNER_NAME` | Gitea runner display name |
| `GITEA_RUNNER_REGISTRATION_TOKEN` | Token to register Gitea Actions runner |
| `BACKEND_PORT` | Backend port (typically `8080`) |
| `BACKEND_HOST` | Backend hostname (use `backend` for Docker) |
| `BACKEND_SECRET` | JWT signing secret |
| `BACKEND_ENDPOINT` | API path prefix (typically `/api`) |
| `OBSIDIAN_DIR` | Absolute path to Obsidian vault on host machine |
| `SPOTIFY_CLIENT_ID` | Spotify app client ID |
| `SPOTIFY_CLIENT_SECRET` | Spotify app client secret |
| `SPOTIFY_REDIRECT_URI` | Spotify OAuth redirect (e.g. `https://www.<DOMAIN>/api/spotify/callback`) |
| `SPOTIFY_AUTH_STATE` | Arbitrary state string for Spotify OAuth |
| `ICECAST_SOURCE_PASSWORD` | Icecast source connection password |
| `ICECAST_RELAY_PASSWORD` | Icecast relay password |
| `ICECAST_ADMIN_USER` | Icecast admin username |
| `ICECAST_ADMIN_PASSWORD` | Icecast admin password |
| `ICECAST_HOST` | Icecast hostname (use `icecast` for Docker) |
| `ICECAST_PORT` | Icecast port (typically `8000`) |
| `ICECAST_MOUNT` | Icecast mount point (e.g. `/stream`) |
| `LIQUIDSOAP_HARBOR_MOUNT` | Liquidsoap live input mount (e.g. `/live`) |
| `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 (read by the Python service, which makes every Claude call) |
| `STEAM_API_KEY` | Steam Web API key |
| `STEAM_ID` | Steam user ID |
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
| `PYTHON_PORT` | Python API port (defaults to `8000`) |
| `SEED_DB` | Set to `true` to seed test data on startup |
### Gitea Config
Copy from the template and fill in secrets:
```sh
cp gitea/config/app.ini.template gitea/config/app.ini
```
Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the database `PASSWD`. Alternatively, the Gitea entrypoint generates `app.ini` from the template using environment variables.
### Spotify Token Setup
4. After authorization, Spotify redirects to the callback endpoint which stores tokens at `/backend/token/spotify_token.json`
5. Tokens are refreshed automatically; the file persists across container restarts via volume mount
### Obsidian Notes Setup
1. Set `OBSIDIAN_DIR` in `.env` to the absolute path of your Obsidian vault on the host machine
2. The vault is mounted read-write into `silverbullet` at `/data`, which serves it as an
editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at
`/notes/` with `SB_READ_ONLY`
3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off
`/notes/` by `SB_SPACE_IGNORE` **and** nginx deny blocks — the nginx blocks are the ones that
actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary")
4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above)
### SSL Certificates (Certbot)
**Initial setup (production):**
1. Set `DOMAIN` and `EMAIL` in `.env`
2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/`
3. Certbot requests a certificate via `certbot certonly --webroot`
4. Once the certificate is issued to `certbot/conf/live/<DOMAIN>/`, restart Nginx — it will detect the certs and switch to the full `nginx.conf.template`
5. Certbot checks for renewal every 12 hours automatically
**Dev mode:** Nginx generates a self-signed certificate for localhost automatically.
### Icecast Radio
Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays these as fallback when no live source is connected. Connect a live source to port 8001 on the `LIQUIDSOAP_HARBOR_MOUNT`.
### Gitea Runner
1. Download the `act_runner` binary from [Gitea releases](https://gitea.com/gitea/act_runner/releases) and place in `gitea-runner/`
2. Set `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`
3. The runner registers automatically on first startup
## Dev Mode
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
```
This:
- Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.)
- Generates a self-signed certificate for localhost
- Disables certbot
- Seeds the database with test data (`SEED_DB=true`)
- Enables GraphQL playground and introspection
Visit `http://localhost` to test.
### Frontend only (hot reload)
```sh
cd vue && npm run dev
```
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
These files are git-ignored and must be created manually:
| File | Notes |
| ------------------------------- | --------------------------------------------------------------- |
| `.env` | See setup section above |
| `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
| `certbot/conf/`, `certbot/www/` | Created automatically by certbot; use dev mode to skip |
| `backend/token/` | Created automatically by Docker volume mount |
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file |
| `gitea-runner/act_runner` | Download from Gitea releases |
| `gitea-runner/.runner` | Generated on first runner startup |
## Future Ideas
- ML for chatboards
- Cache requests
- Design more webpages
- Calendar to show radio times
- Nice smooth function background and transitions
- Design shrines
- Redis (not really but practical experience)
+49 -3
View File
@@ -1,14 +1,60 @@
FROM golang:1.24
# =============================================================================
# Go backend image — multi-stage: build with the full toolchain, ship a slim
# runtime containing one static binary.
#
# STAGE 1 (golang:1.26)
# go.mod/go.sum are copied and downloaded BEFORE the rest of the source, so
# the dependency layer is cached and only re-runs when the module files
# change — a meaningful saving when building on a Raspberry Pi.
#
# The `--mount=type=cache` lines are BuildKit cache mounts: the module cache
# and the Go build cache persist BETWEEN builds on the host without being
# baked into any image layer. This is the single biggest reason a rebuild on
# the Pi takes minutes rather than much longer. They require BuildKit, which
# is the default in modern `docker compose build`.
#
# CGO_ENABLED=0 produces a fully static binary with no libc dependency, which
# is what lets a golang-built binary run on a different, slimmer base image.
#
# STAGE 2 (debian:bookworm-slim)
# Carries only the binary plus ca-certificates — needed because the backend
# makes outbound HTTPS calls (Spotify, Claude, Steam, the Gitea feed) and
# would fail certificate verification without a trust store.
#
# EXPOSE 8080 is documentation only; the port is never published to the host.
# nginx reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
#
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
# amd64 (a dev laptop) with no platform pin.
# =============================================================================
FROM golang:1.26 AS builder
WORKDIR /backend
COPY go.mod go.sum ./
RUN go mod download
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
COPY . ./
RUN go build -o main .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -o main .
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" 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/*
WORKDIR /backend
COPY --from=builder /backend/main ./main
EXPOSE 8080
+344
View File
@@ -0,0 +1,344 @@
# Backend
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). 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
sees it.
## Layout
```
main.go wiring: env -> services -> Store -> routes
models/models.go GORM entities, which are ALSO the GraphQL object types
handlers/ REST endpoints + the shared Store dependency container
store.go Store: DB, service handles, and the third-party caches
handle_*.go one file per domain
services/ stateful collaborators (DB, auth, chat hub, API clients)
graph/ GraphQL layer
schema/*.graphql source of truth for the schema, 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
generated.go GENERATED, do not edit
model/models_gen.go GENERATED, do not edit
```
## Request lifecycle
1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
proxies to this service.
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
that `ClientIP()` — which the login rate limiter keys on — cannot be
spoofed via `X-Forwarded-For`.
3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a
valid access token and stashes the claims in the Gin context;
`AdminMiddleware` then requires `admin: true` in those claims. A handler
reached through the `admin` group can assume both.
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
*annotates* the request context with the Gin context and, if a valid access
token is present, the JWT claims — and then lets everything through. 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`.
## Auth
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary
requests authorise without a database hit;
- `refresh_token` (365 days) carries only `id`.
- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
token for a new pair, re-reading the user — and therefore the admin flag —
from the database.
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
and will transparently refresh, so returning admins are recognised without a
visible re-login.
- `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
their next refresh, not immediately.
The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
`graph/auth.resolvers.go`) are parallel by design, since the front end uses
both. They share `services.Auth` and the rate limiter, but each has its own
cookie-writing helper — change one and you must change the other.
## GraphQL 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
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` | 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 or an
absent Steam key all just leave that feature
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
- **database.go** — Postgres via GORM. There are no migration files:
`AutoMigrate` is the whole schema story, so it adds tables/columns but never
drops or renames, and a new model must be listed there to get a table.
- **auth.go** — HS256 JWT minting and verification.
- **ratelimit.go** — in-memory per-IP sliding window (5 logins/minute).
Process-local and never evicts keys.
- **websocket.go** — the chat hub. A package-level singleton: one connection
set, one mutex, one DB handle. Public, with admin connections additionally
able to see/send private messages and delete.
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
(Steam).
- **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
in `docker-compose.dev.yml`).
## Regenerating gqlgen
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
the end of it — which is why shared helpers live in `*_helpers.go` instead.
`gqlgen.yml` maps most GraphQL object types directly onto the GORM structs in
`models/`, so `graph/model/` holds only input and payload types. Adding a type
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
generated struct rather than the model you expected.
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 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`; 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
50 messages.
- **Store's caches are unsynchronised** and shared by all requests. The races
are benign (at worst a duplicate upstream fetch), but do not add a field
there that would be unsafe to tear.
- **Claude'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;
the container is simply killed.
## Environment
| var | purpose |
| --- | --- |
| `POSTGRES_USER` / `_PASSWORD` / `_DB` / `_HOST` / `_PORT` | database connection |
| `BACKEND_PORT` | listen port |
| `BACKEND_SECRET` | JWT signing secret |
| `BACKEND_ENDPOINT` | this service's public base URL |
| `DOMAIN` | auth cookie domain and WebSocket origin allow-list |
| `DEV_MODE` | release vs debug Gin; gates the two GraphQL dev flags |
| `SEED_DB` | seed dev test data (never in production) |
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
| `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 |
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/` (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.
+33 -20
View File
@@ -1,31 +1,49 @@
module adam-french.co.uk/backend
go 1.24.0
go 1.26
require (
github.com/99designs/gqlgen v0.17.95
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
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
github.com/vektah/gqlparser/v2 v2.5.37
github.com/zmb3/spotify/v2 v2.4.3
golang.org/x/crypto v0.43.0
golang.org/x/crypto v0.55.0
golang.org/x/oauth2 v0.30.0
gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.1
)
require (
github.com/anthropics/anthropic-sdk-go v1.26.0 // indirect
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
github.com/coder/websocket v1.8.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.6.0 // indirect
@@ -35,27 +53,22 @@ require (
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // 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/sosodev/duration v1.4.0 // 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
golang.org/x/arch v0.20.0 // indirect
golang.org/x/mod v0.29.0 // indirect
golang.org/x/net v0.46.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/sys v0.37.0 // indirect
golang.org/x/text v0.30.0 // indirect
golang.org/x/tools v0.38.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.36.10 // indirect
golang.org/x/mod v0.40.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/tools v0.49.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
)
+68 -42
View File
@@ -31,10 +31,38 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/99designs/gqlgen v0.17.95 h1:882h7F5iJImgtyUVttc4MOK2NbzbMYc2oyNeHqkjpP4=
github.com/99designs/gqlgen v0.17.95/go.mod h1:kHYPrpwOXDU1OQyxIg3Z7nVXSnlUoHVWBY7CMJCAM4M=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
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/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/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=
@@ -47,9 +75,13 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/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=
@@ -71,10 +103,12 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
@@ -102,10 +136,7 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
@@ -129,12 +160,16 @@ github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hf
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
@@ -160,15 +195,14 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
@@ -178,6 +212,8 @@ github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQ
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/sosodev/duration v1.4.0 h1:35ed0KiVFriGHHzZZJaZLgmTEEICIyt8Sx0RQfj9IjE=
github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -187,22 +223,14 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
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/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/vektah/gqlparser/v2 v2.5.37 h1:jbb1Ilv+xBklV6653tKb4oVUupPNTLb5LmrnBKVI12Y=
github.com/vektah/gqlparser/v2 v2.5.37/go.mod h1:9O4Ox6Ngd3Y12bMD3w6i3CRQXh8W1oC1q0m6olCymDM=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -216,6 +244,8 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -226,8 +256,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -260,8 +290,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -294,14 +324,13 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20210810183815-faf39c7919d5 h1:Ati8dO7+U7mxpkPSxBZQEvzHVUYB/MqCklCN8ig5w/o=
golang.org/x/oauth2 v0.0.0-20210810183815-faf39c7919d5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
@@ -315,8 +344,8 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -347,12 +376,11 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -368,8 +396,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -415,8 +443,8 @@ golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -443,7 +471,6 @@ google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
@@ -499,14 +526,13 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
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.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
+130
View File
@@ -0,0 +1,130 @@
schema:
- graph/schema/*.graphql
exec:
filename: graph/generated.go
package: graph
model:
filename: graph/model/models_gen.go
package: model
resolver:
layout: follow-schema
dir: graph
package: graph
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
fields:
password:
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
fields:
deletedAt:
resolver: false
Activity:
model:
- adam-french.co.uk/backend/models.Activity
fields:
deletedAt:
resolver: false
Favorite:
model:
- adam-french.co.uk/backend/models.Favorite
fields:
deletedAt:
resolver: false
Rowing:
model:
- adam-french.co.uk/backend/models.Rowing
fields:
deletedAt:
resolver: false
Message:
model:
- adam-french.co.uk/backend/models.Message
fields:
deletedAt:
resolver: false
Bookmark:
model:
- adam-french.co.uk/backend/models.Bookmark
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
+35
View File
@@ -0,0 +1,35 @@
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"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateActivity is the resolver for the createActivity field.
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
// Admin-only, but there is no check to see here: the field is marked
// @admin in the schema and the directive (directives.go) has already
// refused anyone else by the time this runs.
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
if err := r.Store.DB.Create(&activity).Error; err != nil {
return nil, err
}
return &activity, nil
}
// Activities is the resolver for the activities field.
func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, error) {
var activities []models.Activity
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
return nil, err
}
return ptrs(activities), nil
}
+141
View File
@@ -0,0 +1,141 @@
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"
"fmt"
"log"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"golang.org/x/crypto/bcrypt"
)
// Login is the resolver for the login field.
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
// The Gin context is needed for two things GraphQL cannot express: the
// client IP for rate limiting, and setting response cookies. It is
// smuggled in by AuthContextMiddleware.
//
// This mutation mirrors handlers.Store.Login; the two share the limiter
// and services.Auth, so the same 5/min budget covers both entry points.
gc := GinContextFromCtx(ctx)
if gc == nil {
return nil, fmt.Errorf("could not get gin context")
}
if !r.Store.LoginLimiter.Allow(gc.ClientIP()) {
return nil, fmt.Errorf("too many login attempts, please try again later")
}
// Identical message for unknown user and wrong password, so the API
// cannot be used to enumerate usernames.
var user models.User
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
return nil, fmt.Errorf("invalid credentials")
}
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(input.Password)); err != nil {
return nil, fmt.Errorf("invalid credentials")
}
tokens, err := r.Store.Auth.GenerateJWT(&user)
if err != nil {
return nil, fmt.Errorf("failed to generate tokens")
}
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
// The payload carries no token: the tokens only ever travel as HttpOnly
// cookies, so client JavaScript never sees them.
return &model.AuthPayload{User: &user}, nil
}
// Logout is the resolver for the logout field.
func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
gc := GinContextFromCtx(ctx)
if gc == nil {
return false, fmt.Errorf("could not get gin context")
}
// Bumping the token version is what actually revokes the tokens; clearing
// the cookies only stops the browser presenting them. Both are best
// effort and logout always reports success, matching the REST endpoint.
if userID, ok := UserIDFromCtx(ctx); ok {
// The context only carries claims from a token that already
// verified, so this cannot be used to revoke someone else's sessions.
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
}
}
services.ClearAuthCookies(gc, r.Store.Auth.Config)
return true, nil
}
// RefreshToken is the resolver for the refreshToken field.
func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload, error) {
gc := GinContextFromCtx(ctx)
if gc == nil {
return nil, fmt.Errorf("could not get gin context")
}
refreshToken, err := gc.Cookie("refresh_token")
if err != nil {
return nil, fmt.Errorf("unauthorized")
}
// Shared with the REST refresh endpoint, but the messages below are the
// ones this resolver already returned, so the GraphQL error strings are
// unchanged. Admin status and the token version are both re-read from the
// database here, which is what lets a revoked admin flag or a logout take
// effect on refresh.
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
if err != nil {
switch {
case errors.Is(err, services.ErrInvalidClaims):
return nil, fmt.Errorf("invalid token claims")
case errors.Is(err, services.ErrUserNotFound):
return nil, fmt.Errorf("user not found")
default:
return nil, fmt.Errorf("unauthorized")
}
}
tokens, err := r.Store.Auth.GenerateJWT(user)
if err != nil {
return nil, fmt.Errorf("failed to generate tokens")
}
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
return &model.AuthPayload{User: user}, nil
}
// 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")
}
// Read fresh from the database rather than returned from the token
// claims, so `me` reflects the current username and admin flag.
var user models.User
user.ID = userID
if err := r.Store.DB.First(&user).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
return &user, nil
}
+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)
}
}
}
+46
View File
@@ -0,0 +1,46 @@
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"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateBookmark is the resolver for the createBookmark field.
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
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
}
return &bookmark, nil
}
// DeleteBookmark is the resolver for the deleteBookmark field.
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
// Loaded first so the deleted record can be returned to the client, and
// so a missing id is a clean "not found" rather than a silent no-op.
// Delete is a soft delete: deleted_at is set and the row stays.
var bookmark models.Bookmark
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&bookmark).Error; err != nil {
return nil, err
}
return &bookmark, nil
}
// Bookmarks is the resolver for the bookmarks field.
func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, error) {
var bookmarks []models.Bookmark
if err := r.Store.DB.Order("category ASC, created_at DESC").Find(&bookmarks).Error; err != nil {
return nil, err
}
return ptrs(bookmarks), nil
}
+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)
}
})
}
}
+83
View File
@@ -0,0 +1,83 @@
package graph
import (
"context"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// This file is the bridge between Gin's request handling and gqlgen's
// resolvers. gqlgen resolvers receive only a context.Context, so
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
// the *gin.Context itself into that context, and these accessors read them
// back out.
// contextKey is a private named type so that these keys can never collide
// with a key set by another package — the reason the standard library warns
// against using bare strings as context keys. Note the string value
// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the
// *Gin* context, but the two are unrelated and do not see each other.
type contextKey string
const (
userClaimsKey contextKey = "userClaims"
ginContextKey contextKey = "ginContext"
)
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
// is anonymous. nil means "not authenticated": a missing or invalid token is
// not an error here, because many queries are public. 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 {
return nil
}
return claims
}
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
// float64 because claims are decoded by encoding/json, hence the conversion.
//
// ok is also the test behind the @signedIn directive. A resolver calls this
// itself when it needs the id for more than a gate: to record a post's
// author, or to compare the caller with a row's owner.
func UserIDFromCtx(ctx context.Context) (uint, bool) {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
return 0, false
}
idF, ok := (*claims)["id"].(float64)
if !ok {
return 0, false
}
return uint(idF), true
}
// 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 {
return false
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
}
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need
// for things that live outside GraphQL's model: setting auth cookies and
// reading the client IP. Returns nil if the middleware was not installed,
// which the auth resolvers surface as an error rather than panicking.
func GinContextFromCtx(ctx context.Context) *gin.Context {
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
if !ok {
return nil
}
return gc
}
+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)
}
}
+51
View File
@@ -0,0 +1,51 @@
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
// serves most of the site's data.
//
// How the pieces fit:
//
// - graph/schema/*.graphql is the source of truth. Running
// `go run github.com/99designs/gqlgen generate` regenerates generated.go
// and model/models_gen.go, and adds stubs for any new field to the
// matching *.resolvers.go. Never edit those two generated files.
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
// structs in backend/models, so model/ holds only input and payload
// types. A model's `ID uint` binds to `id: ID!` directly, because
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
// needed for it. A field resolver is only written where the Go type has
// no binding (Message.authorId and Rowing's time/distance are unsigned in
// Go and Int in the schema).
// - Resolvers reach the database and the third-party caches through
// Resolver.Store, the same handlers.Store the REST endpoints use.
// - context.go and middleware.go carry the caller's identity from Gin into
// the plain context.Context a resolver receives.
//
// 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. What guards a field is a
// directive on it in the schema:
//
// createUser(input: CreateUserInput!): User! @admin
// places: [Place!]! @signedIn
//
// @admin requires an admin's access token, @signedIn any valid one. Both are
// implemented once, in directives.go, and run before the resolver, so a
// guarded resolver contains no check of its own. A field with NEITHER
// directive is fully public.
//
// The rule of thumb in this schema is that queries are public and mutations
// are @admin, with these exceptions: login, logout and refreshToken are
// public; the places mutations and query are @signedIn; and the users
// queries are @admin (they are private data).
// directives_test.go holds that list and fails when the schema departs from
// it — in particular when a mutation is added with no directive.
//
// A directive is only a gate. Anything finer stays in the resolver and uses
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
// author, `me` answers for the caller (with its own "unauthorized" error),
// the messages query hides private messages from non-admins rather than
// refusing, and spotifyNeedsReauth is simply false for non-admins.
//
// The files ending in _helpers.go are hand-written and are not touched by
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
// them by hand may be moved to the end of the file on the next generate.
package graph
+32
View File
@@ -0,0 +1,32 @@
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"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateFavorite is the resolver for the createFavorite field.
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
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
}
return &favorite, nil
}
// Favorites is the resolver for the favorites field.
func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, error) {
var favorites []models.Favorite
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
return nil, err
}
return ptrs(favorites), nil
}
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
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"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/services"
)
// GiteaFeed is the resolver for the giteaFeed field.
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
// One-minute cache on the Store, shared by every visitor, so a busy home
// page does not hammer the Gitea container.
if cached, ok := r.Store.CachedGiteaFeed(); ok {
return mapGiteaFeed(cached), nil
}
feed, err := services.FetchLatestFeed(r.Store.GiteaHost, r.Store.GiteaPort)
if err != nil {
return nil, err
}
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
// would dereference it, so return null to the client instead. The cache
// is deliberately not written in that case, so an empty feed is retried
// on the next request.
if feed == nil {
return nil, nil
}
r.Store.SetGiteaFeed(feed)
return mapGiteaFeed(feed), nil
}
+21
View File
@@ -0,0 +1,21 @@
package graph
import (
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/services"
)
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
// commit message out of the doubly-encoded Content field as it goes. It
// dereferences feed, so callers must rule out the (nil, nil) that
// FetchLatestFeed returns for an empty feed.
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
return &model.GiteaFeedItem{
AvatarURL: feed.ActUser.AvatarURL,
RepoURL: feed.Repo.HTMLURL,
RepoName: feed.Repo.FullName,
OpType: feed.OpType,
CommitMessage: services.ParseCommitMessage(feed.Content),
CreatedAt: feed.Created,
}
}
+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
}
+44
View File
@@ -0,0 +1,44 @@
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"
"adam-french.co.uk/backend/models"
)
// AuthorID is the resolver for the authorId field.
// AuthorID is the resolver for the authorId field. The value is the chat
// hub's per-connection counter, not a User id — see models.Message.
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
return int(obj.AuthorID), nil
}
// Messages is the resolver for the messages field.
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
// Non-admins get the public subset rather than an error, so the chat
// history loads for everyone. The same filter is applied to the history
// replayed over the WebSocket (services.HandleWebSocket) — change one and
// the other must change too.
//
// Note the ordering differs between the two: newest first here, oldest
// first over the socket.
var messages []models.Message
query := r.Store.DB.Order("created_at DESC")
if !IsAdminFromCtx(ctx) {
query = query.Where("private = ?", false)
}
if err := query.Find(&messages).Error; err != nil {
return nil, err
}
return ptrs(messages), nil
}
// Message returns MessageResolver implementation.
func (r *Resolver) Message() MessageResolver { return &messageResolver{r} }
type messageResolver struct{ *Resolver }
+47
View File
@@ -0,0 +1,47 @@
package graph
import (
"context"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// AuthContextMiddleware prepares the request context for the GraphQL handler.
//
// It always attaches the *gin.Context, and attaches the JWT claims only when a
// valid access token is present. Crucially it never rejects a request: a
// missing, expired or forged token simply leaves the context anonymous, which
// is what lets public queries work and leaves every authorisation decision
// to the field being resolved — the @admin / @signedIn directives on it (see
// directives.go), or the resolver itself for anything finer. Both cookie and
// verify errors are swallowed for exactly that reason.
//
// It takes the database because validating a token means loading the user to
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
//
// Unlike the REST path there is no refresh-token fallback here, so once the
// access token expires GraphQL treats the caller as anonymous until the front
// end refreshes.
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
accessToken, err := c.Cookie("access_token")
if err == nil {
// The database is needed to check the token version, so a
// revoked token (logout, password change) leaves the request
// anonymous instead of continuing to authorise mutations.
_, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken)
if err == nil {
ctx = context.WithValue(ctx, userClaimsKey, claims)
}
}
// The context is immutable, so the enriched one has to be written
// back onto the request for the gqlgen handler to see it.
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}
+232
View File
@@ -0,0 +1,232 @@
// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.
package model
import (
"time"
"adam-french.co.uk/backend/models"
)
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"`
Link *string `json:"link,omitempty"`
}
type CreateBookmarkInput struct {
Category string `json:"category"`
Name string `json:"name"`
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 CreateLayoutInput struct {
Name string `json:"name"`
Page string `json:"page"`
}
type CreatePageInput struct {
Slug string `json:"slug"`
Title string `json:"title"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type CreatePlaceInput struct {
Title string `json:"title"`
Location *string `json:"location,omitempty"`
Notes *string `json:"notes,omitempty"`
ImageURL *string `json:"imageUrl,omitempty"`
Category *string `json:"category,omitempty"`
Cost *string `json:"cost,omitempty"`
Priority *int `json:"priority,omitempty"`
Done *bool `json:"done,omitempty"`
}
type CreatePostInput struct {
Title string `json:"title"`
Content string `json:"content"`
}
type CreateUserInput struct {
Username string `json:"username"`
Password string `json:"password"`
}
type GiteaFeedItem struct {
AvatarURL string `json:"avatarUrl"`
RepoURL string `json:"repoUrl"`
RepoName string `json:"repoName"`
OpType string `json:"opType"`
CommitMessage string `json:"commitMessage"`
CreatedAt time.Time `json:"createdAt"`
}
type LoginInput struct {
Username string `json:"username"`
Password string `json:"password"`
}
type Mutation struct {
}
type Query struct {
}
type SpotifyAlbum struct {
Name string `json:"name"`
Images []*SpotifyImage `json:"images"`
}
type SpotifyArtist struct {
Name string `json:"name"`
}
type SpotifyImage struct {
URL string `json:"url"`
}
type SpotifyPlaying struct {
Playing bool `json:"playing"`
Track *SpotifyTrack `json:"track,omitempty"`
}
type SpotifyRecentItem struct {
Track *SpotifyTrack `json:"track"`
PlayedAt time.Time `json:"playedAt"`
}
type SpotifyTrack struct {
Name string `json:"name"`
Artists []*SpotifyArtist `json:"artists"`
Album *SpotifyAlbum `json:"album"`
}
type SteamGame struct {
AppID int `json:"appId"`
Name string `json:"name"`
Playtime2Weeks int `json:"playtime2Weeks"`
PlaytimeForever int `json:"playtimeForever"`
HeaderImageURL string `json:"headerImageUrl"`
}
type SteamStatus struct {
Online bool `json:"online"`
RecentGames []*SteamGame `json:"recentGames"`
}
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 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 {
Title *string `json:"title,omitempty"`
Location *string `json:"location,omitempty"`
Notes *string `json:"notes,omitempty"`
ImageURL *string `json:"imageUrl,omitempty"`
Category *string `json:"category,omitempty"`
Cost *string `json:"cost,omitempty"`
Priority *int `json:"priority,omitempty"`
Done *bool `json:"done,omitempty"`
}
type UpdatePostInput struct {
Title string `json:"title"`
Content string `json:"content"`
}
+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)
}
}
}
+98
View File
@@ -0,0 +1,98 @@
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"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// 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, 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,
Notes: input.Notes,
ImageURL: input.ImageURL,
Category: input.Category,
Cost: input.Cost,
}
if input.Priority != nil {
place.Priority = *input.Priority
}
if input.Done != nil {
place.Done = *input.Done
}
if err := r.Store.DB.Create(&place).Error; err != nil {
return nil, err
}
return &place, nil
}
// UpdatePlace is the resolver for the updatePlace field.
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
// Partial update, same pointer-means-supplied convention as job
// applications: nil fields are left as they are.
var place models.Place
if err := r.Store.DB.First(&place, id).Error; err != nil {
return nil, err
}
if input.Title != nil {
place.Title = *input.Title
}
if input.Location != nil {
place.Location = input.Location
}
if input.Notes != nil {
place.Notes = input.Notes
}
if input.ImageURL != nil {
place.ImageURL = input.ImageURL
}
if input.Category != nil {
place.Category = input.Category
}
if input.Cost != nil {
place.Cost = input.Cost
}
if input.Priority != nil {
place.Priority = *input.Priority
}
if input.Done != nil {
place.Done = *input.Done
}
if err := r.Store.DB.Save(&place).Error; err != nil {
return nil, err
}
return &place, nil
}
// DeletePlace is the resolver for the deletePlace field.
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
var place models.Place
if err := r.Store.DB.First(&place, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&place).Error; err != nil {
return nil, err
}
return &place, nil
}
// Places is the resolver for the places field.
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
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
}
+116
View File
@@ -0,0 +1,116 @@
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"
)
// CreatePost is the resolver for the createPost field.
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
// @admin has already established that there is a session; the id is read
// here because the post needs an author, not as a second gate. The !ok
// branch is only reachable with a token that has admin but no usable id.
userID, ok := UserIDFromCtx(ctx)
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
}
return &post, nil
}
// UpdatePost is the resolver for the updatePost field.
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
}
var post models.Post
if err := r.Store.DB.First(&post, id).Error; err != nil {
return nil, fmt.Errorf("post not found")
}
// 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")
}
// Both fields are non-pointer in the input, so this is a full replace —
// omitting one in the mutation blanks it rather than leaving it alone.
post.Title = input.Title
post.Content = input.Content
if err := r.Store.DB.Save(&post).Error; err != nil {
return nil, err
}
return &post, nil
}
// DeletePost is the resolver for the deletePost field.
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
userID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
}
var post models.Post
if err := r.Store.DB.First(&post, id).Error; err != nil {
return nil, fmt.Errorf("post not found")
}
if post.AuthorID != userID {
return nil, fmt.Errorf("you can only delete your own posts")
}
// Soft delete. The error is propagated: reporting success for a delete
// that did not happen would leave the client showing the post as gone
// until the next reload.
if err := r.Store.DB.Delete(&post).Error; err != nil {
return nil, err
}
return &post, 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.
// Without it the field is nil and the schema's author field resolves to
// null — there is no lazy loading and no error to tell you why.
var posts []models.Post
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
return nil, err
}
return ptrs(posts), nil
}
// Post is the resolver for the post field.
func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error) {
var post models.Post
if err := r.Store.DB.Preload("Author").First(&post, id).Error; err != nil {
return nil, fmt.Errorf("post not found")
}
return &post, nil
}
+23
View File
@@ -0,0 +1,23 @@
package graph
import "adam-french.co.uk/backend/handlers"
// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require
// here.
// Resolver is the root of the GraphQL schema and the only dependency every
// resolver has. Rather than listing dependencies individually it holds the
// same handlers.Store the REST handlers use, so GraphQL and REST share one
// database handle and one set of third-party caches.
//
// The generated code embeds *Resolver in per-type resolver structs, 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
}
+38
View File
@@ -0,0 +1,38 @@
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"
"adam-french.co.uk/backend/models"
)
// RowingSessions is the resolver for the rowingSessions field.
func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, error) {
var rows []models.Rowing
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
return nil, err
}
return ptrs(rows), 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.
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
return int(obj.Time), nil
}
// Distance is the resolver for the distance field.
func (r *rowingResolver) Distance(ctx context.Context, obj *models.Rowing) (int, error) {
return int(obj.Distance), nil
}
// Rowing returns RowingResolver implementation.
func (r *Resolver) Rowing() RowingResolver { return &rowingResolver{r} }
type rowingResolver struct{ *Resolver }
+17
View File
@@ -0,0 +1,17 @@
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
// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }
type (
mutationResolver struct{ *Resolver }
queryResolver struct{ *Resolver }
)
+22
View File
@@ -0,0 +1,22 @@
type Activity {
id: ID!
createdAt: Time!
updatedAt: Time!
type: String!
name: String!
link: String
}
input CreateActivityInput {
type: String!
name: String!
link: String
}
extend type Query {
activities: [Activity!]!
}
extend type Mutation {
createActivity(input: CreateActivityInput!): Activity! @admin
}
+22
View File
@@ -0,0 +1,22 @@
input LoginInput {
username: String!
password: String!
}
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!
refreshToken: AuthPayload!
}
+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
}
+23
View File
@@ -0,0 +1,23 @@
type Bookmark {
id: ID!
createdAt: Time!
updatedAt: Time!
category: String!
name: String!
link: String!
}
input CreateBookmarkInput {
category: String!
name: String!
link: String!
}
extend type Query {
bookmarks: [Bookmark!]!
}
extend type Mutation {
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
}
+22
View File
@@ -0,0 +1,22 @@
type Favorite {
id: ID!
createdAt: Time!
updatedAt: Time!
type: String!
name: String!
link: String
}
input CreateFavoriteInput {
type: String!
name: String!
link: String
}
extend type Query {
favorites: [Favorite!]!
}
extend type Mutation {
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
}
+15
View File
@@ -0,0 +1,15 @@
# Latest activity from the self-hosted Gitea instance, proxied and cached for
# one minute by the backend. Resolves to null when the feed is empty.
type GiteaFeedItem {
avatarUrl: String!
repoUrl: String!
repoName: String!
opType: String!
commitMessage: String!
createdAt: Time!
}
extend type Query {
giteaFeed: GiteaFeedItem
}
+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
}
+20
View File
@@ -0,0 +1,20 @@
# Chat history. The live chat runs over the WebSocket at /ws, not GraphQL;
# this query is the initial page load.
#
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
# User id, and private messages are silently filtered out for non-admins
# rather than causing an error — which is why the query has no @admin: the
# resolver makes that decision per row.
type Message {
id: ID!
content: String!
authorId: Int!
fileUrl: String
private: Boolean!
createdAt: Time!
}
extend type Query {
messages: [Message!]!
}
+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
}
+49
View File
@@ -0,0 +1,49 @@
# 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!
createdAt: Time!
updatedAt: Time!
title: String!
location: String
notes: String
imageUrl: String
category: String
cost: String
priority: Int!
done: Boolean!
}
input CreatePlaceInput {
title: String!
location: String
notes: String
imageUrl: String
category: String
cost: String
priority: Int
done: Boolean
}
input UpdatePlaceInput {
title: String
location: String
notes: String
imageUrl: String
category: String
cost: String
priority: Int
done: Boolean
}
extend type Query {
places: [Place!]! @signedIn
}
extend type Mutation {
createPlace(input: CreatePlaceInput!): Place! @signedIn
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
deletePlace(id: ID!): Place! @signedIn
}
+31
View File
@@ -0,0 +1,31 @@
type Post {
id: ID!
createdAt: Time!
updatedAt: Time!
title: String!
author: User
content: String!
}
input CreatePostInput {
title: String!
content: String!
}
input UpdatePostInput {
title: String!
content: String!
}
extend type Query {
posts: [Post!]!
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! @admin
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
deletePost(id: ID!): Post! @admin
}
+13
View File
@@ -0,0 +1,13 @@
type Rowing {
id: ID!
createdAt: Time!
date: Time!
time: Int!
distance: Int!
timePer500m: Float!
calories: Float!
}
extend type Query {
rowingSessions: [Rowing!]!
}
+37
View File
@@ -0,0 +1,37 @@
# Root of the GraphQL schema.
#
# Query and Mutation are declared here with no fields; every other file in this
# directory adds to them with `extend type Query` / `extend type Mutation`.
# That is what lets the schema be split one file per domain, matching the
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
#
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
# serialised as RFC 3339.
#
# These files are the source of truth: after editing one, run
# go run github.com/99designs/gqlgen generate
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
# Note that `#` comments like this one are invisible to clients; a `"""` block
# would become a schema description and show up in introspection.
scalar Time
# 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
+42
View File
@@ -0,0 +1,42 @@
# Spotify "now playing" / "recently played" for the home page. Both resolve to
# null / an empty list when the backend has never completed the Spotify OAuth
# flow, so the page degrades rather than erroring.
type SpotifyArtist {
name: String!
}
type SpotifyImage {
url: String!
}
type SpotifyAlbum {
name: String!
images: [SpotifyImage!]!
}
type SpotifyTrack {
name: String!
artists: [SpotifyArtist!]!
album: SpotifyAlbum!
}
type SpotifyPlaying {
playing: Boolean!
track: SpotifyTrack
}
type SpotifyRecentItem {
track: SpotifyTrack!
playedAt: Time!
}
extend type Query {
spotifyListening: SpotifyPlaying
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 — a soft
# check in the resolver, not @admin, so the home page query never errors.
spotifyNeedsReauth: Boolean!
}
+19
View File
@@ -0,0 +1,19 @@
# Steam presence and recent games for the home page, cached for five minutes.
# headerImage is built from the app id rather than returned by Steam's API.
type SteamGame {
appId: Int!
name: String!
playtime2Weeks: Int!
playtimeForever: Int!
headerImageUrl: String!
}
type SteamStatus {
online: Boolean!
recentGames: [SteamGame!]!
}
extend type Query {
steamStatus: SteamStatus
}
+39
View File
@@ -0,0 +1,39 @@
type User {
id: ID!
createdAt: Time!
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 {
username: String!
password: String!
}
extend type Query {
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! @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
}
+22
View File
@@ -0,0 +1,22 @@
package graph
// This file is hand-written and is never regenerated by gqlgen — it is not
// named after a schema file, so `gqlgen generate` leaves it alone.
// ptrs copies a slice of values into a slice of pointers to those values.
//
// Every list query loads rows with Find(&xs) into a []T and then has to hand
// gqlgen a []*T, because the schema returns lists of nullable objects. Taking
// &xs[i] is safe: the slice is never appended to after this point, so the
// backing array cannot move and the pointers stay valid.
//
// Loading straight into a []*T would avoid the copy but changes the query
// GORM emits, so the copy is kept deliberately.
func ptrs[T any](xs []T) []*T {
result := make([]*T, len(xs))
for i := range xs {
result[i] = &xs[i]
}
return result
}
+72
View File
@@ -0,0 +1,72 @@
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"
"adam-french.co.uk/backend/graph/model"
)
// SpotifyListening is the resolver for the spotifyListening field.
func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) {
// A nil client means the OAuth flow has never been completed. Report that
// as null rather than an error so the home page renders without it.
if r.Store.SpotifyClient == nil {
r.Store.LogSpotifyUnauthenticated("spotifyListening")
return nil, nil
}
playing, err := r.Store.SpotifyClient.PlayerCurrentlyPlaying(ctx)
if err != nil {
return nil, err
}
result := &model.SpotifyPlaying{Playing: playing.Playing}
if playing.Item != nil {
result.Track = mapSpotifyTrack(playing.Item)
}
return result, nil
}
// SpotifyRecent is the resolver for the spotifyRecent field.
func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRecentItem, error) {
if r.Store.SpotifyClient == nil {
r.Store.LogSpotifyUnauthenticated("spotifyRecent")
return []*model.SpotifyRecentItem{}, nil
}
// Shared one-minute cache, filled by whichever of this resolver and the
// REST /spotify/recent endpoint misses it first.
played, err := r.Store.RecentlyPlayedTracks(ctx)
if err != nil {
return nil, err
}
return mapRecentItems(played), nil
}
// SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field.
//
// Admin-gated: false for everyone else, so this query leaks nothing. Admin is
// read from the access-token claims the AuthContextMiddleware resolved, not
// the database — the same trade-off AdminMiddleware makes (revocation waits
// for token expiry).
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
if r.Store.SpotifyClient != nil {
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
}
r.Store.LogSpotifyUnauthenticated("spotifyNeedsReauth")
return true, nil
}
+62
View File
@@ -0,0 +1,62 @@
package graph
import (
"adam-french.co.uk/backend/graph/model"
"github.com/zmb3/spotify/v2"
)
// Converters from the Spotify library's rich types to the deliberately narrow
// GraphQL types — the schema exposes only the handful of fields the home page
// renders.
// mapSpotifyImages keeps just the URLs of a set of album images.
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
result := make([]*model.SpotifyImage, len(images))
for i, img := range images {
result[i] = &model.SpotifyImage{URL: img.URL}
}
return result
}
// mapSpotifyTrack converts a currently-playing track.
func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
artists := make([]*model.SpotifyArtist, len(track.Artists))
for i, a := range track.Artists {
artists[i] = &model.SpotifyArtist{Name: a.Name}
}
return &model.SpotifyTrack{
Name: track.Name,
Artists: artists,
Album: &model.SpotifyAlbum{
Name: track.Album.Name,
Images: mapSpotifyImages(track.Album.Images),
},
}
}
// mapRecentItems converts recently played history entries.
//
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
// takes — the duplication is forced by the library's types.
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
result := make([]*model.SpotifyRecentItem, len(items))
for i, item := range items {
artists := make([]*model.SpotifyArtist, len(item.Track.Artists))
for j, a := range item.Track.Artists {
artists[j] = &model.SpotifyArtist{Name: a.Name}
}
result[i] = &model.SpotifyRecentItem{
PlayedAt: item.PlayedAt,
Track: &model.SpotifyTrack{
Name: item.Track.Name,
Artists: artists,
Album: &model.SpotifyAlbum{
Name: item.Track.Album.Name,
Images: mapSpotifyImages(item.Track.Album.Images),
},
},
}
}
return result
}
+53
View File
@@ -0,0 +1,53 @@
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"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/services"
)
// SteamStatus is the resolver for the steamStatus field.
func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, error) {
if r.Store.SteamAPIKey == "" {
return nil, nil
}
// Five-minute cache across both Steam calls, which are made together and
// expire together.
if games, online, ok := r.Store.CachedSteam(); ok {
return &model.SteamStatus{
Online: online,
RecentGames: mapSteamGames(games),
}, nil
}
games, err := services.FetchRecentlyPlayedGames(r.Store.SteamAPIKey, r.Store.SteamID)
if err != nil {
return nil, err
}
summary, err := services.FetchPlayerSummary(r.Store.SteamAPIKey, r.Store.SteamID)
if err != nil {
return nil, err
}
// PersonaState 0 is offline; every higher value is some flavour of
// online. A nil summary (private profile) reads as offline.
online := false
if summary != nil {
online = summary.PersonaState > 0
}
r.Store.SetSteam(games, online)
return &model.SteamStatus{
Online: online,
RecentGames: mapSteamGames(games),
}, nil
}
+27
View File
@@ -0,0 +1,27 @@
package graph
import (
"fmt"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/services"
)
// mapSteamGames converts Steam API games into the GraphQL shape.
//
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
// serves every game's cover art at a predictable path keyed by app id, so
// building the URL here saves an extra API call per game.
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
result := make([]*model.SteamGame, len(games))
for i, g := range games {
result[i] = &model.SteamGame{
AppID: g.AppID,
Name: g.Name,
Playtime2Weeks: g.Playtime2Weeks,
PlaytimeForever: g.PlaytimeForever,
HeaderImageURL: fmt.Sprintf("https://cdn.akamai.steamstatic.com/steam/apps/%d/header.jpg", g.AppID),
}
}
return result
}
+134
View File
@@ -0,0 +1,134 @@
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"
"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) {
// 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
}
user := models.User{Username: input.Username, Password: hashedPassword}
if err := r.Store.DB.Create(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// DeleteUser is the resolver for the deleteUser field.
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
if err := r.Store.DB.Delete(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// SetUserAdmin is the resolver for the setUserAdmin field.
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
callerID, ok := UserIDFromCtx(ctx)
if !ok {
return nil, fmt.Errorf("unauthorized")
}
// Guards against the last admin demoting themselves and locking everyone
// out of the admin UI.
if uint(id) == callerID {
return nil, fmt.Errorf("cannot change your own admin status")
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
user.Admin = admin
if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err
}
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) {
var users []models.User
if err := r.Store.DB.Find(&users).Error; err != nil {
return nil, err
}
return ptrs(users), nil
}
// User is the resolver for the user field.
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
return &user, 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
}
-40
View File
@@ -1,40 +0,0 @@
package handlers
import (
"net/http"
"adam-french.co.uk/backend/models"
"github.com/gin-gonic/gin"
)
type CreateActivityInput struct {
Type string `json:"type" binding:"required"`
Name string `json:"name" binding:"required"`
Link *string `json:"link"`
}
func (store *Store) GetActivity(ctx *gin.Context) {
var activitys []models.Activity
if err := store.DB.Order("Created_At DESC").Find(&activitys).Error; err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
ctx.JSON(http.StatusOK, activitys)
}
func (store *Store) CreateActivity(ctx *gin.Context) {
var input CreateActivityInput
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
return
}
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
tx := store.DB.Create(&activity)
if tx.Error != nil {
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
return
}
ctx.JSON(http.StatusCreated, activity)
}
+290 -99
View File
@@ -1,32 +1,218 @@
package handlers
import (
"fmt"
"errors"
"log"
"net/http"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
// This file holds the REST authentication endpoints and the Gin middleware
// that guards the other REST routes. GraphQL has its own parallel
// implementation of login/logout/refresh in graph/auth.resolvers.go; both
// mint the same cookies through services.Auth.
//
// Cookie model: `access_token` is short-lived and carries id + admin, so most
// requests authorise without a database hit; `refresh_token` carries only the
// id and is exchanged for a fresh pair. Both are set HttpOnly and Secure, so
// JavaScript cannot read them and the browser attaches them automatically.
// UserCredentials is the JSON body of POST /auth/login. The binding tags make
// Gin reject a request missing either field.
type UserCredentials struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// AuthMiddlewear requires a valid access token on a REST route and stashes
// the claims for AdminMiddleware to read.
//
// (The name is misspelled but it is exported and referenced from main.go, so
// it is left alone rather than renamed.)
//
// It deliberately does NOT fall back to the refresh token: an expired access
// token yields a 401 and the front end is expected to call /auth/refresh and
// retry. A token whose version has been revoked is also a 401.
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
ctx.AbortWithStatusJSON(401, err.Error())
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
}
claims, err := store.Auth.VerifyJWT(access_token)
// Validated against the database, not just cryptographically: that is
// what makes a logged-out or password-changed token stop working here
// rather than lingering until it expires.
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
if err != nil {
ctx.AbortWithStatusJSON(401, err.Error())
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
}
// store claims in Gin context
// Stored under a plain string key in the *Gin* context. This is a
// different mechanism from graph/context.go, which puts the same claims
// into the standard library request context under an unexported typed
// key; the two do not see each other's values.
ctx.Set("userClaims", claims)
ctx.Next()
}
// AdminMiddleware requires the access token to carry admin=true. It must be
// chained after AuthMiddlewear, which is what populates "userClaims"; on its
// own it always rejects.
//
// Admin is read from the token, not the database, so revoking someone's admin
// flag only takes effect once their current access token expires.
func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims")
if !exists {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid claims"})
return
}
// A token minted before the admin claim existed simply has no "admin"
// key, so a failed type assertion is treated as "not an admin".
admin, ok := (*mapClaims)["admin"].(bool)
if !ok || !admin {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
ctx.Next()
}
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// 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) {
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
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
})
}
// 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 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.
//
// 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
}
// Any failure at all (bad token, unknown user, revoked version) is
// "cannot decide" here, exactly as before: the caller sends 401.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
return false
}
if !allow(user, nil) {
ctx.Status(http.StatusForbidden)
return true
}
tokens, err := store.Auth.GenerateJWT(user)
if err != nil {
return false
}
store.setAuthCookies(ctx, tokens)
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return true
}
// setAuthCookies writes the access/refresh cookie pair. The cookie
// attributes live in services.SetAuthCookies so that REST and GraphQL cannot
// disagree about them; this method is just the Store-shaped spelling of it.
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
}
// CheckToken backs GET /auth/check: it returns the current user for a valid
// access token, or 401. If the token is valid but the user no longer exists
// it answers 404 and clears the cookies, so the browser stops presenting a
// token for a deleted account.
func (store *Store) CheckToken(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
@@ -34,150 +220,155 @@ func (store *Store) CheckToken(ctx *gin.Context) {
return
}
claims, err := store.Auth.VerifyJWT(access_token)
// Status codes here are unchanged from the hand-rolled version: a bad
// token or bad claims are both 401, and only a missing user is 404 with
// the cookies cleared. A revoked (out-of-date version) token joins the
// 401 case, since from the client's point of view it is simply no longer
// a valid token.
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
if err != nil {
ctx.JSON(401, err.Error())
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(401, gin.H{"error": "claims does not contain id"})
return
}
userID := uint(userIDF)
user := models.User{ID: userID}
tx := store.DB.First(&user)
if tx.Error != nil {
ctx.JSON(http.StatusNotFound, tx.Error.Error())
removeCookies(ctx)
if errors.Is(err, services.ErrUserNotFound) {
log.Println(err)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
return
}
ctx.JSON(401, gin.H{"error": "unauthorized"})
return
}
ctx.JSON(http.StatusOK, user)
}
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
// for a new cookie pair and returns the user.
//
// The old refresh token is not rotated, but it does die when the user logs out
// or changes their password, because those bump the token version this checks.
func (store *Store) RefreshToken(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
ctx.JSON(http.StatusUnauthorized, err.Error())
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
claims, err := store.Auth.VerifyJWT(refreshToken)
// The three outcomes below preserve the original status codes exactly:
// an unusable token is 401, unreadable claims are 500, and a token for a
// user that no longer exists is 404 with the cookies cleared. A revoked
// token is treated as an unusable one (401) — the client's correct
// response is to log in again.
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
ctx.JSON(http.StatusUnauthorized, err.Error())
}
fmt.Printf("claims: %v\n", claims)
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
return
}
userID := uint(userIDF)
user := models.User{ID: userID}
tx := store.DB.First(&user)
if tx.Error != nil {
ctx.JSON(http.StatusNotFound, tx.Error.Error())
removeCookies(ctx)
switch {
case errors.Is(err, services.ErrInvalidClaims):
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
case errors.Is(err, services.ErrUserNotFound):
log.Println(err)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
default:
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
}
return
}
tokens, err := store.Auth.GenerateJWT(&user)
tokens, err := store.Auth.GenerateJWT(user)
if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
ctx.SetCookie(
"access_token",
tokens.AccessToken,
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
ctx.SetCookie(
"refresh_token",
tokens.RefreshToken,
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
store.setAuthCookies(ctx, tokens)
ctx.JSON(http.StatusAccepted, user)
}
// Login backs POST /auth/login. The user object it returns omits the password
// because models.User tags that field `json:"-"`.
func (store *Store) Login(ctx *gin.Context) {
var input UserCredentials
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
// Per-IP limit (5/min) on top of nginx's own login rate limit.
// ctx.ClientIP is only trustworthy because main.go pins the trusted
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
// client talking through nginx.
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
return
}
var input UserCredentials
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
// Unknown user and wrong password return the identical message, so the
// response cannot be used to enumerate usernames. (The timing does
// differ, since only the second path runs bcrypt.)
user := models.User{}
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(input.Password)); err != nil {
ctx.JSON(http.StatusUnauthorized, err.Error())
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
tokens, err := store.Auth.GenerateJWT(&user)
if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
ctx.SetCookie(
"access_token",
tokens.AccessToken,
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
ctx.SetCookie(
"refresh_token",
tokens.RefreshToken,
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
store.setAuthCookies(ctx, tokens)
ctx.JSON(http.StatusAccepted, user)
}
// Logout backs POST /auth/logout. As well as clearing the browser's cookies
// it bumps the user's token version, so the tokens it just discarded — and
// any copy taken beforehand — stop being accepted immediately.
//
// It always answers 200: identifying the caller is best effort (the cookies
// may already be gone or expired), and a client that cannot be identified has
// nothing to revoke anyway.
func (store *Store) Logout(ctx *gin.Context) {
removeCookies(ctx)
store.revokeCallerTokens(ctx)
store.removeCookies(ctx)
ctx.Status(http.StatusOK)
}
func removeCookies(ctx *gin.Context) {
ctx.SetCookie(
"access_token",
"",
-1,
"",
"",
true, true,
)
ctx.SetCookie(
"refresh_token",
"",
-1,
"",
"",
true, true,
)
// revokeCallerTokens bumps the token version of whoever made this request,
// identified from the access token or, failing that, the refresh token.
//
// It deliberately verifies the token rather than just reading the id out of
// it: without that, anyone could bump an arbitrary user's version by posting a
// forged cookie, which is a denial-of-service on that account's sessions.
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
for _, name := range []string{"access_token", "refresh_token"} {
token, err := ctx.Cookie(name)
if err != nil {
continue
}
user, err := store.Auth.AuthenticateToken(store.DB, token)
if err != nil {
continue
}
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
// Logged rather than returned: the cookies are still cleared, but
// this means the logout did not actually revoke anything.
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
}
return
}
}
// removeCookies expires both auth cookies; see services.ClearAuthCookies for
// why the attributes have to match those used when setting them.
func (store *Store) removeCookies(ctx *gin.Context) {
services.ClearAuthCookies(ctx, store.Auth.Config)
}
-40
View File
@@ -1,40 +0,0 @@
package handlers
import (
"net/http"
"adam-french.co.uk/backend/models"
"github.com/gin-gonic/gin"
)
type CreateFavoriteInput struct {
Type string `json:"type" binding:"required"`
Name string `json:"name" binding:"required"`
Link *string `json:"link"`
}
func (store *Store) GetFavorites(ctx *gin.Context) {
var favorites []models.Favorite
if err := store.DB.Order("Created_At DESC").Find(&favorites).Error; err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
ctx.JSON(http.StatusOK, favorites)
}
func (store *Store) CreateFavorite(ctx *gin.Context) {
var input CreateFavoriteInput
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
return
}
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
tx := store.DB.Create(&favorite)
if tx.Error != nil {
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
return
}
ctx.JSON(http.StatusCreated, favorite)
}
+10
View File
@@ -7,9 +7,16 @@ import (
"github.com/gin-gonic/gin"
)
// GetNoteFile serves one file from the notes directory for the admin-only
// route GET /notes/*path. The wildcard means `path` arrives with a leading
// slash and may contain further slashes, so it has to be validated rather
// than trusted — Notes.ParsePath does the containment check.
func (store *Store) GetNoteFile(ctx *gin.Context) {
path := ctx.Param("path")
// A traversal attempt is reported as 404, not 403, so probing cannot
// distinguish a blocked path from a missing one.
path, err := store.Notes.ParsePath(path)
if err != nil {
ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
@@ -22,6 +29,9 @@ func (store *Store) GetNoteFile(ctx *gin.Context) {
return
}
// The SPA reads Last-Modified to show a note's edit date. Browsers hide
// non-safelisted headers from cross-origin fetch() unless they are listed
// in Access-Control-Expose-Headers, hence the second header.
ctx.Header("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
ctx.Header("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified")
-167
View File
@@ -1,167 +0,0 @@
package handlers
import (
"net/http"
"strconv"
"adam-french.co.uk/backend/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
type CreatePostInput struct {
Title string `json:"title" binding:"required"`
Content string `json:"content" binding:"required"`
}
func (store *Store) GetPosts(ctx *gin.Context) {
var posts []models.Post
if err := store.DB.Preload("Author").Order("Created_At DESC").Find(&posts).Error; err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
ctx.JSON(http.StatusOK, posts)
}
func (store *Store) GetPost(ctx *gin.Context) {
postIDStr := ctx.Param("id")
postID, err := strconv.ParseUint(postIDStr, 10, 64)
if err != nil {
ctx.JSON(http.StatusBadRequest, "invalid id")
return
}
post := models.Post{ID: uint(postID)}
if err := store.DB.First(&post).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
return
}
ctx.JSON(http.StatusOK, post)
}
func (store *Store) CreatePost(ctx *gin.Context) {
var input CreatePostInput
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
return
}
claimsVal, ok := ctx.Get("userClaims")
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
return
}
claims, ok := claimsVal.(*jwt.MapClaims)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
return
}
userID := uint(userIDF)
if !(*claims)["admin"].(bool) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "you are not admin :("})
return
}
// Create post
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
tx := store.DB.Create(&post)
if tx.Error != nil {
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
return
}
ctx.JSON(http.StatusCreated, post)
}
func (store *Store) UpdatePost(ctx *gin.Context) {
postID := ctx.Param("id")
var post models.Post
if err := store.DB.First(&post, postID).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
return
}
claimsVal, ok := ctx.Get("userClaims")
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
return
}
claims, ok := claimsVal.(*jwt.MapClaims)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
return
}
userID := uint(userIDF)
if !(userID == post.AuthorID) {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user and post author id missmatch"})
}
var input CreatePostInput
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
return
}
post.Title = input.Title
post.Content = input.Content
tx := store.DB.Save(&post)
if tx.Error != nil {
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
return
}
ctx.JSON(http.StatusOK, post)
}
func (store *Store) DeletePost(ctx *gin.Context) {
postID := ctx.Param("id")
var post models.Post
if err := store.DB.First(&post, postID).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
return
}
claimsVal, ok := ctx.Get("userClaims")
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
return
}
claims, ok := claimsVal.(*jwt.MapClaims)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
return
}
userID := uint(userIDF)
if !(userID == post.AuthorID) {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user and post author id missmatch"})
}
store.DB.Delete(&post)
ctx.JSON(http.StatusOK, post)
}
+224
View File
@@ -0,0 +1,224 @@
package handlers
import (
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
)
// Admin management of the radio's fallback music. These handlers only move
// files around on disk; the Python service is what actually streams them, and
// it picks up the directory contents on its own.
//
// Disabling a song moves it into a "disabled" subdirectory rather than
// deleting it — so presence in that directory IS the disabled flag, and there
// is no database state for the radio at all.
// fallbackMusicDir is a shared volume, also mounted by the radio service.
const fallbackMusicDir = "/backend/fallback_music"
// allowedAudioExtensions is the upload allow-list, keyed by lower-cased
// extension. Unlike chat uploads, the content is not sniffed: the route is
// admin-only and audio formats sniff unreliably.
var allowedAudioExtensions = map[string]bool{
".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true,
}
// UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat
// uploads the original filename is kept, because it is what the admin sees in
// the song list — hence the sanitisation below.
func (store *Store) UploadRadioSong(ctx *gin.Context) {
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
const maxSize = 50 << 20 // 50MB
if file.Size > maxSize {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large (max 50MB)"})
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowedAudioExtensions[ext] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed (accepted: .mp3, .ogg, .flac, .wav, .m4a, .opus)"})
return
}
// filepath.Base strips any directory component, so "../../etc/passwd"
// becomes "passwd". The absolute-path check below is a second, redundant
// guard in case Base ever fails to neutralise some input.
filename := filepath.Base(file.Filename)
dest := filepath.Join(fallbackMusicDir, filename)
// The separator is appended before comparing so a sibling directory whose
// name merely starts with the same characters cannot pass.
absDest, err := filepath.Abs(dest)
if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return
}
// Refuse to overwrite. There is a check-then-write race here, but the
// route is admin-only and single-user in practice.
if _, err := os.Stat(dest); err == nil {
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
return
}
if err := ctx.SaveUploadedFile(file, dest); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
ctx.JSON(http.StatusOK, gin.H{"name": filename})
}
// ListRadioSongs backs the admin-only GET /radio/songs, returning both the
// enabled songs and those parked in the disabled subdirectory, flagged.
func (store *Store) ListRadioSongs(ctx *gin.Context) {
// Declared inside the function because it is purely the JSON shape of
// this one response.
type songInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
Modified int64 `json:"modified"`
Disabled bool `json:"disabled"`
}
// Initialised empty rather than nil so the response is [] and not null.
songs := []songInfo{}
// Read enabled songs
entries, err := os.ReadDir(fallbackMusicDir)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"})
return
}
// Skipping directories is also what keeps the "disabled" subdirectory out
// of the enabled list; dotfiles skip editor and OS cruft.
for _, entry := range entries {
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
songs = append(songs, songInfo{
Name: entry.Name(),
Size: info.Size(),
Modified: info.ModTime().Unix(),
Disabled: false,
})
}
// The disabled directory is created lazily by DisableRadioSong, so a read
// failure here is normally just "nothing has ever been disabled" and is
// ignored rather than reported.
disabledDir := filepath.Join(fallbackMusicDir, "disabled")
disabledEntries, err := os.ReadDir(disabledDir)
if err == nil {
for _, entry := range disabledEntries {
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
songs = append(songs, songInfo{
Name: entry.Name(),
Size: info.Size(),
Modified: info.ModTime().Unix(),
Disabled: true,
})
}
}
ctx.JSON(http.StatusOK, gin.H{"songs": songs})
}
// DisableRadioSong moves a song into the disabled subdirectory so the radio
// stops playing it, keeping the file.
func (store *Store) DisableRadioSong(ctx *gin.Context) {
// filepath.Base neutralises traversal in the :filename route parameter.
// It returns "." for an empty input and "/" for "/", neither of which is
// a real file, so both are rejected explicitly.
filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return
}
src := filepath.Join(fallbackMusicDir, filename)
if _, err := os.Stat(src); os.IsNotExist(err) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "file not found"})
return
}
disabledDir := filepath.Join(fallbackMusicDir, "disabled")
if err := os.MkdirAll(disabledDir, 0o755); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create disabled directory"})
return
}
dst := filepath.Join(disabledDir, filename)
if err := os.Rename(src, dst); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to disable song"})
return
}
ctx.JSON(http.StatusOK, gin.H{"disabled": filename})
}
// EnableRadioSong moves a song back out of the disabled subdirectory.
func (store *Store) EnableRadioSong(ctx *gin.Context) {
filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return
}
src := filepath.Join(fallbackMusicDir, "disabled", filename)
if _, err := os.Stat(src); os.IsNotExist(err) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "file not found in disabled directory"})
return
}
dst := filepath.Join(fallbackMusicDir, filename)
if err := os.Rename(src, dst); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to enable song"})
return
}
ctx.JSON(http.StatusOK, gin.H{"enabled": filename})
}
// DeleteRadioSong permanently removes an enabled song. It cannot reach the
// disabled subdirectory, so a disabled song must be enabled before it can be
// deleted.
func (store *Store) DeleteRadioSong(ctx *gin.Context) {
filename := filepath.Base(ctx.Param("filename"))
if filename == "." || filename == "/" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
return
}
path := filepath.Join(fallbackMusicDir, filename)
if _, err := os.Stat(path); os.IsNotExist(err) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "file not found"})
return
}
if err := os.Remove(path); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete file"})
return
}
ctx.JSON(http.StatusOK, gin.H{"deleted": filename})
}
+135 -56
View File
@@ -2,34 +2,78 @@ package handlers
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"time"
"github.com/rwcarlsen/goexif/exif"
"adam-french.co.uk/backend/models"
"github.com/anthropics/anthropic-sdk-go"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
// the admin uploads a photo of the rowing machine display and Claude reads the
// numbers off it. The session date comes from the photo's EXIF metadata, which
// also doubles as the deduplication key.
//
// 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 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 float64 `json:"timeMinutes"`
TimeSeconds float64 `json:"timeSeconds"`
Distance float64 `json:"distance"`
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) {
var rowing []models.Rowing
// "Created_At" works because Postgres folds unquoted identifiers to lower
// case; the column is created_at.
if err := store.DB.Order("Created_At DESC").Find(&rowing).Error; err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
ctx.JSON(http.StatusOK, rowing)
}
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the
// rowing machine display, dates it from EXIF, has Claude read the time and
// distance (via the Python service), sanity-checks the result and stores a
// session.
//
// Note it is admin-gated and costs a paid API call once per request, so the
// validation below exists to catch misreadings rather than hostile input.
func (store *Store) CreateRowing(ctx *gin.Context) {
file, err := ctx.FormFile("image")
if err != nil {
@@ -44,25 +88,38 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
defer f.Close()
// Get the date taken from the EXIF data
x, err := exif.Decode(f)
// EXIF is required, not optional: it is both the session date and the
// duplicate key, so a stripped-metadata image (anything that has been
// through most messaging apps) is rejected outright.
exifData, err := exif.Decode(f)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
return
}
dateTaken, err := x.DateTime()
dateTaken, err := exifData.DateTime()
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no date found in EXIF data"})
return
}
// Seek back to start since exif.Decode advanced the cursor
// exif.Decode consumed part of the stream, so rewind before reading the
// bytes to send 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, 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
}
data, err := io.ReadAll(f)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read image"})
@@ -75,56 +132,48 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
"image/gif": true,
"image/webp": true,
}
// This is the browser's claimed type, not a sniffed one; it is passed
// straight through to the Anthropic API, so the allow-list is there to
// keep the API call well-formed rather than to police the file. 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)
// 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.`),
},
},
},
})
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to analyze image"})
// Duplicate guard: two photos of the same session share an EXIF capture
// time to the second. Checked before the Claude call so a re-upload costs
// nothing.
//
// Fails closed: only gorm.ErrRecordNotFound means "no duplicate". Any
// other error is a real database problem, and treating it as "not found"
// would both insert a duplicate and spend a paid Claude call to do it.
var existing models.Rowing
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
switch {
case err == nil:
ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"})
return
case !errors.Is(err, gorm.ErrRecordNotFound):
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
if len(message.Content) == 0 {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "empty response from Claude"})
return
}
extractedData := ExtractedRowingData{}
err = json.Unmarshal([]byte(message.Content[0].Text), &extractedData)
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse JSON response"})
log.Println(err)
// 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
}
@@ -134,15 +183,45 @@ No text, no markdown, no explanation. Just the JSON object.`),
}
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
totalDuration := time.Duration(totalSeconds * float64(time.Second))
per500m := time.Duration(totalSeconds / extractedData.Distance * 500 * float64(time.Second))
// Sanity bounds on what Claude claims to have read. A misread digit
// typically lands far outside human rowing performance, and the pace
// check catches the case where time and distance are individually
// plausible but inconsistent with each other.
const (
minDistance = 100 // metres
maxDistance = 100000 // metres
minTotalSecs = 30 // 30 seconds
maxTotalSecs = 7200 // 2 hours
minPacePer500m = 80 // ~1:20 /500m (faster than any human)
maxPacePer500m = 150 // ~2:30 /500m (slow, not important)
)
if extractedData.Distance < minDistance || extractedData.Distance > maxDistance {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "anomalous distance value"})
return
}
if totalSeconds < minTotalSecs || totalSeconds > maxTotalSecs {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "anomalous time value"})
return
}
per500m := float64(totalSeconds) / float64(extractedData.Distance) * 500.0
if per500m < minPacePer500m || per500m > maxPacePer500m {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "anomalous pace value"})
return
}
// Rough calorie estimate from distance alone: roughly 500 kcal per
// 7500 m. Not from the machine and not physiologically derived — it is a
// display figure only.
calories := float64(extractedData.Distance) / 7500.0 * 500.0
rowing := models.Rowing{
Date: dateTaken,
Time: totalDuration,
Time: totalSeconds,
TimePer500m: per500m,
Distance: extractedData.Distance,
Calories: extractedData.Distance / 7500.0 * 500.0,
Calories: calories,
}
if err := store.DB.Create(&rowing).Error; err != nil {
+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)
}
})
}
}
+84 -24
View File
@@ -2,26 +2,55 @@ package handlers
import (
"context"
"log"
"net/http"
"time"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/zmb3/spotify/v2"
)
// These REST endpoints predate the equivalent GraphQL queries in
// graph/spotify.resolvers.go and are kept for the OAuth callback (which must
// be REST, because Spotify redirects a browser to it) and for direct use.
// CompleteSpotifyAuth handles Spotify's OAuth redirect to
// GET /spotify/callback. It swaps the code for a token, saves it so the
// authorisation survives restarts, and installs the authenticated client on
// the Store — which is how Store.SpotifyClient becomes non-nil without a
// restart.
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
state := ctx.Query("state")
c := context.Background()
// code := c.Query("code")
token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
if err != nil {
ctx.String(http.StatusInternalServerError, "Couldn't get token: %v", err)
// CSRF check: the state must be a nonce this process handed out from
// StartSpotifyAuth and has not seen come back yet. Without it, anyone who
// could get the site owner's browser to hit this URL with an attacker's
// authorisation code would bind the site to the attacker's Spotify
// account. The library also compares the state to the value passed below,
// but since that value is the one just received, this check is the real
// one.
if !store.ConsumeSpotifyState(state) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid state"})
return
}
services.SaveSpotifyToken(services.SPOTIFY_TOKEN_JSON_PATH, token)
// context.Background, not the request context: the client built below
// outlives this request and would otherwise be cancelled when it ends.
c := context.Background()
// The library pulls the `code` out of the request itself and checks the
// state parameter matches the one passed here.
token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
return
}
if err := services.SaveSpotifyToken(services.SPOTIFY_TOKEN_JSON_PATH, token); err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
client := spotify.New(store.SpotifyAuth.Client(c, token))
@@ -29,12 +58,30 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "Authentication successful",
"token": token.AccessToken,
"type": token.TokenType,
"expiry": token.Expiry,
})
}
// StartSpotifyAuth backs the admin-only GET /spotify/auth. It returns the
// Spotify authorisation URL carrying a freshly minted one-shot state nonce,
// which CompleteSpotifyAuth then verifies and consumes.
//
// This exists because the state has to be per-request to be a CSRF defence,
// and the start of the flow therefore has to be a request rather than a line
// printed at start-up.
func (store *Store) StartSpotifyAuth(ctx *gin.Context) {
state, err := store.NewSpotifyState()
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
ctx.JSON(http.StatusOK, gin.H{"url": store.SpotifyAuth.AuthURL(state)})
}
// ListeningTo backs GET /spotify/listening with the currently playing track.
// A nil client means the OAuth flow has never been completed, reported here
// as a 500.
func (store *Store) ListeningTo(ctx *gin.Context) {
c := ctx.Request.Context()
@@ -45,37 +92,50 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
playing, err := store.SpotifyClient.PlayerCurrentlyPlaying(c)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
log.Println(err)
ctx.JSON(500, gin.H{"error": "failed to fetch currently playing"})
return
}
ctx.JSON(200, playing)
}
// RecentlyPlayed backs GET /spotify/recent, serving the shared one-minute
// cache. Both this endpoint and the GraphQL spotifyRecent resolver go through
// RecentlyPlayedTracks, so either one can fill the cache for the other.
func (store *Store) RecentlyPlayed(ctx *gin.Context) {
opts := spotify.RecentlyPlayedOptions{Limit: 3}
if store.RecentSongsFresh() {
ctx.JSON(200, *store.RecentSongs)
if store.SpotifyClient == nil {
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
return
}
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
played, err := store.RecentlyPlayedTracks(ctx)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
log.Println(err)
ctx.JSON(500, gin.H{"error": "failed to fetch recently played"})
return
}
ctx.JSON(200, played)
}
func (s *Store) RecentSongsFresh() bool {
if s.RecentSongs == nil {
return false
// RecentlyPlayedTracks returns the last few played tracks, from the cache when
// it is fresh and from Spotify otherwise — populating the cache in that case.
//
// This is the single fetch-and-cache path for recently-played data; the caller
// must have checked SpotifyClient is non-nil.
func (store *Store) RecentlyPlayedTracks(ctx context.Context) ([]spotify.RecentlyPlayedItem, error) {
if cached, ok := store.CachedRecentSongs(); ok {
return cached, nil
}
if len(*s.RecentSongs) == 0 {
return false
opts := spotify.RecentlyPlayedOptions{Limit: 3}
played, err := store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
if err != nil {
return nil, err
}
return time.Since(s.RecentSongsFetchedAt) < time.Minute
store.SetRecentSongs(played)
return played, nil
}
+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
}
-162
View File
@@ -1,162 +0,0 @@
package handlers
import (
"net/http"
"adam-french.co.uk/backend/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
type UserCredentials struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
func (store *Store) CreateUser(ctx *gin.Context) {
var input UserCredentials
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, err.Error())
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
user := models.User{Username: input.Username, Password: hashedPassword}
tx := store.DB.Create(&user)
if tx.Error != nil {
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
}
// Generate JWT token
tokens, err := store.Auth.GenerateJWT(&user)
if err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
ctx.SetCookie(
"access_token",
tokens.AccessToken,
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
ctx.SetCookie(
"refresh_token",
tokens.RefreshToken,
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
ctx.JSON(http.StatusOK, user)
}
func (store *Store) GetUser(ctx *gin.Context) {
userID := ctx.Param("id")
var user models.User
if err := store.DB.First(&user, userID).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
return
}
ctx.JSON(http.StatusOK, user)
}
func (store *Store) GetUsers(ctx *gin.Context) {
var users []models.User
if err := store.DB.Find(&users).Error; err != nil {
ctx.JSON(http.StatusInternalServerError, err.Error())
return
}
ctx.JSON(http.StatusOK, users)
}
func (store *Store) UpdateUser(ctx *gin.Context) {
claimsVal, ok := ctx.Get("userClaims")
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
return
}
claims, ok := claimsVal.(*jwt.MapClaims)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
return
}
userID := uint(userIDF)
var user models.User
if err := store.DB.First(&user, userID).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
return
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "will be implemented"})
}
func (store *Store) DeleteUser(ctx *gin.Context) {
claimsVal, ok := ctx.Get("userClaims")
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
return
}
claims, ok := claimsVal.(*jwt.MapClaims)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
return
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
return
}
userID := uint(userIDF)
var user models.User
if err := store.DB.First(&user, userID).Error; err != nil {
ctx.JSON(http.StatusNotFound, err.Error())
return
}
tx := store.DB.Delete(&user)
if tx.Error != nil {
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
return
}
ctx.SetCookie(
"access_token",
"",
-1,
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
ctx.SetCookie(
"refresh_token",
"",
-1,
store.Auth.Config.Endpoint,
store.Auth.Config.Domain,
true, true,
)
ctx.JSON(http.StatusOK, user)
}
+36 -2
View File
@@ -5,12 +5,46 @@ import (
"github.com/gin-gonic/gin"
)
// ConnectWebSocket upgrades GET /ws into a chat connection. The route is
// public: anyone may chat, and admin status only adds the ability to see and
// send private messages and to delete.
func (store *Store) ConnectWebSocket(ctx *gin.Context) {
// Work out admin status before upgrading: the browser sends the auth
// cookies with the upgrade request, but they are not available afterwards.
isAdmin := store.isAdminRequest(ctx)
conn, err := services.Upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
// Upgrader already wrote the HTTP error response, so just return
return
}
services.HandleWebSocket(conn)
services.HandleWebSocket(conn, isAdmin)
}
// isAdminRequest reports whether the request carries valid admin credentials.
// It prefers the access token and falls back to the refresh token plus a DB
// lookup, so an admin whose access token has just expired is still recognised.
// Both branches go through AuthenticateTokenWithClaims rather than bare
// VerifyJWT: that is what enforces the "tv" token-version claim, so a token
// revoked by logout or a password change is rejected here too. A bare
// VerifyJWT would leave /ws honouring stale tokens for their full lifetime
// while every other path rejects them.
func (store *Store) isAdminRequest(ctx *gin.Context) bool {
if accessToken, err := ctx.Cookie("access_token"); err == nil {
if _, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken); err == nil {
admin, ok := (*claims)["admin"].(bool)
return ok && admin
}
}
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
}
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
return false
}
return user.Admin
}
+291
View File
@@ -0,0 +1,291 @@
package handlers
import (
"net/http/httptest"
"strings"
"testing"
"time"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/zmb3/spotify/v2"
)
// What is deliberately NOT covered here, and why:
//
// - Every handler method (Login, Upload, the radio file movers,
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
// multipart request, the container's /backend/... directories, or a paid
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
// CI.
// - The radio upload's filename sanitisation. It is written inline in the
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
// the radio allow-list.
// --- Spotify OAuth CSRF nonces -------------------------------------------
func TestSpotifyStateSingleUse(t *testing.T) {
s := &Store{}
state, err := s.NewSpotifyState()
if err != nil {
t.Fatalf("NewSpotifyState: %v", err)
}
if !s.ConsumeSpotifyState(state) {
t.Fatal("a freshly minted state must be accepted")
}
// The whole point of the nonce: a replayed callback must not authenticate
// a second time.
if s.ConsumeSpotifyState(state) {
t.Fatal("a consumed state must not be accepted again")
}
}
func TestConsumeSpotifyStateRejections(t *testing.T) {
cases := []struct {
name string
// setup returns the state string to present to ConsumeSpotifyState.
setup func(s *Store) string
want bool
}{
{
name: "empty state is rejected before the map is even consulted",
setup: func(*Store) string { return "" },
want: false,
},
{
name: "a state this process never minted is rejected",
setup: func(*Store) string { return "deadbeef" },
want: false,
},
{
name: "a state minted within the TTL is accepted",
setup: func(s *Store) string {
st, _ := s.NewSpotifyState()
return st
},
want: true,
},
{
name: "a state older than the TTL is rejected",
setup: func(s *Store) string {
st, _ := s.NewSpotifyState()
// Backdating beats sleeping for ten minutes; the map is in the
// same package so the creation stamp is writable here.
s.spotifyStates[st] = time.Now().Add(-spotifyStateTTL - time.Second)
return st
},
want: false,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
state := c.setup(s)
if got := s.ConsumeSpotifyState(state); got != c.want {
t.Fatalf("ConsumeSpotifyState = %v, want %v", got, c.want)
}
})
}
}
// An expired nonce must also be removed, not merely refused: otherwise the map
// grows without bound for any flow that is started and abandoned.
func TestNewSpotifyStatePrunesExpired(t *testing.T) {
s := &Store{}
stale, _ := s.NewSpotifyState()
s.spotifyStates[stale] = time.Now().Add(-spotifyStateTTL - time.Second)
if _, err := s.NewSpotifyState(); err != nil {
t.Fatalf("NewSpotifyState: %v", err)
}
if _, ok := s.spotifyStates[stale]; ok {
t.Fatal("minting a new state should have pruned the expired one")
}
}
// --- Cache TTL rules ------------------------------------------------------
// Each cache treats "empty" as stale, which is deliberate (an empty listening
// history or games list is re-fetched rather than cached). These tables pin
// that down so it cannot be "fixed" into caching emptiness by accident.
func TestCachedRecentSongsFreshness(t *testing.T) {
song := []spotify.RecentlyPlayedItem{{}}
cases := []struct {
name string
setup func(s *Store)
wantOK bool
}{
{"never fetched", func(*Store) {}, false},
{"fetched but empty counts as stale", func(s *Store) {
s.SetRecentSongs([]spotify.RecentlyPlayedItem{})
}, false},
{"just fetched", func(s *Store) { s.SetRecentSongs(song) }, true},
{"inside the one-minute TTL", func(s *Store) {
s.SetRecentSongs(song)
s.RecentSongsFetchedAt = time.Now().Add(-59 * time.Second)
}, true},
{"past the one-minute TTL", func(s *Store) {
s.SetRecentSongs(song)
s.RecentSongsFetchedAt = time.Now().Add(-time.Minute - time.Second)
}, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
c.setup(s)
if _, ok := s.CachedRecentSongs(); ok != c.wantOK {
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
}
})
}
}
func TestCachedGiteaFeedFreshness(t *testing.T) {
feed := &services.GiteaFeedResponse{}
cases := []struct {
name string
setup func(s *Store)
wantOK bool
}{
{"never fetched", func(*Store) {}, false},
{"just fetched", func(s *Store) { s.SetGiteaFeed(feed) }, true},
{"past the one-minute TTL", func(s *Store) {
s.SetGiteaFeed(feed)
s.GiteaFeedFetchedAt = time.Now().Add(-time.Minute - time.Second)
}, false},
// Unlike the songs cache, a nil feed is the only "empty" here, and a
// nil stored feed must never read as fresh.
{"explicitly cached nil is never fresh", func(s *Store) { s.SetGiteaFeed(nil) }, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
c.setup(s)
if _, ok := s.CachedGiteaFeed(); ok != c.wantOK {
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
}
})
}
}
func TestCachedSteamFreshness(t *testing.T) {
games := []services.SteamRecentGame{{}}
cases := []struct {
name string
setup func(s *Store)
wantOK bool
wantOnline bool
}{
{"never fetched", func(*Store) {}, false, false},
{"just fetched, online flag preserved", func(s *Store) { s.SetSteam(games, true) }, true, true},
{"just fetched, offline", func(s *Store) { s.SetSteam(games, false) }, true, false},
{"nil games list counts as stale even when online", func(s *Store) { s.SetSteam(nil, true) }, false, false},
{"past the five-minute TTL", func(s *Store) {
s.SetSteam(games, true)
s.SteamFetchedAt = time.Now().Add(-5*time.Minute - time.Second)
}, false, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &Store{}
c.setup(s)
_, online, ok := s.CachedSteam()
if ok != c.wantOK {
t.Fatalf("fresh = %v, want %v", ok, c.wantOK)
}
if online != c.wantOnline {
t.Fatalf("online = %v, want %v", online, c.wantOnline)
}
})
}
}
// --- Upload trust boundary ------------------------------------------------
// requestIsAdmin gates private (admin-only) attachment uploads, so every way
// the claim can be absent or the wrong shape must read as "not admin". No DB
// or network is involved: it only inspects the Gin context.
func TestRequestIsAdmin(t *testing.T) {
gin.SetMode(gin.TestMode)
claims := func(m jwt.MapClaims) any { return &m }
cases := []struct {
name string
// set is nil when nothing should be put in the context at all.
set any
want bool
}{
{"no claims in context at all", nil, false},
{"claims of the wrong type are not trusted", "not-claims", false},
// A by-value jwt.MapClaims is not what AuthMiddlewear stores; accepting
// it would mean the type assertion had been loosened.
{"claims stored by value rather than by pointer", jwt.MapClaims{"admin": true}, false},
{"pre-admin-claim token has no admin key", claims(jwt.MapClaims{"id": 1.0}), false},
{"admin false", claims(jwt.MapClaims{"admin": false}), false},
{"admin as a string is not a truthy admin", claims(jwt.MapClaims{"admin": "true"}), false},
{"admin true", claims(jwt.MapClaims{"admin": true}), true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
if c.set != nil {
ctx.Set("userClaims", c.set)
}
if got := requestIsAdmin(ctx); got != c.want {
t.Fatalf("requestIsAdmin = %v, want %v", got, c.want)
}
})
}
}
// --- Permission gate ------------------------------------------------------
// 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())
}
}
}
// 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)
}
}
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)
}
}
}
+201 -2
View File
@@ -1,23 +1,222 @@
package handlers
import (
"crypto/rand"
"encoding/hex"
"log"
"sync"
"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"
)
// Package handlers holds the REST endpoints and the shared Store that every
// request handler — and, through graph.Resolver, every GraphQL resolver —
// depends on.
//
// Store is the backend's dependency container: it is built once in main and
// passed around by pointer, so the caches on it are shared process-wide.
//
// Concurrency note: the third-party caches below are read and written by
// concurrent requests, so every access goes through cacheMu and the accessor
// methods at the bottom of this file. Do not touch the cache fields directly
// — an unsynchronised read of one of them is a data race, not merely a stale
// value.
type Store struct {
DB *gorm.DB
SpotifyAuth *spotifyauth.Authenticator
SpotifyClient *spotify.Client
ClaudeClient *anthropic.Client
Auth *services.Auth
Notes *services.Notes
LoginLimiter *services.RateLimiter
// 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
// mean "never fetched" distinctly from "fetched, empty".
// cacheMu guards every cache field below (and only those). One mutex for
// all of them keeps the locking obvious; the critical sections are just
// field copies, never network calls, so there is no contention worth
// splitting it up for.
cacheMu sync.RWMutex
RecentSongs *[]spotify.RecentlyPlayedItem
RecentSongsFetchedAt time.Time
// Cached latest Gitea activity entry, 1 minute TTL.
GiteaHost string
GiteaPort string
GiteaFeed *services.GiteaFeedResponse
GiteaFeedFetchedAt time.Time
// Cached Steam status and recent games, 5 minute TTL.
SteamAPIKey string
SteamID string
SteamRecentGames []services.SteamRecentGame
SteamOnline bool
SteamFetchedAt time.Time
// spotifyStates holds the one-shot CSRF nonces handed out by
// GET /spotify/auth, mapped to their creation time. In-memory is enough:
// there is one backend instance, and losing them on restart only means
// restarting an OAuth flow that takes seconds.
spotifyStatesMu sync.Mutex
spotifyStates map[string]time.Time
// spotifyNilLoggedAt rate-limits the "Spotify not authenticated" log line:
// every page visit hits spotifyRecent, so an unauthenticated backend would
// otherwise write a flood of identical lines. nil means "recently logged".
spotifyNilLoggedMu sync.Mutex
spotifyNilLoggedAt time.Time
}
// spotifyStateTTL is how long an unused Spotify OAuth nonce stays valid. Long
// enough to log in at Spotify and approve the scopes, short enough that a
// leaked authorisation URL is not reusable later.
const spotifyStateTTL = 10 * time.Minute
// NewSpotifyState mints a one-shot CSRF nonce for the Spotify authorisation
// URL and remembers it. Expired entries are pruned on the way through, which
// is the only cleanup there is — the map is otherwise unbounded, and only an
// admin can add to it.
func (s *Store) NewSpotifyState() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
state := hex.EncodeToString(b)
s.spotifyStatesMu.Lock()
defer s.spotifyStatesMu.Unlock()
if s.spotifyStates == nil {
s.spotifyStates = make(map[string]time.Time)
}
for k, created := range s.spotifyStates {
if time.Since(created) > spotifyStateTTL {
delete(s.spotifyStates, k)
}
}
s.spotifyStates[state] = time.Now()
return state, nil
}
// ConsumeSpotifyState checks a nonce returned by Spotify's redirect and
// removes it, so a replayed callback fails. An unknown or expired nonce
// returns false, which the callback must treat as a rejected request.
func (s *Store) ConsumeSpotifyState(state string) bool {
if state == "" {
return false
}
s.spotifyStatesMu.Lock()
defer s.spotifyStatesMu.Unlock()
created, ok := s.spotifyStates[state]
if !ok {
return false
}
delete(s.spotifyStates, state)
return time.Since(created) <= spotifyStateTTL
}
// The cache accessors below are the only supported way to touch the cache
// fields. Each "Cached..." method returns the value plus a bool that is true
// only when the entry is present and inside its TTL; each "Set..." method
// stores a value and stamps it.
// LogSpotifyUnauthenticated logs that the Spotify OAuth flow has never been
// completed (or a stored token stopped working), with a where hint. It is
// rate-limited to one line per hour — see spotifyNilLoggedAt — because
// spotifyRecent is hit by every home-page visit.
func (s *Store) LogSpotifyUnauthenticated(where string) {
s.spotifyNilLoggedMu.Lock()
defer s.spotifyNilLoggedMu.Unlock()
if time.Since(s.spotifyNilLoggedAt) < time.Hour {
return
}
s.spotifyNilLoggedAt = time.Now()
log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where)
}
// CachedRecentSongs returns the cached Spotify recently-played list if it is
// within its one-minute TTL. An empty list counts as stale, so an empty
// listening history is re-fetched every time (unchanged behaviour).
func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
if s.RecentSongs == nil || len(*s.RecentSongs) == 0 {
return nil, false
}
if time.Since(s.RecentSongsFetchedAt) >= time.Minute {
return nil, false
}
return *s.RecentSongs, true
}
// SetRecentSongs replaces the cached recently-played list.
func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
s.RecentSongs = &songs
s.RecentSongsFetchedAt = time.Now()
}
// CachedGiteaFeed returns the cached Gitea activity entry if it is within its
// one-minute TTL. A nil cache is never fresh, so the first request always hits
// Gitea.
func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
if s.GiteaFeed == nil || time.Since(s.GiteaFeedFetchedAt) >= time.Minute {
return nil, false
}
return s.GiteaFeed, true
}
// SetGiteaFeed replaces the cached Gitea feed entry.
func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
s.GiteaFeed = feed
s.GiteaFeedFetchedAt = time.Now()
}
// CachedSteam returns the cached Steam recent games and online flag if they
// are within their five-minute TTL. As before, freshness is judged only on the
// games list: if Steam legitimately returns no recent games the cache never
// registers as fresh and every request re-queries the API.
func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) {
s.cacheMu.RLock()
defer s.cacheMu.RUnlock()
if s.SteamRecentGames == nil || time.Since(s.SteamFetchedAt) >= 5*time.Minute {
return nil, false, false
}
return s.SteamRecentGames, s.SteamOnline, true
}
// SetSteam replaces the cached Steam data.
func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) {
s.cacheMu.Lock()
defer s.cacheMu.Unlock()
s.SteamRecentGames = games
s.SteamOnline = online
s.SteamFetchedAt = time.Now()
}
+170 -37
View File
@@ -7,23 +7,53 @@ import (
"os"
"time"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/lru"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gin-gonic/gin"
"github.com/vektah/gqlparser/v2/ast"
"adam-french.co.uk/backend/graph"
"adam-french.co.uk/backend/handlers"
"adam-french.co.uk/backend/services"
)
// Command backend is the Go API for adam-french.co.uk.
//
// main is the single place everything is wired together: it reads every
// setting from the environment, builds the services, packs them into one
// handlers.Store, and registers the routes. There are three route groups —
// open, `protected` (valid access token) and `admin` (token with admin=true)
// — plus the GraphQL endpoint, which 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).
logsDir := "/backend/logs"
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
panic(err)
}
gin.DefaultWriter = io.MultiWriter(os.Stdout, logFile)
r := gin.Default()
if os.Getenv("DEV_MODE") != "true" {
gin.SetMode(gin.ReleaseMode)
}
r := gin.New()
// Custom traffic formatter (services/traffic_log.go) instead of gin's
// default: quiets heartbeat subrequests, surfaces external visitors and
// server errors. Same writer pair as above.
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
r.Use(gin.Recovery())
// Only the Docker network nginx sits on may set X-Forwarded-For. Without
// this pin any client could spoof its IP and defeat the per-IP login rate
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
if err != nil {
panic(err)
@@ -39,24 +69,37 @@ func main() {
if err != nil {
log.Fatal(err)
}
// Dev only; the seeder creates an admin with a known password.
if os.Getenv("SEED_DB") == "true" {
services.SeedDatabase(db)
}
// DOMAIN does double duty: the WebSocket origin allow-list and the auth
// cookie domain.
domainName := os.Getenv("DOMAIN")
// The chat hub is a package-level singleton rather than a value on the
// Store, so it is initialised rather than constructed.
services.InitWebSocket(db, domainName)
// SPOTIFY
spotifyAuthState := os.Getenv("SPOTIFY_AUTH_STATE")
// No SPOTIFY_AUTH_STATE: the OAuth `state` is now a one-shot nonce minted
// per authorisation request, so there is nothing to configure.
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET")
spotifyConfig := services.SpotifyConfig{AuthState: spotifyAuthState, RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
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")
domainName := os.Getenv("DOMAIN")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
accessTokenLifetime := 24 * time.Hour
// Long-lived by design: this is a personal site with a single admin, and
// there is no server-side revocation, so a leaked token stays valid for
// its whole lifetime.
accessTokenLifetime := 7 * 24 * time.Hour
refreshTokenLifetime := 365 * 24 * time.Hour
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
auth := services.InitAuth(&authConfig)
@@ -65,53 +108,138 @@ func main() {
notesConfig := services.NotesConfig{Dir: notesDir}
notes := services.InitNotes(&notesConfig)
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes}
giteaHost := os.Getenv("GITEA_HOST")
giteaPort := os.Getenv("GITEA_PORT")
steamAPIKey := os.Getenv("STEAM_API_KEY")
steamID := os.Getenv("STEAM_ID")
// 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"
}
pythonPort := os.Getenv("PYTHON_PORT")
if pythonPort == "" {
pythonPort = "8000"
}
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, 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.
//
// Paths below have no /api prefix: nginx strips it before proxying.
protected := r.Group("/", store.AuthMiddlewear)
// FAVORITES
r.GET("/favorites", store.GetFavorites)
protected.POST("/favorites", store.CreateFavorite)
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
// ROWING
r.GET("/rowing", store.GetRowing)
protected.POST("/rowing", store.CreateRowing)
// ACTIVITIES
r.GET("/activity", store.GetActivity)
protected.POST("/activity", store.CreateActivity)
// POSTS
r.GET("/posts", store.GetPosts)
protected.POST("/posts", store.CreatePost)
r.GET("/posts/:id", store.GetPost)
protected.PUT("/posts/:id", store.UpdatePost)
protected.DELETE("/posts/:id", store.DeletePost)
// USERS
r.GET("/user/:id", store.GetUser)
protected.PUT("/user/:id", store.UpdateUser)
protected.DELETE("/user/:id", store.DeleteUser)
r.GET("/user", store.GetUsers)
r.POST("/user", store.CreateUser)
admin.POST("/rowing", store.CreateRowing)
// AUTH
r.POST("/auth/login", store.Login)
r.POST("/auth/refresh", store.RefreshToken)
r.GET("/auth/check", store.CheckToken)
r.POST("/auth/logout", store.Logout)
r.GET("/auth/validate-admin", store.ValidateAdmin)
r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY
// The callback must be open — Spotify redirects a logged-out browser to
// it — and is protected by the state nonce instead. Starting the flow is
// admin-only, since that is what mints the nonce.
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
admin.GET("/spotify/auth", store.StartSpotifyAuth)
r.GET("/spotify/listening", store.ListeningTo)
r.GET("/spotify/recent", store.RecentlyPlayed)
// r.POST("/spotify", store.SendSong)
// RADIO
admin.POST("/radio/upload", store.UploadRadioSong)
admin.GET("/radio/songs", store.ListRadioSongs)
admin.DELETE("/radio/songs/:filename", store.DeleteRadioSong)
admin.PATCH("/radio/songs/:filename/disable", store.DisableRadioSong)
admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong)
// MESSAGES
// /ws is deliberately outside the protected group: chat is public, and
// the handler checks the cookies itself to decide admin privileges.
r.GET("/ws", store.ConnectWebSocket)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
r.GET("/notes/*path", store.GetNoteFile)
admin.GET("/notes/*path", store.GetNoteFile)
// GRAPHQL
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
// so the transports and extensions below are explicit.
//
// Note the whole API is one POST route with no middleware guard.
// Authorisation 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},
Directives: graph.Directives(),
}))
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
gqlSrv.AddTransport(transport.Options{})
gqlSrv.AddTransport(transport.POST{})
gqlSrv.AddTransport(transport.MultipartForm{})
// Caches parsed query documents so repeated queries skip parsing.
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
// Rejects queries above a computed complexity, the standard defence
// against a deeply nested query being used to exhaust the server.
gqlSrv.Use(extension.FixedComplexityLimit(200))
// Introspection and the playground are both off unless DEV_MODE *and*
// their own flag are set, so production does not publish its schema.
devMode := os.Getenv("DEV_MODE") == "true"
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
gqlSrv.Use(extension.Introspection{})
}
// AuthContextMiddleware copies the Gin context and any verified claims
// into the request context, which is what resolvers read. The closure is
// needed because gqlgen speaks net/http, not gin.
r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) {
gqlSrv.ServeHTTP(c.Writer, c.Request)
})
if devMode && os.Getenv("GQL_PLAYGROUND") == "true" {
r.GET("/graphql", func(c *gin.Context) {
playground.Handler("GraphQL Playground", "/graphql").ServeHTTP(c.Writer, c.Request)
})
}
// HELLO WORLD
r.GET("/", func(c *gin.Context) {
@@ -119,5 +247,10 @@ func main() {
})
port := os.Getenv("BACKEND_PORT")
r.Run(fmt.Sprintf(":%s", 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
// and reports the container as having succeeded.
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
log.Fatalf("http server stopped: %v", err)
}
}
+257 -9
View File
@@ -6,16 +6,64 @@ import (
"gorm.io/gorm"
)
// Package models holds the GORM entities, which are also the GraphQL object
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
// graph/model/ only contains generated input and payload types. That means
// these structs carry three sets of contracts at once — database columns,
// JSON field names for the REST endpoints, and the shape resolvers return —
// and renaming a field or changing a tag breaks at least one of them.
//
// Conventions across every model:
// - There are no migration files; services.migrateDatabase runs AutoMigrate,
// so a model must be listed there to get a table.
// - A gorm.DeletedAt field means soft delete: Delete sets deleted_at, and
// every subsequent query silently filters those rows out. Rows are never
// actually removed, and a uniqueIndex still sees deleted rows, so a
// soft-deleted username cannot be reused.
// - IDs are uint 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.
type User struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Username string `gorm:"uniqueIndex" json:"username"`
Password []byte `json:"-"`
Admin bool `json:"admin"`
// bcrypt hash, never the plaintext. `json:"-"` keeps it out of REST
// responses, and gqlgen.yml marks the GraphQL password field
// resolver:false so it is not exposed there either.
Password []byte `json:"-"`
// Admin gates almost every mutation. It is copied into the access token,
// so a change here only takes effect on the user's next token refresh.
Admin bool `json:"admin"`
// 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
// incrementing this column revokes every outstanding token for the user
// at once (logout, password change). It is the only server-side
// revocation mechanism there is.
//
// Pre-migration rows: AutoMigrate adds the column with DEFAULT 1, but a
// row that somehow ends up at 0 is normalised to 1 by
// services.tokenVersionOf, as is a token minted before the "tv" claim
// existed. So the migration invalidates nobody's existing session, and
// the first bump moves a user to 2 and invalidates everything older.
TokenVersion uint `gorm:"not null;default:1" json:"-"`
}
// Post is a blog entry. Author is loaded with Preload("Author") by the post
// resolvers; without that preload it is nil rather than an error.
type Post struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -27,15 +75,27 @@ type Post struct {
Content string `json:"content"`
}
// Message is one chat message. The table is capped at 50 rows by the
// WebSocket hub, which soft-deletes older ones on every insert.
//
// Two things to watch: Content is exposed as "text", not "content"; and
// AuthorID is a per-process connection counter from the WebSocket hub, NOT a
// User ID — chat is pseudonymous and the number is meaningless across
// restarts.
type Message struct {
ID uint `gorm:"primarykey" json:"id"`
Content string `json:"text"`
AuthorID uint `json:"-"`
Author *User `gorm:"foreignKey:AuthorID" json:"author"`
ID uint `gorm:"primarykey" json:"id"`
Content string `json:"text"`
AuthorID uint `json:"authorId"`
FileURL string `json:"fileUrl,omitempty"`
// Private messages are visible only to admins; both the WebSocket
// broadcast and the messages query filter on it.
Private bool `gorm:"not null;default:false" json:"private"`
CreatedAt time.Time `json:"createdAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
}
// Activity is a "currently doing" entry on the home page. Structurally
// identical to Favorite but kept separate so the two lists can diverge.
type Activity struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -46,6 +106,7 @@ type Activity struct {
Link *string `json:"link"`
}
// Favorite is a "currently enjoying" entry on the home page.
type Favorite struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
@@ -56,13 +117,200 @@ type Favorite struct {
Link *string `json:"link"`
}
// Rowing is one rowing machine session, created by uploading a photo of the
// display (see handlers.CreateRowing).
//
// Date is the photo's EXIF capture time and acts as the deduplication key —
// it is not the row's creation time. Time is total seconds; Distance is
// metres; TimePer500m is seconds and derived from the other two; Calories is
// an estimate computed from distance, not read off the machine.
type Rowing struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Date time.Time `json:"date"`
Time time.Duration `json:"time"`
TimePer500m time.Duration `json:"timePer500m"`
Distance float64 `json:"distance"`
Time uint64 `json:"time"`
Distance uint64 `json:"distance"`
TimePer500m float64 `json:"timePer500m"`
Calories float64 `json:"calories"`
}
// Bookmark is a link on the bookmarks page, grouped by Category.
type Bookmark struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Category string `gorm:"not null" json:"category"`
Name string `gorm:"not null" json:"name"`
Link string `gorm:"not null" json:"link"`
}
// Place is an entry on the places-to-go list. Creating or editing one needs
// only a signed-in user, not an admin — the one exception to the
// admin-writes-everything rule.
type Place struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Title string `gorm:"not null" json:"title"`
Location *string `json:"location"`
Notes *string `json:"notes"`
ImageURL *string `json:"imageUrl"`
Category *string `json:"category"`
Cost *string `json:"cost"`
Priority int `gorm:"default:0" json:"priority"`
Done bool `gorm:"default:false" json:"done"`
}
// 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"`
// 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"`
}

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