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
201 changed files with 22148 additions and 5134 deletions
+4
View File
@@ -32,3 +32,7 @@ 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.
+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
+127 -20
View File
@@ -15,18 +15,15 @@
#
# HOW TO USE
# cp .env.example .env then fill in every value.
# Distribute to the Raspberry Pi with ./sync-secrets.sh (newer file wins in
# either direction — see that script's header before editing on both hosts).
# On the Pi, keys and settings can also be changed from the admin panel's
# Environment tab, which rewrites this file in place (previous version kept
# as .env.bak) and restarts what reads the change. See "Editing from the
# admin panel" in DEPLOYMENT.md.
# 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 backend/services/env_registry.json as well. That file decides
# whether the admin panel shows it, whether it is editable there, and which
# services are restarted when it changes; a backend test fails if the two
# lists differ.
# 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,
@@ -37,11 +34,12 @@
# =============================================================================
# --- Postgres ----------------------------------------------------------------
# One instance, three databases: POSTGRES_DB for the Go backend,
# POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker (with its
# own role). Only POSTGRES_DB is auto-created on first init; the other two must
# be created by hand on a fresh volume (the job tracker's README has the
# commands).
# 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=
@@ -51,6 +49,9 @@ 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.
@@ -63,6 +64,10 @@ GITEA_INTERNAL_TOKEN=
GITEA_LFS_JWT_SECRET=
GITEA_OAUTH2_JWT_SECRET=
POSTGRES_GITEA_DB=gitea
# The host's Tailscale MagicDNS name (e.g. stpvm.tailf20278.ts.net), shown in
# Gitea's SSH clone URLs. Not the public domain: 2222 is reachable only over
# the tailnet. Becomes Gitea's SSH_DOMAIN and DOMAIN. Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
@@ -186,14 +191,28 @@ LIQUIDSOAP_HARBOR_PORT=8001
DOMAIN=
EMAIL=
# --- Cloudflare Tunnel -------------------------------------------------------
# Token of the remotely managed tunnel the `cloudflared` container runs
# (Zero Trust -> Networks -> Tunnels -> your tunnel -> the `--token` value in
# the install command). Hostnames and origin settings are configured in the
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
# the container restarting with an error and the site reachable directly.
CLOUDFLARE_TUNNEL_TOKEN=
# Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API
# Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the
# certificate renews without any inbound port, so the router's 80/443
# forwards can close. Blank falls back to HTTP-01 on port 80.
CLOUDFLARE_DNS_API_TOKEN=
# --- Third-party API keys (backend) ------------------------------------------
# CLAUDE_API_KEY is used by the python service, which makes every Claude call
# in the stack: the rowing photo reader, the job posting reader and the email
# pipeline's classifier. The backend no longer calls Claude itself.
# CLAUDE_API_KEY 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. Editable on the admin panel's
# Environment tab, which restarts the python service to apply it.
# (the default when blank) or claude-opus-5-5. Recreate the python service
# to apply a change.
CLAUDE_MODEL=
STEAM_API_KEY=
STEAM_ID=
@@ -213,5 +232,93 @@ PYTHON_PORT=8000
# `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=
+5 -9
View File
@@ -29,7 +29,7 @@
#
# NOT TESTED HERE: THE VUE BUILD
# Deliberately skipped. `docker compose up --build` in the deploy job
# already runs the full frontend build (wasm-pack + vite) while building the
# 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
@@ -87,9 +87,7 @@ jobs:
test -f "$SRC/python/requirements-dev.txt"
echo "Exported $SHA ($REF) to $SRC"
# The whole repo is mounted, not just backend/, because
# services/env_manager_test.go reads ../../.env.example to check
# it against env_registry.json. Read-only: tests write only to
# 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.
@@ -170,12 +168,10 @@ jobs:
- name: Run docker compose up
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
COMPOSE_BAKE: "false"
# The lock is shared with env-apply/apply.py, so a deploy and a
# .env change made from the admin panel cannot run compose at
# the same time.
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
# The lock is shared with maintenance.yaml, so a deploy and the
# weekly rebuild cannot run compose at the same time.
run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker resources
run: docker image prune -f
+15 -18
View File
@@ -2,7 +2,10 @@ name: Weekly Maintenance
on:
schedule:
- cron: "0 1 * * 0"
# 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and
# every container, so it runs when nobody is likely to be mid-edit;
# 01:00 kept catching late-night SilverBullet saves.
- cron: "0 5 * * 0"
workflow_dispatch:
jobs:
@@ -21,28 +24,22 @@ jobs:
- name: Autoremove obsolete packages
run: sudo apt-get -y autoremove --purge
# Both compose steps below take env-apply/run/lock, the same flock
# deploy.yaml and env-apply/apply.py hold while they run compose.
# Without it this weekly job could recreate containers at the same
# moment a .env edit from the admin panel is being applied (or a
# deploy is mid-build), and two `compose up`s racing over the same
# project can each recreate a container the other just started,
# ending with services built against a half-written .env. 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 an admin-panel change from waiting behind a long pull.
# Both compose steps below take .compose.lock, the same flock
# deploy.yaml holds while it runs compose. Without it this weekly
# job could recreate containers while a deploy is mid-build, and
# two `compose up`s racing over the same project can each recreate
# a container the other just started. flock blocks until the other
# holder finishes, so the job waits rather than fails. The lock is
# taken per step, not across both: nothing needs pull and up to be
# atomic, and holding it for less time keeps a deploy from waiting
# behind a long pull.
- name: Pull latest base images
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
run: flock env-apply/run/lock docker compose pull
run: flock .compose.lock docker compose pull
- name: Rebuild and restart containers
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker images
run: docker image prune -af
+71
View File
@@ -0,0 +1,71 @@
# =============================================================================
# renovate.yaml — weekly dependency-update PRs, opened against this repo.
#
# Renovate stands in for Dependabot, which does not exist outside GitHub. What
# it updates is configured in /renovate.json5; this file is only how it runs.
#
# HOW IT RUNS
# The same host-mode act_runner as deploy.yaml, so (as there) nothing but
# git and docker is assumed on the host: Renovate runs from its own image.
# --network host lets the container reach Gitea on localhost:3000, the port
# the runner itself registers against, so this keeps working while nginx or
# the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same reason:
# without it Renovate clones from the URL Gitea advertises, which is
# ROOT_URL — the public https://…/gitea/ path.
#
# WHAT HAPPENS AFTER
# Each update is pushed as a renovate/* branch, which triggers deploy.yaml's
# `test` job like any other push (and never its `deploy` job, which is
# main-only). Nothing is merged automatically: merging is deploying.
# Renovate also keeps a "Dependency Dashboard" issue open listing everything
# pending; ticking a box there is picked up on the next run, so run this
# workflow by hand (workflow_dispatch) to act on it sooner.
#
# THE TOKEN
# RENOVATE_TOKEN is a repo Actions secret: a Gitea access token for the
# account the PRs come from (a dedicated `renovate` user with write access
# to this repo, ideally), scopes read:user, read:organization,
# write:repository, write:issue.
# RENOVATE_GITHUB_COM_TOKEN is optional: any github.com token with no
# scopes. Without it Renovate is rate-limited by GitHub and leaves release
# notes out of the PRs. (Gitea refuses secret names starting GITHUB_, hence
# the prefix.) Both reach the container as `-e NAME` with no value, so they
# are copied from this step's env and never appear in the process list.
#
# The renovate/renovate:44 tag floats within the major (--pull always picks
# up the newest 44.x each week); Renovate itself proposes the next major via
# the regex manager in renovate.json5.
# =============================================================================
name: Renovate
on:
schedule:
# 04:00 UTC Monday: clear of the Sunday 05:00 maintenance rebuild, and
# done before the working week so the PRs are waiting.
- cron: "0 4 * * 1"
workflow_dispatch:
jobs:
renovate:
runs-on: self-hosted
steps:
- name: Run Renovate
shell: bash
env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
GITHUB_COM_TOKEN: ${{ secrets.RENOVATE_GITHUB_COM_TOKEN }}
run: |
set -eu
if [ -z "$RENOVATE_TOKEN" ]; then
echo "The RENOVATE_TOKEN Actions secret is not set (repo Settings -> Actions -> Secrets)."
exit 1
fi
docker run --rm --pull always --network host \
-e RENOVATE_PLATFORM=gitea \
-e RENOVATE_ENDPOINT=http://localhost:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/web_server \
-e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \
renovate/renovate:44
+8 -10
View File
@@ -1,15 +1,16 @@
icecast2/fallback_music/*
.claude/
!icecast2/fallback_music/.gitkeep
certbot/conf
certbot/www
backend/token/
jobs-data/
usaco-data/
.env
.env.bak
# Admin panel -> host hand-off (request and status files, holds secrets)
env-apply/run/*
!env-apply/run/.gitkeep
# flock taken by the deploy and maintenance workflows around docker compose
.compose.lock
gitea/data/*
gitea/config/app.ini
@@ -19,9 +20,6 @@ gitea-runner/.runner
gitea-runner/act_runner
gitea-runner/nohup.out
# Rust build artifacts
**/target/
# Python bytecode
__pycache__/
*.pyc
@@ -30,9 +28,6 @@ __pycache__/
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
/.venv/
# Generated WASM output
vue/src/wasm/
# Logs
logs
*.log
@@ -74,7 +69,6 @@ __screenshots__/
.deploy
*.xcf
sync-secrets.sh
# Local-only outstanding-work notes, deliberately not published
TODO-NEXT.md
@@ -82,3 +76,7 @@ TODO-NEXT.md
# SilverBullet git deploy key (key material only; the README stays)
silverbullet/ssh/*
!silverbullet/ssh/README.md
# Dev notes vault (OBSIDIAN_DIR in .env.dev); only the README is tracked
dev/notes/*
!dev/notes/README.md
.gstack/
+18 -13
View File
@@ -10,15 +10,16 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
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.
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it.
### Full stack (dev mode, HTTP only)
```
cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
### Full stack (production, HTTPS)
@@ -40,7 +41,7 @@ Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets defaul
cd vue && npm run build
```
`npm run build` compiles the Rust crate first and needs `wasm-pack`. `npm run build:js` (plain `vite build`) is the check to use when only the JS changed and `src/wasm/` already exists.
`npm run build` is a plain `vite build`.
### Regenerate GraphQL (after editing schema files)
@@ -52,17 +53,19 @@ This regenerates `graph/generated.go` and `graph/model/models_gen.go`. Resolver
## Architecture
Dockerized multi-service personal website self-hosted on a Raspberry Pi.
Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubuntu VM; formerly a Raspberry Pi).
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode).
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **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`), chosen on the admin panel's Environment tab; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
**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 in `env_registry.json` with `services: ["jobs"]`.
**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`.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks.
**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
@@ -73,16 +76,17 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
- `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)
- `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`), the `.env` registry (`env_manager.go`), DB seeding. There is no Claude client in Go any more
- `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/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places. `createCrudStore.js` is the factory behind places; `createMirrorStore.js` is the one behind the home-page slices
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines)
- `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`.
@@ -92,8 +96,9 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
- **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 tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it); a variable the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, which a second test checks against the registry, with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`.
- **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.
@@ -112,4 +117,4 @@ Each area has its own README with the detail that doesn't belong here:
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
- **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating.
- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead — e.g. `views/unused/CoverLetters.vue` is actually live on `/cv`.
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof.
+351 -137
View File
@@ -4,15 +4,19 @@ How this site is put together and how to operate it. Application code is
documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only
— compose, nginx, TLS, the runner, and the runbook.
Everything runs on a single Raspberry Pi, as Docker containers on one bridge
Everything runs on a single host, `stpvm` (an x86-64 Ubuntu VM on Proxmox,
reached over Tailscale as `stpvm.tailf20278.ts.net`; until 2026-10-15 it was
the Raspberry Pi `stppi`), as Docker containers on one bridge
network, behind one nginx.
---
## 1. Service topology
Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
3000/2222, and the liquidsoap harbor port. Everything else is internal.
Only three things are reachable from outside the host: nginx on 80/443, Gitea on
3000/2222, and the liquidsoap harbor port. Everything else is internal. Web
traffic can also come in through the Cloudflare tunnel (`cloudflared`), which
dials out and publishes no port; see "Cloudflare Tunnel" in §3.
```
internet
@@ -47,20 +51,28 @@ backend icecast2 gitea sb sb-pub python | |
### 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 the app itself) | 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 |
| 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
@@ -78,19 +90,33 @@ in one step — never change one without the other.**
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
backend down (502s until it appears) instead of refusing to start.
- **Admin gate.** `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
SPA login. None of these services has any auth of its own at that path.
- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
branch views stay public) are
protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure
redirects to the SPA login. Most of these services have no auth of their own at that path; the
job and activity trackers also check the session themselves. Their carve-outs, which a session
cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps:
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`.
- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead, which also lets in a
non-admin account granted `receipt` in the admin panel's Manage Users tab. Not signed in
redirects to the login; signed in without the grant redirects to `/no-access`. To let a
friend print: create their user (admin panel → User), then tick "Receipt printer" for them
under Manage Users. Revoking is the same tick, and applies on their next request.
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of
nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
file *list*; direct `/.fs/` fetches and server-rendered page URLs still serve
file _list_; direct `/.fs/` fetches and server-rendered page URLs still serve
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the
comment above `location /notes/` in `nginx_routes.conf.template`.
- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads`
volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so
user-supplied files cannot execute anything on our origin.
- **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.
---
@@ -105,16 +131,16 @@ docker compose up --build
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
- renders `nginx.conf.template` if the cert is there, else
`nginx_setup.conf.template`;
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
nginx either way.
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
- renders `nginx.conf.template` if the cert is there, else
`nginx_setup.conf.template`;
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
nginx either way.
3. `certbot` obtains or confirms the certificate, then loops renewing.
4. Everything else comes up in parallel; `depends_on` here is the plain list
form, which waits only for *start*, not readiness.
form, which waits only for _start_, not readiness.
On the Pi this is triggered automatically by `.gitea/workflows/deploy.yaml`,
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
@@ -127,9 +153,9 @@ which has two jobs:
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
hard-resets the deploy checkout, and runs
`docker compose up -d --build --remove-orphans` under the
`env-apply/run/lock` flock.
`.compose.lock` flock, shared with the weekly maintenance workflow.
The test job keeps state on the Pi outside the deploy checkout: a bare
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
@@ -142,16 +168,24 @@ validation — run it before pushing, since a red `test` job blocks the deploy.
### Development
```
cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
`.env.dev` is committed and holds only dummy values, so the stack starts
without any real credential and cannot reach a real account. Features that
need one fail at the provider, which is the point. It must become `.env`
rather than be passed with `--env-file`, because several services read
`env_file: ./.env` directly. Its Postgres passwords only match a `dbdata`
volume created with them, and as in production only `POSTGRES_DB` is created
automatically.
The override layer changes five services and disables one:
- **vue** — `npm run dev` instead of a one-shot build; `./vue` is bind-mounted
for hot reload, with anonymous-volume masks on `/app/node_modules` and
`/app/src/wasm` so the image's installed deps and compiled WASM are not hidden
by the bind mount. You need neither `node_modules` nor a Rust toolchain on the
host.
for hot reload, with an anonymous-volume mask on `/app/node_modules` so the
image's installed deps are not hidden by the bind mount. You don't need
`node_modules` on the host.
- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a
`CN=localhost` certificate (once, kept in `certbot/conf`) and render
`nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and
@@ -166,7 +200,7 @@ Visit `http://localhost`.
**`SEED_DB`** makes the Go backend populate the database with test posts, users
and messages at startup. It is set only in the dev override and must never be
set on the Pi — it would inject fake content into the live site.
set on the host — it would inject fake content into the live site.
Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
`/api`, `/gitea` and `/radio` to locally running services.
@@ -179,8 +213,7 @@ Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
The production nginx config references
`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port
80. On a brand-new host neither can go first.
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port 80. On a brand-new host neither can go first.
`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no
upstreams, nothing that can fail to load. It serves
@@ -190,7 +223,7 @@ so a half-configured site is never partially exposed.
**First run on a new domain:**
1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx
config.`
config.`
2. certbot runs `certbot certonly --webroot` and writes the certificate into
`./certbot/conf` (bind-mounted into both containers — that sharing is what
makes the whole thing work).
@@ -205,6 +238,13 @@ until the cert is inside its 30-day window, so this is well within Let's Encrypt
rate limits — it just means the window is checked twice a day. Certs are valid 90
days, so renewal lands around day 60.
**Validation method.** With `CLOUDFLARE_DNS_API_TOKEN` set, certbot proves
control of the domain by creating a `_acme-challenge` TXT record through the
Cloudflare API (DNS-01), so renewal needs no inbound port at all. That is
what lets the router's 80/443 forwards close behind the tunnel. Without the
token it uses the webroot (HTTP-01) on port 80, as it always did. Switching
either way takes effect at the next renewal; see `certbot/entrypoint.sh`.
**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container
cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the
certificate at startup and holds it in memory, so **a renewed certificate is not
@@ -212,6 +252,104 @@ served until nginx is reloaded or restarted.** In practice pushes to `main`
recreate nginx often enough to hide this. If the site ever serves an expired
cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
### Cloudflare Tunnel
The `cloudflared` container holds an outbound connection to Cloudflare and
forwards requests for the site's hostnames down it to nginx. It is a
_remotely managed_ tunnel: the only thing in this repo is the token
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
origin settings live in the dashboard.
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
terminates the visitor's TLS at its edge, and cloudflared opens a second TLS
connection to nginx. That is deliberate. Pointed at `http://nginx:80`, the
tunnel would hit the HTTP→HTTPS redirect and loop. Going to :443 keeps every
redirect, security header and the `X-Forwarded-Proto: https` the backend's
Secure cookies depend on, and needs no nginx change.
The origin is the public name, not `nginx`, because nginx carries `<DOMAIN>`
and `www.<DOMAIN>` as network aliases on `app-network` (`docker-compose.yml`).
Inside the network those names resolve to the nginx container, so the hop
never leaves the host, and cloudflared verifies the Let's Encrypt certificate
against a name it covers. `https://nginx` would fail that check and need No
TLS Verify. The flip side: **an expired certificate now takes the tunnel down
with a 502**, which is why renewal over DNS-01 (step 5) matters.
An alias only exists while nginx is running, so cloudflared also pins both
names to nginx's fixed address (`172.28.255.251`) with `extra_hosts`. Without
that, while nginx is stopped for a deploy or the weekly maintenance, the name
falls through to public DNS, resolves to Cloudflare itself, and visitors see
Cloudflare error 1000 instead of a 502.
The aliases have a side effect for anything else on `app-network` that uses
the public name for a port nginx does not serve. `silverbullet-git` pushes to
Gitea's SSH on `<DOMAIN>:2222`, so it maps `<DOMAIN>` to the host gateway
instead, where Gitea publishes that port.
Setup, once:
1. Cloudflare dashboard → the domain must be on Cloudflare DNS.
2. Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy the
token from the install command (the long string after `--token`).
3. Put it in `.env` as `CLOUDFLARE_TUNNEL_TOKEN`, then
`docker compose up -d cloudflared`. The tunnel
shows as Healthy in the dashboard.
4. Add a public hostname per name, each with service `HTTPS` and its own
name as the URL, and no other settings:
- `www.<DOMAIN>` → `https://www.<DOMAIN>`: the site.
- `<DOMAIN>` → `https://<DOMAIN>`: nginx redirects it to www, and it serves Gitea's registry
at `/v2/`.
Creating each hostname replaces the existing A record for that name with
a CNAME to the tunnel. **That is the cutover**: until then the tunnel
carries nothing.
5. Create a Cloudflare API token (My Profile → API Tokens → "Edit zone
DNS", this zone only) and set it as `CLOUDFLARE_DNS_API_TOKEN`. certbot
then renews over DNS-01 (see Renewal above) and needs no inbound port.
6. On the host, point the apex at nginx locally (next section).
7. Close the router's 80 and 443 forwards. Once 5 and 6 are done nothing
depends on them.
#### What the tunnel does not carry, and where it goes instead
- **Certificate renewal.** Over DNS-01 with `CLOUDFLARE_DNS_API_TOKEN` set;
without it certbot falls back to HTTP-01, which needs port 80 forwarded.
The certificate matters behind the tunnel: cloudflared verifies it, as
do the registry path below and any direct LAN access. A fresh machine with no
certificate at all boots the setup config (§3), which serves nothing over
443, so the tunnel carries nothing until the first issuance.
- **Registry pushes and pulls on the host.** Cloudflare caps request bodies at
100 MB on the free plan, so a push of a larger image layer through the
tunnel fails. The runner on the host pushes to `<DOMAIN>/adamf/...` and the
stack pulls from it, both through the host's Docker daemon, which resolves
names through the host's `/etc/hosts`. Pin the apex there to the loopback:
```
127.0.0.1 <DOMAIN>
```
so registry traffic goes straight to nginx on :443, with the real
certificate, and never leaves the host. (Without it the name resolves to
Cloudflare once DNS moves there.) Only the apex: www stays on Cloudflare for anything on the host
that wants the public site. Pushing from another machine still goes
through Cloudflare and its cap; use the host's Tailscale name for that.
- **Gitea SSH (2222).** Not HTTP, so not tunnelled. Already Tailscale-only:
`GITEA_SSH_DOMAIN` in `.env` (Gitea's `SSH_DOMAIN`) is the host's MagicDNS name
and 2222 has never been forwarded. Nothing changes.
- **The radio harbor (8001).** Also a raw source protocol, so a DJ client
pointed at `<DOMAIN>:8001` stops connecting once the domain resolves to
Cloudflare. Point it at the host's Tailscale name
(`stpvm.tailf20278.ts.net:8001`) and close the 8001 forward. A guest DJ
off the tailnet would need either a Tailscale share of the host or a
Cloudflare TCP route used with `cloudflared access tcp` on their side.
#### Other limits
- Cloudflare returns a 524 if the origin sends no response bytes for 100
seconds. Streaming endpoints are fine while they keep writing; a long
silent request is not.
- Dev never runs cloudflared (`disabled` profile in `docker-compose.dev.yml`),
so a laptop cannot join the production tunnel.
---
## 4. What persists across restarts
@@ -219,27 +357,28 @@ cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
**Named volumes** — survive `docker compose down` and rebuilds; destroyed only by
`docker compose down -v` or `docker volume rm`:
| Volume | Holds | Losing it means |
|---|---|---|
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
| `uploads` | User-uploaded files (backend writes, nginx serves) | All uploaded images |
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
| Volume | Holds | Losing it means |
| ---------- | ----------------------------------------------------- | -------------------------------------------------- |
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
| `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files |
| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) |
| `garage_data` | The bucket's object bytes | Every upload stored in Garage |
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
**Bind mounts** — live in the repo checkout on the Pi, survive everything short
**Bind mounts** — live in the repo checkout on the host, survive everything short
of deleting the directory:
| Path | Holds | Notes |
|---|---|---|
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
| `./certbot/www` | ACME challenge webroot | Transient by nature |
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
| `./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. |
| `./env-apply/run` | The admin panel's queued `.env` change (`request.json`) and the host's report on it (`status.json`) | Gitignored. Transient, but must be owned by the deploy user, not root — see §5. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs | |
| `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git |
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
| Path | Holds | Notes |
| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
| `./certbot/www` | ACME challenge webroot | Transient by nature |
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
| `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") |
| `./icecast2/fallback_music` | Radio fallback MP3s | Copied to the host by hand, not git |
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
**Ephemeral:** anything else inside a container. Notably the Vue build, the
rendered nginx/icecast configs, and the Gitea runner's downloaded binary
@@ -269,48 +408,21 @@ makes the site's one Claude call (the rowing photo reader); the `jobs` container
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` and `backend/services/env_registry.json`; backend tests fail if
the three disagree.
`.env.example`.
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
`.env`, and `icecast2/fallback_music/*.mp3`. The sync is **bidirectional and
resolved by modification time — newer wins, with no merge.** Editing `.env` on
both machines silently loses one side's edits. Run it before and after editing.
**`.env` is edited by hand on the host**, in
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's
`.env` (often with dev values) never reaches production by accident.
An unset variable is not an error: `envsubst` renders it as an empty string,
which for a password field means *no password*. After editing `.env`, confirm
which for a password field means _no password_. After editing `.env`, confirm
with `docker compose config`.
### Editing from the admin panel
### Changing a value on the host
The **Environment** tab at `/admin` edits `.env` on the Pi without SSH. API
keys, OAuth client settings, the email settings and the generated secrets are
editable; anything that would rename a container, move a port or lock the
backend out of Postgres is shown read-only.
The backend cannot write `.env` or reach Docker. It queues the change in
`./env-apply/run/request.json`, and a systemd path unit on the host runs
`env-apply/apply.py`, which:
1. rewrites `.env` atomically, keeping comments and order, with the previous
version saved as **`.env.bak`**;
2. runs `docker compose config -q` and restores the backup if compose rejects
the file;
3. recreates only the services that read the changed variables, plus the
backend (`docker compose up -d --no-deps --force-recreate …`);
4. writes the outcome to `status.json`, which the panel is polling.
Only those services are recreated because nginx, db, icecast2 and certbot load
the whole file too; a plain `up -d` would restart Postgres for a Steam key.
They pick the new file up at the next deploy, which is harmless.
**The watcher is installed once per host** — see the runbook. Without it the
panel still queues the change and says nothing has picked it up.
A change made this way makes the Pi's `.env` the newer copy, so the next
`./sync-secrets.sh` pulls it down to the laptop. The newer-wins caveat above
still applies: do not also edit the local copy before syncing.
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.
---
@@ -324,29 +436,32 @@ tuned value.
`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one
request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead
of that drip, and `nodelay` (used everywhere here) serves those N immediately.
So the effective behaviour is *"N instant requests, then throttled to the drip
rate"*. Anything beyond the burst gets an immediate **503**.
So the effective behaviour is _"N instant requests, then throttled to the drip
rate"_. Anything beyond the burst gets an immediate **503**.
| Zone | Rate | Burst | Applied to | Why |
|---|---|---|---|---|
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
| `upload` | 5/min | 3 | `/api/messages/upload` | Uploads can be 50MB and hit disk; bounds how fast one IP fills the volume. |
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
| Zone | Rate | Burst | Applied to | Why |
| -------------- | ------ | ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
| `upload` | 30/min | 20 | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
request, and a limit there would drop reconnect storms rather than abuse.
These zones key on the direct client IP, which is correct because nginx is the
sole edge. **If a CDN or proxy is ever put in front, they must switch to a
trusted `X-Forwarded-For` or every visitor shares one bucket.**
These zones key on `$remote_addr`. For tunnel traffic nginx rewrites that
from Cloudflare's `CF-Connecting-IP` header (`set_real_ip_from` /
`real_ip_header` in `nginx.conf.template`), trusting the header only from
cloudflared's fixed address. **If that address changes in
`docker-compose.yml` without the nginx line, every tunnel visitor shares
cloudflared's one bucket**, and the login limit locks everyone out together.
---
## 7. Runbook
All commands run from the deploy checkout on the Pi
All commands run from the deploy checkout on the host
(`~/deploy/web_server`) unless stated.
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
@@ -356,24 +471,6 @@ it. By hand:
git pull && docker compose up -d --build --remove-orphans
```
**Install the `.env` watcher** (once per host; lets the admin panel's
Environment tab apply changes):
```
./env-apply/install.sh # asks for sudo
systemctl status web-server-env-apply.path # should be active (waiting)
journalctl -u web-server-env-apply.service # one entry per applied change
```
Run it as the user that owns the checkout. `env-apply/run` must belong to that
user: if Docker created it first it is root-owned, and the script fixes that.
To apply a queued change by hand, or undo one:
```
python3 env-apply/apply.py # apply what the panel queued
cp .env.bak .env && docker compose up -d # roll back the last change
```
**Rebuild one service** (e.g. after changing only the backend):
```
@@ -410,6 +507,40 @@ docker compose ps # note: `vue` Exited(0) is correct
docker compose logs certbot # issuance / renewal outcomes
```
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
login required).
**Incoming request bodies.** nginx writes one JSON line per request, body
included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The
`traffic` container tails it, so in Dozzle pick **traffic** and each request
renders as fields you can search. From a shell:
```
tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")'
jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log
```
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
(that covers every login and the refresh call). Bodies over 64 KB, i.e.
uploads, are logged with an empty `body`, and responses are never logged.
The file is never rotated by the stack. On the host, add
`/etc/logrotate.d/web_server`:
```
/home/adamf/deploy/web_server/logs/nginx/*.log {
weekly
rotate 4
compress
missingok
notifempty
copytruncate
}
```
`copytruncate` because nginx keeps the file open; `tail -F` in `traffic`
follows the truncation.
**Reset the database** — destructive; wipes the app database **and Gitea's**:
```
@@ -427,37 +558,120 @@ manually before Gitea will start:
docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB"
```
**Sync secrets / fallback music** (from the laptop checkout, not the Pi):
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket,
with the `uploads` volume as a safety net. Nothing breaks while Garage is down
or not set up:
- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to
disk (with a log line) whenever Garage refuses a write;
- nginx serves `/uploads/` from Garage and falls back to the volume when
Garage has no such file or is unreachable, and it boots without the
`garage` container.
Turning it on:
1. Fill in `GARAGE_RPC_SECRET`, `GARAGE_ADMIN_TOKEN`, `S3_ACCESS_KEY_ID` and
`S3_SECRET_ACCESS_KEY` in `.env` **before** the deploy that adds the
containers (otherwise `garage` crash-loops on a blank secret until they
are set; nothing else is affected). `.env.example` says how to generate
each.
2. Deploy, then `garage/bootstrap.sh` (idempotent; it creates the layout, the
`uploads` bucket and the backend's key, and opens the bucket to the
website endpoint).
3. Set `S3_ENDPOINT=http://garage:3900` and `docker compose up -d backend`.
The backend logs `[upload] storing uploads in bucket uploads ...` on start.
4. Check: upload something through a canvas page or chat, then
`docker compose exec garage /garage bucket info uploads` shows the object
count going up, and the returned `/uploads/...` URL loads.
Moving the old files in (so they show in garage-webui, and so the bucket
holds everything):
```
./sync-secrets.sh
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env)
docker run --rm --network web_server_app-network \
-v web_server_uploads:/data:ro \
-e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \
-e AWS_DEFAULT_REGION=garage \
amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \
--endpoint-url http://garage:3900
```
**Set up the CI runner on a fresh Pi:**
The copies left on the volume are then only a fallback for when Garage is
down, and the rollback. One catch: a file deleted in garage-webui is still
served from its disk copy, if it has one. Once the bucket has been trusted for
a while, remove everything but `private/` from the volume.
**Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files
written to the bucket in the meantime stay reachable as long as `garage` runs;
to drop Garage entirely, first copy them back
(`aws s3 sync s3://uploads /data` with the volume mounted read-write).
**Managing files:** garage-webui at `/garage/` (site admin login). Files
uploaded there are public at `/uploads/<path>` and skip the backend's type
checks; keep them under a prefix such as `media/`. Uploads through it are
capped at 2G by nginx.
**Backups:** Garage here is one node on the same disk — it is not a backup.
Back up `garage_meta` and `garage_data` together (meta without data, or the
reverse, is useless); Garage also snapshots its metadata every 6h inside
`garage_meta`.
**Set up the CI runner on a fresh host:**
```
cd gitea-runner
bash download.sh # pulls the arm64 binary
bash download.sh # pulls the binary for this CPU
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises
```
The runner lives **outside** Docker on purpose: it runs `docker compose up`
against this stack, so it cannot be a container in it. Registration is one-shot —
`.runner` is the lasting credential; re-registering needs that file deleted *and*
`.runner` is the lasting credential; re-registering needs that file deleted _and_
a fresh token.
**Go live on the radio:** point a broadcasting client (e.g. butt) at the Pi on
**Dependency updates (Renovate).** Dependabot is GitHub-only, so
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday
at 04:00 UTC (or by hand from the Actions tab), configured by
`renovate.json5`. It opens PRs from `renovate/*` branches, which get the
normal `test` job; nothing automerges, because merging to `main` deploys. It
needs a `RENOVATE_TOKEN` repo Actions secret: create a `renovate` Gitea user,
add it to this repo as a collaborator with write access, and mint a token for
it with `read:user`, `read:organization`, `write:repository` and
`write:issue`. `RENOVATE_GITHUB_COM_TOKEN` (any github.com token, no scopes)
is optional and lifts GitHub's rate limit on release-note lookups. The first
run opens a "Dependency Dashboard" issue listing everything pending.
**Go live on the radio:** point a broadcasting client (e.g. butt) at the host's
Tailscale name (not the domain, which resolves to Cloudflare) on
`${LIQUIDSOAP_HARBOR_PORT}` with mount `${LIQUIDSOAP_HARBOR_MOUNT}` and the
icecast source password. liquidsoap pre-empts the fallback playlist immediately
(`track_sensitive=false`). Disconnect and it falls back to the playlist, then to
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
(`reload_mode="watch"`) with no restart.
**Unhealthy containers are not restarted automatically.** `backend` and `python`
define healthchecks, but the `autoheal` watchdog that acted on them was retired
(`.deprecated/autoheal`), so `unhealthy` is only visible in `docker ps`.
`restart: always` still brings back a container whose process exits.
**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
```
---
@@ -475,7 +689,7 @@ Documented, not fixed — each would change deploy behaviour.
mounted to the same in-container path as the real wrapper. It is currently
shadowed by an explicit file mount — fragile. Deleting it would be safe but
is a file removal.
4. **The two `/uploads/` location blocks are still written twice** — once in
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
+3 -18
View File
@@ -11,8 +11,7 @@
# 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/, and the
# generated vue/src/wasm/ directory (see below)
# 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.
#
@@ -69,26 +68,12 @@ $(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
check-python: $(VENV_STAMP)
cd python && ../$(VENV)/bin/python -m pytest tests -q
# `npx vite build`, NOT `npm run build`: the npm script first runs wasm-pack to
# compile the Rust crate, which needs a Rust toolchain most machines (and the
# Pi) do not have. The Vite half alone is enough to catch a broken import or
# template.
#
# It does still need the OUTPUT of that Rust step, vue/src/wasm/, which is
# generated and gitignored — so a fresh clone has none and Vite would fail with
# a bare "could not resolve ../wasm/..." error. The guards below say what is
# actually wrong instead.
# 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/src/wasm || { \
echo "check-vue: vue/src/wasm/ is missing."; \
echo " It is the generated (gitignored) output of the Rust crate in vue/crates/"; \
echo " and the Vite build imports it. Create it with wasm-pack:"; \
echo " cd vue && npm run build:wasm"; \
echo " (needs a Rust toolchain; the vue image builds it for you, see vue/Dockerfile)."; \
exit 1; }
@test -d vue/node_modules || { \
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
exit 1; }
+4 -3
View File
@@ -1,3 +1,4 @@
Gay bal;;s
# My Web
![screenshot](vue/public/img/screenshot.png)
@@ -32,7 +33,7 @@ certbot ── SSL Certificate Management (disabled in dev)
## Tech Stack
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX)
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
@@ -147,7 +148,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
**Protected (auth required)**
| Method | Path | Description |
| --- | --- | --- |
| POST | `/api/messages/upload` | Upload message file (rate limited: 5/min) |
| POST | `/api/messages/upload` | Upload a file for a chat message or a canvas box (rate limited: 30/min, burst 20) |
**Admin (auth + admin required)**
| Method | Path | Description |
@@ -302,6 +303,7 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
Run the full stack over plain HTTP without SSL certificates:
```sh
cp .env.dev .env # committed, dummy values only
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
@@ -349,7 +351,6 @@ These files are git-ignored and must be created manually:
## Future Ideas
- More Rust to WASM
- ML for chatboards
- Cache requests
- Design more webpages
+28 -46
View File
@@ -64,6 +64,16 @@ graph/ GraphQL layer
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
and will transparently refresh, so returning admins are recognised without a
visible re-login.
- `GET /auth/validate/:permission` is the same for one named permission
(200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
*permission gate*, which lets a non-admin account into one service — the
receipt printer at `/receipt/` — without making it an admin. Grantable keys
are the registry `services.PermissionTypes` (`services/permissions.go`);
a user's grants are `User.Permissions`, set from the admin panel's Manage
Users tab (`setUserPermissions`). Admins pass every permission check. The
check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which
nginx forwards to the gated service as `X-Remote-User`.
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
is revoked server-side, and a token that has already been issued stays valid
until it expires. The same is true of demoting an admin: it takes effect on
@@ -172,52 +182,11 @@ for the things GraphQL cannot do:
| --- | --- |
| `/auth/*` | cookie handling and the status-code-only admin probe |
| `/spotify/callback` | OAuth providers redirect a *browser* here |
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
| `/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 |
| `/admin/env`, `/admin/logs` | process environment and files on disk, not the data model |
### Environment tab
`handlers/handle_env.go` and `services/env_manager.go` let the admin panel
change `.env` on the Pi without SSH. The backend never reads or writes the
file and has no Docker access: it validates an edit and leaves it for the
host, which is the part trusted to act.
- **`services/env_registry.json`** lists every variable in `.env.example`
with its group, kind, whether it is editable, and the compose services that
read it. It is embedded in the binary and read from the checkout by the host
script, so one file decides what the panel offers and what the host accepts.
A test fails if it and `.env.example` disagree.
- **The `python` and `jobs` services are a third place.** They are given an
explicit `environment:` list in `docker-compose.yml` instead of the whole
`.env`, so that they never hold the site's database password or the JWT
secret. A new variable for either therefore goes in the registry (with the
service in its `services`), in `.env.example`, *and* in that list.
`TestEnvRegistryMatchesComposePythonEnvironment` reads the compose file and
fails if a variable the registry says one of them reads is not passed to
it, or if an editable variable passed to it does not list that service. Locked
variables carry no `services` and are exempt (`PYTHON_PORT` is one).
- `GET /admin/env` — the registry plus state from this process's own
environment. A secret's value is never sent, only "set" and, for values of
12+ characters, the last four.
- `PUT /admin/env` — `{"set": {NAME: value}, "generate": [NAME]}`; `""`
clears. The whole batch is validated first. Control characters are refused
because `.env` is line oriented: a newline would let an edit to an allowed
variable write a second, arbitrary one. Generated values (32 random bytes,
hex) are returned once.
- The change is written to `/backend/env-apply/request.json` (`./env-apply/run`
on the host), `0600` and chowned to that directory's owner so the
unprivileged host user can read it. `env-apply/apply.py` claims it, rewrites
`.env`, recreates the affected services and writes `status.json`.
- `GET /admin/env/status` — `idle`, `pending`, `applying`, `applied` or
`failed`. `watcher: false` means a request has sat unclaimed for 15 seconds,
i.e. nothing on the host is watching. `DELETE /admin/env/pending` withdraws
an unclaimed request.
The backend is always among the recreated services, because the values the
panel shows are the ones this process started with.
## Calling the Python service
@@ -268,6 +237,19 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
(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
@@ -356,7 +338,7 @@ 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. It is in
the registry with `services: ["python", "jobs"]`, the two containers that use
it. The email and job-lead variables still in `.env` belong to the job
`CLAUDE_API_KEY` is not in the table: the backend does not read it. The
`python` and `jobs` containers, the two that use it, get it through their
explicit `environment:` lists in `docker-compose.yml`. The email and job-lead variables still in `.env` belong to the job
tracker (`jobs`), which has its own repo and README.
+12
View File
@@ -4,6 +4,9 @@ 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
@@ -18,6 +21,15 @@ require (
require (
github.com/agnivade/levenshtein v1.2.1 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
github.com/aws/smithy-go v1.28.5 // indirect
github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
+24
View File
@@ -39,6 +39,30 @@ github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KO
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=
+52
View File
@@ -34,6 +34,10 @@ models:
resolver: false
deletedAt:
resolver: false
# Not a database model: the fixed registry in services/permissions.go.
PermissionType:
model:
- adam-french.co.uk/backend/services.PermissionType
Post:
model:
- adam-french.co.uk/backend/models.Post
@@ -76,3 +80,51 @@ models:
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
+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)
}
}
}
+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)
}
})
}
}
+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)
}
})
}
}
+8 -3
View File
@@ -187,9 +187,14 @@ func TestSignedInMutationsArePinned(t *testing.T) {
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
"user": "admin",
"places": "signedIn",
"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 {
+6852 -22
View File
File diff suppressed because it is too large Load Diff
+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
}
+102
View File
@@ -12,6 +12,12 @@ type AuthPayload struct {
User *models.User `json:"user"`
}
type BackgroundInput struct {
Color string `json:"color"`
Image string `json:"image"`
Fit string `json:"fit"`
}
type CreateActivityInput struct {
Type string `json:"type"`
Name string `json:"name"`
@@ -24,12 +30,62 @@ type CreateBookmarkInput struct {
Link string `json:"link"`
}
type CreateBoxInput struct {
Page string `json:"page"`
Kind string `json:"kind"`
Widget *string `json:"widget,omitempty"`
HTML *string `json:"html,omitempty"`
Title *string `json:"title,omitempty"`
X *int `json:"x,omitempty"`
Y *int `json:"y,omitempty"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Z *int `json:"z,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
ComponentID *int `json:"componentId,omitempty"`
}
type CreateComponentInput struct {
Name string `json:"name"`
Title *string `json:"title,omitempty"`
HTML string `json:"html"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type CreateCoverLetterInput struct {
Name string `json:"name"`
Body string `json:"body"`
}
type CreateCoverSnippetInput struct {
Text string `json:"text"`
Section *string `json:"section,omitempty"`
}
type CreateFavoriteInput struct {
Type string `json:"type"`
Name string `json:"name"`
Link *string `json:"link,omitempty"`
}
type 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"`
@@ -113,6 +169,52 @@ type SteamStatus struct {
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"`
+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)
}
}
}
+7
View File
@@ -8,6 +8,7 @@ package graph
import (
"context"
"fmt"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
@@ -23,6 +24,12 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
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
+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
}
+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
}
+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
}
+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
}
+16
View File
@@ -4,6 +4,17 @@ type User {
updatedAt: Time!
username: String!
admin: Boolean!
# Keys of the gated services this user may use (see PermissionType). Admins
# pass every permission check whatever this holds.
permissions: [String!]!
}
# One grantable service, from services.PermissionTypes: `key` is what is
# stored and what nginx gates on, `label` and `path` are for display.
type PermissionType {
key: String!
label: String!
path: String!
}
input CreateUserInput {
@@ -14,10 +25,15 @@ input CreateUserInput {
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
}
+43
View File
@@ -8,9 +8,11 @@ package graph
import (
"context"
"fmt"
"slices"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"golang.org/x/crypto/bcrypt"
)
@@ -72,6 +74,41 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return &user, nil
}
// SetUserPermissions is the resolver for the setUserPermissions field.
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
// The whole list is replaced, so the admin panel sends every ticked box
// each time. An unknown key is refused rather than dropped, so a stale
// front end cannot silently save less than it showed. The stored list is
// rebuilt in registry order, which also drops duplicates.
want := map[string]bool{}
for _, key := range permissions {
if !services.ValidPermission(key) {
return nil, fmt.Errorf("unknown permission %q", key)
}
want[key] = true
}
granted := []string{}
for _, p := range services.PermissionTypes {
if want[p.Key] {
granted = append(granted, p.Key)
}
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
// No token bump needed: the permission gate reads this column on every
// request, so the change applies to the user's next one.
user.Permissions = granted
if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// Users is the resolver for the users field.
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
var users []models.User
@@ -89,3 +126,9 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
}
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
}
-93
View File
@@ -1,93 +0,0 @@
package handlers
import (
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
)
// This file backs the admin diagnostics panel's log tail. It is an admin-only
// REST endpoint rather than GraphQL because it reads the filesystem — outside
// the data model the GraphQL schema describes. The configuration report that
// used to live here is now the Environment tab (handle_env.go).
// logTailBytes and logTailLines bound how much of the log file one request
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
// cheap even on the Pi.
const (
logTailBytes = 256 << 10
logTailLines = 500
)
// Logs backs GET /admin/logs. It returns the tail of the backend's own log
// file (go.log — Gin traffic plus application log lines), which lives on the
// bind-mounted ./logs volume.
//
// Why tail and not offer a range: the panel wants "what happened recently",
// and the file can grow unboundedly between rotations, so anything else
// invites reading the whole thing into memory.
func (store *Store) Logs(ctx *gin.Context) {
lines, size, err := tailLogFile(logPath)
if err != nil {
// The mount being absent is a deployment problem worth surfacing
// distinctly from "log file empty".
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size})
}
// logPath matches the file main.go opens for gin.DefaultWriter.
const logPath = "/backend/logs/go.log"
// tailLogFile returns the last logTailLines lines of a file, reading at most
// logTailBytes from the end. Split out from the handler so the offset and
// partial-line rules are testable without a filesystem mount.
func tailLogFile(path string) ([]string, int64, error) {
f, err := os.Open(path)
if err != nil {
return nil, 0, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, 0, err
}
// Read from near the end rather than head-to-toe so the read stays
// constant-size regardless of how old the file is.
start := int64(0)
if info.Size() > logTailBytes {
start = info.Size() - logTailBytes
}
buf := make([]byte, info.Size()-start)
if len(buf) > 0 {
if _, err := f.ReadAt(buf, start); err != nil {
return nil, 0, err
}
}
// Starting mid-file almost certainly lands mid-line; drop that fragment
// so the panel never renders a truncated first entry.
text := string(buf)
if start > 0 {
if i := strings.IndexByte(text, '\n'); i >= 0 {
text = text[i+1:]
}
}
text = strings.TrimRight(text, "\n")
if text == "" {
return []string{}, info.Size(), nil
}
lines := strings.Split(text, "\n")
if len(lines) > logTailLines {
lines = lines[len(lines)-logTailLines:]
}
return lines, info.Size(), nil
}
-76
View File
@@ -1,76 +0,0 @@
package handlers
import (
"os"
"path/filepath"
"strings"
"testing"
)
// tailLogFile's rules that are easy to get wrong: the line cap, and dropping
// the partial first line when the read started mid-file.
func writeLog(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "go.log")
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("writing fixture: %v", err)
}
return path
}
func TestTailLogFileCapsLines(t *testing.T) {
var b strings.Builder
for range logTailLines + 50 {
b.WriteString("line\n")
}
lines, _, err := tailLogFile(writeLog(t, b.String()))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) != logTailLines {
t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines)
}
}
func TestTailLogFileDropsPartialFirstLine(t *testing.T) {
// A file larger than the byte window: the read starts mid-file, so the
// first line it sees is a fragment and must be discarded.
filler := strings.Repeat("x", 100) + "\n"
var b strings.Builder
for b.Len() < logTailBytes+len(filler) {
b.WriteString(filler)
}
b.WriteString("FINAL\n")
lines, _, err := tailLogFile(writeLog(t, b.String()))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) == 0 {
t.Fatal("expected some lines")
}
if lines[len(lines)-1] != "FINAL" {
t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1])
}
// Every surviving line must be whole, i.e. a full filler line.
if got := lines[0]; got != strings.TrimSuffix(filler, "\n") {
t.Fatalf("first line = %q, want a complete filler line", got)
}
}
func TestTailLogFileEmpty(t *testing.T) {
lines, size, err := tailLogFile(writeLog(t, ""))
if err != nil {
t.Fatalf("tailLogFile: %v", err)
}
if len(lines) != 0 || size != 0 {
t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size)
}
}
func TestTailLogFileMissing(t *testing.T) {
if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil {
t.Fatal("expected an error for a missing log file")
}
}
+72 -36
View File
@@ -93,51 +93,86 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
}
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// decide whether to show admin UI. It answers with a bare status code and no
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
// decide whether to show admin UI, nginx's admin gate calls as an
// auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
// new cookie pair as a side effect, so a returning admin is recognised
// without a visible re-login.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
accessToken, err := ctx.Cookie("access_token")
if err != nil {
// No access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// On the access-token path admin is read from the token, as
// everywhere else; on the refresh path there is no admin claim, and
// the row is what makes that path pick up a revoked admin flag.
if claims == nil {
return user.Admin
}
return
}
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err != nil {
// Expired, invalid or revoked access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
}
return
}
admin, ok := (*claims)["admin"].(bool)
if !ok || !admin {
ctx.Status(http.StatusForbidden)
return
}
ctx.Status(http.StatusOK)
admin, ok := (*claims)["admin"].(bool)
return ok && admin
})
}
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
// ValidatePermission backs GET /auth/validate/:permission, nginx's permission
// gate (see services/permissions.go). Same bare-status contract and refresh
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in an nginx location fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The bool does not mean "is an admin" — it means "this function already
// wrote the response". It returns true both for a successful admin refresh
// (200, new cookies set) and for a valid non-admin (403), and false only when
// it could not decide, leaving the caller to send 401. Getting this backwards
// would send two status codes for one request.
// The decision reads the user row, not the token, for admins as well: a
// grant, a revoke or a demotion applies on the very next request.
func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission")
if !services.ValidPermission(key) {
ctx.Status(http.StatusNotFound)
return
}
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
return services.HasPermission(user, key)
})
}
// validateSession is the body shared by the two validate endpoints: identify
// the caller from the access token, or failing that the refresh token, and
// answer 200 / 403 / 401 according to allow.
//
// Admin status is re-read from the database here, which is what makes the
// refresh path pick up a revoked admin flag.
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which nginx can lift with
// auth_request_set and hand to the service behind the gate, so that service
// knows who is using it without having accounts of its own.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err == nil {
if !allow(user, claims) {
ctx.Status(http.StatusForbidden)
return
}
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return
}
}
// No access token, or an expired, invalid or revoked one — try refreshing.
if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized)
}
}
// tryRefreshAndValidate re-authenticates from the refresh token.
//
// The bool does not mean "allowed" — it means "this function already wrote
// the response". It returns true both for a successful refresh (200, new
// cookies set) and for a valid but unauthorised user (403, no new cookies),
// and false only when it could not decide, leaving the caller to send 401.
// Getting this backwards would send two status codes for one request.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
@@ -150,7 +185,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
return false
}
if !user.Admin {
if !allow(user, nil) {
ctx.Status(http.StatusForbidden)
return true
}
@@ -162,6 +197,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
store.setAuthCookies(ctx, tokens)
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return true
}
-133
View File
@@ -1,133 +0,0 @@
package handlers
import (
"errors"
"log"
"net/http"
"os"
"strings"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
)
// This file backs the admin panel's Environment tab: a report on every
// variable in .env, and a way to change the ones that are safe to change.
//
// The handlers never read or write .env. State is this process's own
// environment, and a change is a request left for the host to apply (see
// services.EnvManager). REST rather than GraphQL for the same reason as the
// rest of the admin endpoints: this is process and host state, not the data
// model the schema describes.
// envSecretHintMinLen is the shortest secret that gets its last four
// characters shown. Below it, four characters is too much of the value.
const envSecretHintMinLen = 12
type envVarView struct {
services.EnvVar
Secret bool `json:"secret"`
Set bool `json:"set"`
// Value is sent only for non-secret variables; Hint (the last four
// characters) is all a secret ever reveals.
Value string `json:"value,omitempty"`
Hint string `json:"hint,omitempty"`
}
type envGroupView struct {
Name string `json:"name"`
Vars []envVarView `json:"vars"`
}
// GetEnv backs GET /admin/env: every registry variable grouped for display,
// plus the state of the latest change.
//
// Values are what this process was started with, not what .env holds now —
// the two differ between a save and the recreate that follows it, which is
// what the status's pending list is for.
func (store *Store) GetEnv(ctx *gin.Context) {
var groups []envGroupView
index := map[string]int{}
for _, v := range store.Env.Vars() {
value := os.Getenv(v.Name)
view := envVarView{EnvVar: v, Secret: v.Secret(), Set: strings.TrimSpace(value) != ""}
switch {
case !view.Set:
case !view.Secret:
view.Value = value
case len(value) >= envSecretHintMinLen:
view.Hint = value[len(value)-4:]
}
i, seen := index[v.Group]
if !seen {
i = len(groups)
index[v.Group] = i
groups = append(groups, envGroupView{Name: v.Group})
}
groups[i].Vars = append(groups[i].Vars, view)
}
ctx.JSON(http.StatusOK, gin.H{"groups": groups, "status": store.Env.Status()})
}
type updateEnvRequest struct {
// Set maps a variable to its new value; "" clears it.
Set map[string]string `json:"set"`
// Generate names "generated" variables to mint a random value for.
Generate []string `json:"generate"`
}
// UpdateEnv backs PUT /admin/env. It queues the change for the host and
// returns straight away; the panel follows progress on GET /admin/env/status,
// through the backend's own restart.
//
// The response is the only time a generated value is sent anywhere.
func (store *Store) UpdateEnv(ctx *gin.Context) {
var body updateEnvRequest
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
generated, recreates, err := store.Env.Submit(body.Set, body.Generate)
if errors.Is(err, services.ErrEnvApplying) {
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
if err != nil {
// Validation messages name the variable, never the value.
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
names := make([]string, 0, len(body.Set)+len(body.Generate))
for name := range body.Set {
names = append(names, name)
}
names = append(names, body.Generate...)
log.Printf("[Env] change queued for %s", strings.Join(names, ", "))
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusAccepted, gin.H{
"generated": generated,
"services": recreates,
"status": store.Env.Status(),
})
}
// GetEnvStatus backs GET /admin/env/status.
func (store *Store) GetEnvStatus(ctx *gin.Context) {
ctx.JSON(http.StatusOK, store.Env.Status())
}
// CancelEnv backs DELETE /admin/env/pending: withdraw a request nothing on
// the host has picked up, so new secrets do not sit in the shared directory
// waiting for a watcher that is not there.
func (store *Store) CancelEnv(ctx *gin.Context) {
if err := store.Env.Cancel(); err != nil {
log.Println("Cancelling env request failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to cancel the request"})
return
}
ctx.JSON(http.StatusOK, store.Env.Status())
}
-148
View File
@@ -1,148 +0,0 @@
package handlers
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
)
func envRouter(t *testing.T) (*gin.Engine, string) {
t.Helper()
gin.SetMode(gin.TestMode)
dir := t.TempDir()
env, err := services.NewEnvManager(dir)
if err != nil {
t.Fatalf("NewEnvManager: %v", err)
}
store := &Store{Env: env}
r := gin.New()
r.GET("/admin/env", store.GetEnv)
r.PUT("/admin/env", store.UpdateEnv)
r.GET("/admin/env/status", store.GetEnvStatus)
r.DELETE("/admin/env/pending", store.CancelEnv)
return r, dir
}
func envDo(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec
}
// The property the whole tab rests on: a secret's value never leaves the
// server, while a non-secret's does so it can be edited in place.
func TestGetEnvNeverReturnsSecrets(t *testing.T) {
r, _ := envRouter(t)
t.Setenv("CLAUDE_API_KEY", "sk-ant-very-secret-value-9f3a")
t.Setenv("POSTGRES_PASSWORD", "hunter2")
t.Setenv("STEAM_ID", "76561198000000000")
t.Setenv("TFL_APP_KEY", "")
rec := envDo(r, http.MethodGet, "/admin/env", "")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
body := rec.Body.String()
for _, secret := range []string{"sk-ant-very-secret-value-9f3a", "hunter2"} {
if strings.Contains(body, secret) {
t.Fatalf("response contains the secret %q", secret)
}
}
var parsed struct {
Groups []struct {
Vars []envVarView `json:"vars"`
} `json:"groups"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
t.Fatalf("parsing response: %v", err)
}
byName := map[string]envVarView{}
for _, g := range parsed.Groups {
for _, v := range g.Vars {
byName[v.Name] = v
}
}
if v := byName["CLAUDE_API_KEY"]; !v.Set || !v.Secret || v.Value != "" || v.Hint != "9f3a" {
t.Errorf("CLAUDE_API_KEY = %+v, want set, secret, no value, hint 9f3a", v)
}
// Too short for four characters to be a safe hint.
if v := byName["POSTGRES_PASSWORD"]; !v.Set || v.Hint != "" || v.Editable {
t.Errorf("POSTGRES_PASSWORD = %+v, want set, no hint, locked", v)
}
if v := byName["STEAM_ID"]; v.Value != "76561198000000000" || v.Secret {
t.Errorf("STEAM_ID = %+v, want its value shown", v)
}
if v := byName["TFL_APP_KEY"]; v.Set {
t.Errorf("TFL_APP_KEY = %+v, want unset", v)
}
}
func TestUpdateEnv(t *testing.T) {
r, dir := envRouter(t)
requestPath := filepath.Join(dir, "request.json")
t.Run("a locked variable is refused and nothing is queued", func(t *testing.T) {
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"POSTGRES_PASSWORD":"x"}}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", rec.Code)
}
if _, err := os.Stat(requestPath); err == nil {
t.Fatal("a refused change left a request behind")
}
})
t.Run("a malformed body is refused", func(t *testing.T) {
if rec := envDo(r, http.MethodPut, "/admin/env", `{"set":`); rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", rec.Code)
}
})
t.Run("a valid change is queued and a generated value returned once", func(t *testing.T) {
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"STEAM_ID":"42"},"generate":["BACKEND_SECRET"]}`)
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202: %s", rec.Code, rec.Body)
}
var parsed struct {
Generated map[string]string `json:"generated"`
Status services.EnvApplyStatus `json:"status"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
t.Fatalf("parsing response: %v", err)
}
secret := parsed.Generated["BACKEND_SECRET"]
if len(secret) != 64 {
t.Fatalf("generated BACKEND_SECRET = %q, want 64 hex characters", secret)
}
if parsed.Status.State != "pending" {
t.Fatalf("status = %+v, want pending", parsed.Status)
}
// Reading the state back must not repeat it.
for _, path := range []string{"/admin/env", "/admin/env/status"} {
if strings.Contains(envDo(r, http.MethodGet, path, "").Body.String(), secret) {
t.Fatalf("GET %s repeats the generated secret", path)
}
}
})
t.Run("a pending change can be withdrawn", func(t *testing.T) {
rec := envDo(r, http.MethodDelete, "/admin/env/pending", "")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if _, err := os.Stat(requestPath); err == nil {
t.Fatal("the request file survived the cancel")
}
})
}
-178
View File
@@ -1,178 +0,0 @@
package handlers
import (
"crypto/rand"
"encoding/hex"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Attachment upload for the chat.
//
// Files land in one of two directories. /backend/uploads/ is served by nginx
// at /uploads/ with no authentication, so anything written there is publicly
// reachable by URL — which is why the extension and content checks below
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
// messages and is served at /uploads/private/ behind an nginx auth_request
// gate; only an admin may upload there.
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
var allowedExtensions = map[string]bool{
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
".pdf": true, ".txt": true,
}
// extensionToMIMEPrefix cross-checks the sniffed content type against the
// claimed extension, to stop e.g. HTML being served from a .png URL.
//
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
// http.DetectContentType's answers for them are unreliable enough to reject
// legitimate files, so a missing entry means "extension allowed, content not
// verified".
var extensionToMIMEPrefix = map[string]string{
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
".mp4": "video/", ".webm": "video/",
".pdf": "application/pdf", ".txt": "text/",
}
// publicUploadDir and privateUploadDir are the two destinations; the private
// one is created on demand because nothing else guarantees it exists.
const (
publicUploadDir = "/backend/uploads/"
privateUploadDir = "/backend/uploads/private/"
)
// UploadMessageFile backs POST /messages/upload (login required) and returns
// the URL of the stored file, which the client then sends over the WebSocket
// as a message's fileUrl.
//
// The multipart form takes an optional "private" field: "true" stores the file
// under /uploads/private/ for use as a private message's attachment. That is
// admin-only, because private messages themselves are — an attachment URL
// leaking out is the same disclosure as the message leaking out.
func (store *Store) UploadMessageFile(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
const maxSize = 10 << 20 // 10MB
if file.Size > maxSize {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowedExtensions[ext] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed"})
return
}
// Validate actual content type matches extension
f, err := file.Open()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
return
}
// 512 bytes is exactly what http.DetectContentType inspects; reading more
// would be wasted. A single Read may return fewer bytes than asked for,
// which is fine — sniffing works on a short prefix — so only a read that
// produced nothing at all is an error.
buf := make([]byte, 512)
n, err := f.Read(buf)
f.Close()
if err != nil && n == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file content"})
return
}
detectedType := http.DetectContentType(buf[:n])
expectedPrefix, ok := extensionToMIMEPrefix[ext]
if ok && !strings.HasPrefix(detectedType, expectedPrefix) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file content does not match extension"})
return
}
// The uploaded name is discarded entirely in favour of 16 random bytes
// from crypto/rand. That kills path traversal and collisions in one go,
// and makes the resulting URL unguessable. Only the extension is carried
// over, and it has already been checked against the allow-list.
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
return
}
filename := hex.EncodeToString(b) + ext
uploadDir := publicUploadDir
urlPrefix := "/uploads/"
if private {
uploadDir = privateUploadDir
urlPrefix = "/uploads/private/"
// 0755 so nginx (a different user) can traverse the directory to
// serve the files once its auth_request gate has approved.
if err := os.MkdirAll(uploadDir, 0755); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
}
dest := filepath.Join(uploadDir, filename)
// Reopened rather than rewound: the earlier handle was closed after
// sniffing, and multipart files may be backed by either memory or a temp
// file, so a fresh reader is the simplest correct option.
src, err := file.Open()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
return
}
defer src.Close()
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
defer out.Close()
if _, err := io.Copy(out, src); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+89
View File
@@ -0,0 +1,89 @@
package handlers
import (
"errors"
"log"
"net/http"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Upload backs POST /uploads (login required): the one endpoint the frontend
// stores a file through (vue/src/uploads.js). Multipart form:
//
// file the file (required)
// private "true" to store it as an admin-only chat attachment
//
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
// the file was refused (wrong type, too large) and 500 when storing failed.
// Validation, naming and storage are all services.Uploads.Save; this handler
// only reads the form and decides who may use `private`.
//
// `private` is admin-only because private messages themselves are: an
// attachment URL leaking out is the same disclosure as the message leaking.
func (store *Store) Upload(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
url, err := store.Uploads.Save(ctx.Request.Context(), file, private)
var rejected *services.UploadError
switch {
case errors.As(err, &rejected):
ctx.JSON(http.StatusBadRequest, gin.H{"error": rejected.Message})
case err != nil:
log.Printf("[upload] storing %s failed: %v", file.Filename, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
default:
ctx.JSON(http.StatusOK, gin.H{"url": url})
}
}
// ListUploads backs GET /uploads (admin): every public upload, newest first,
// for the upload picker on the canvas pages (vue/src/components/util/
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
//
// Admin-only because the listing is the one thing that turns unguessable
// upload URLs into known ones; see services.Uploads.List.
func (store *Store) ListUploads(ctx *gin.Context) {
files, err := store.Uploads.List(ctx.Request.Context())
if err != nil {
log.Printf("[upload] listing failed: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list uploads"})
return
}
if files == nil {
files = []services.StoredFile{} // [] rather than null for the frontend
}
ctx.JSON(http.StatusOK, gin.H{"files": files})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+40 -58
View File
@@ -14,23 +14,22 @@ import (
// What is deliberately NOT covered here, and why:
//
// - Every handler method (Login, UploadMessageFile, the radio file movers,
// - Every handler method (Login, Upload, the radio file movers,
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
// multipart request, the container's /backend/... directories, or a paid
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
// CI.
// - The radio/chat upload filename sanitisation itself. It is written inline
// inside the handler bodies rather than in a helper, so testing it would
// mean either driving a full multipart upload against the real upload
// directories or refactoring production code. Neither was in scope, so the
// part that *is* extractable — the extension allow-lists those handlers
// gate on — is covered as a table contract below instead.
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
// reach the database on the refresh path.
// - The radio upload's filename sanitisation. It is written inline in the
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
// the upload allow-list tables.
// the radio allow-list.
// --- Spotify OAuth CSRF nonces -------------------------------------------
@@ -253,57 +252,40 @@ func TestRequestIsAdmin(t *testing.T) {
}
}
// The allow-list tables are the upload trust boundary's data. Testing them as
// data catches the realistic failure: someone adding an executable or markup
// extension, or adding an extension to the MIME map without allowing it (which
// would be dead configuration).
func TestUploadAllowLists(t *testing.T) {
t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) {
// Served by nginx from a public directory with no auth, so anything
// the browser will execute or render as markup must not be storable.
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} {
if allowedExtensions[ext] {
t.Errorf("%q must not be an allowed chat upload extension", ext)
}
}
})
// --- Permission gate ------------------------------------------------------
t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) {
// The handlers look up strings.ToLower(filepath.Ext(...)), so a key in
// any other shape is unreachable.
for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} {
for ext := range m {
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
}
// An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in an nginx
// location shows up as a 404 rather than as a missing grant.
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Store{}
for _, key := range []string{"no-such-service", "admin", ""} {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "permission", Value: key}}
ctx.Request = httptest.NewRequest("GET", "/auth/validate/"+key, nil)
s.ValidatePermission(ctx)
if ctx.Writer.Status() != 404 {
t.Errorf("key %q: status %d, want 404", key, ctx.Writer.Status())
}
})
}
}
t.Run("every MIME-checked extension is also allowed", func(t *testing.T) {
for ext := range extensionToMIMEPrefix {
if !allowedExtensions[ext] {
t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext)
}
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
func TestRadioAllowList(t *testing.T) {
for ext := range allowedAudioExtensions {
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
// any other shape is unreachable.
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
})
t.Run("audio extensions are content-unverified by design", func(t *testing.T) {
// http.DetectContentType is unreliable for these, so a missing entry
// means "extension allowed, content not verified". Adding one would
// start rejecting legitimate uploads.
for _, ext := range []string{".mp3", ".ogg"} {
if _, ok := extensionToMIMEPrefix[ext]; ok {
t.Errorf("%q should not be MIME-checked", ext)
}
}
})
t.Run("radio allow-list is audio only", func(t *testing.T) {
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
}
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
})
}
}
+3 -3
View File
@@ -38,9 +38,9 @@ type Store struct {
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string
// Registry of .env variables and the request/status hand-off with the
// host that applies changes to them (handle_env.go).
Env *services.EnvManager
// 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
+20 -18
View File
@@ -128,19 +128,27 @@ func main() {
}
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)
// ENVIRONMENT
// The registry is embedded, so the only way this fails is a malformed
// env_registry.json — a build mistake worth stopping for.
envManager, err := services.NewEnvManager(services.ENV_APPLY_DIR)
if err != nil {
log.Fatal(err)
}
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, Env: envManager}
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.
@@ -159,6 +167,7 @@ func main() {
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
@@ -181,19 +190,12 @@ func main() {
// /ws is deliberately outside the protected group: chat is public, and
// the handler checks the cookies itself to decide admin privileges.
r.GET("/ws", store.ConnectWebSocket)
protected.POST("/messages/upload", store.UploadMessageFile)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile)
// ADMIN DIAGNOSTICS: log tail for the admin panel.
admin.GET("/admin/logs", store.Logs)
// ENVIRONMENT: report on .env and queue changes for the host to apply.
admin.GET("/admin/env", store.GetEnv)
admin.PUT("/admin/env", store.UpdateEnv)
admin.GET("/admin/env/status", store.GetEnvStatus)
admin.DELETE("/admin/env/pending", store.CancelEnv)
// GRAPHQL
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
// so the transports and extensions below are explicit.
+159
View File
@@ -39,6 +39,14 @@ type User struct {
// Admin gates almost every mutation. It is copied into the access token,
// so a change here only takes effect on the user's next token refresh.
Admin bool `json:"admin"`
// Permissions names the gated services this non-admin user may use, one
// key each from services.PermissionTypes (admins pass every check
// regardless). Unlike Admin it is never copied into a token: the gate
// reads it from the row, which services.Auth loads on every request
// anyway, so a grant or revoke takes effect on the user's next request.
// Stored as a JSON array in one text column; a row from before the
// column existed reads as NULL, i.e. no permissions.
Permissions []string `gorm:"serializer:json" json:"permissions"`
// TokenVersion is the session generation counter. Every issued JWT
// carries the value current at the time it was minted, and
// services.Auth rejects a token whose value no longer matches, so
@@ -155,3 +163,154 @@ type Place struct {
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"`
}
+1 -1
View File
@@ -155,7 +155,7 @@ func tokenVersionOf(v uint) uint {
// verifies the signature and expiry, reads the id claim, loads the row, and
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
+24 -1
View File
@@ -51,12 +51,35 @@ func migrateDatabase(db *gorm.DB) error {
&models.Message{},
&models.Bookmark{},
&models.Place{},
&models.Box{},
&models.Page{},
&models.Background{},
&models.Layout{},
&models.Component{},
&models.CoverLetter{},
&models.CoverSnippet{},
)
if err != nil {
return err
}
return nil
return ensureStpPage(db)
}
// ensureStpPage turns the home page (/stp) into an ordinary canvas Page once.
// It used to be a built-in canvas with its own route; its boxes and
// background were already keyed "stp", so a Page row with that slug is all
// it takes. Unscoped, so that deleting the page on purpose sticks rather than
// bringing it back on the next start.
func ensureStpPage(db *gorm.DB) error {
var count int64
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil
}
return db.Create(&models.Page{Slug: "stp", Title: "STP"}).Error
}
// InitDatabase connects to Postgres and runs the auto-migration.
-377
View File
@@ -1,377 +0,0 @@
package services
import (
"crypto/rand"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/url"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
// ENV_APPLY_DIR is the directory shared with the host (./env-apply/run in the
// checkout, bind-mounted by docker-compose). It is the whole interface
// between this process and the host script that edits .env.
const ENV_APPLY_DIR = "/backend/env-apply"
// The registry is JSON rather than a Go literal because the host script
// (env-apply/apply.py) reads the same file from the checkout: one list
// decides both what the panel offers and what the host will accept.
//
//go:embed env_registry.json
var envRegistryJSON []byte
// EnvVar is one registry entry.
//
// Kind decides how a value is validated and how the panel renders it:
// "secret" and "generated" are never sent to the browser; "generated" can
// also be minted here. Services lists the compose services that read the
// variable, which is what the host recreates after a change.
type EnvVar struct {
Name string `json:"name"`
Group string `json:"group"`
Purpose string `json:"purpose"`
Kind string `json:"kind"`
Editable bool `json:"editable"`
LockedReason string `json:"lockedReason,omitempty"`
Services []string `json:"services,omitempty"`
DocsURL string `json:"docsUrl,omitempty"`
Options []string `json:"options,omitempty"`
Warning string `json:"warning,omitempty"`
}
// Secret reports whether the variable's value must stay on the server.
func (v EnvVar) Secret() bool {
return v.Kind == "secret" || v.Kind == "generated"
}
// EnvManager turns an edit made in the admin panel into a request for the
// host to apply.
//
// The backend deliberately cannot write .env or restart containers itself:
// it is the internet-facing process, and either ability would make a
// compromised admin session a compromised host. Instead it validates the
// change and leaves request.json in the shared directory; the host's watcher
// (env-apply/apply.py, run by a systemd path unit) merges it into .env,
// recreates the affected containers and reports back through status.json.
type EnvManager struct {
dir string
vars []EnvVar
byName map[string]EnvVar
// Serialises Submit and Cancel so two requests cannot interleave their
// read-merge-write of request.json. The host is a separate process and is
// handled by renames instead (see Submit).
mu sync.Mutex
}
// envApplyRequest is request.json. Clearing a variable is setting it to "".
type envApplyRequest struct {
ID string `json:"id"`
RequestedAt time.Time `json:"requestedAt"`
Set map[string]string `json:"set"`
}
// EnvApplyStatus is what the panel polls. State is one of idle, pending
// (request written, host has not picked it up), applying, applied, failed.
type EnvApplyStatus struct {
State string `json:"state"`
ID string `json:"id,omitempty"`
// When the state was entered.
At *time.Time `json:"at,omitempty"`
// Names in a pending request. Values are never reported.
Pending []string `json:"pending,omitempty"`
Services []string `json:"services,omitempty"`
Changed []string `json:"changed,omitempty"`
Output string `json:"output,omitempty"`
// False once a request has waited long enough that nothing on the host
// can be watching for it (a dev machine, or the units not installed).
Watcher bool `json:"watcher"`
}
const (
envRequestFile = "request.json"
envStatusFile = "status.json"
// The path unit fires within a second, so a request still unclaimed
// after this long means there is no watcher.
envWatcherGrace = 15 * time.Second
// An "applying" status older than this is a host script that died
// mid-run; stop letting it block new requests.
envApplyingStale = 5 * time.Minute
envValueMaxLen = 4096
)
// ErrEnvApplying is returned by Submit while the host is mid-apply.
var ErrEnvApplying = errors.New("a change is being applied; try again in a moment")
// NewEnvManager parses the embedded registry. dir need not exist yet: without
// the bind mount, reads report "idle" and Submit fails with a clear error.
func NewEnvManager(dir string) (*EnvManager, error) {
var vars []EnvVar
if err := json.Unmarshal(envRegistryJSON, &vars); err != nil {
return nil, fmt.Errorf("parsing env registry: %w", err)
}
byName := make(map[string]EnvVar, len(vars))
for _, v := range vars {
if _, dup := byName[v.Name]; dup {
return nil, fmt.Errorf("env registry lists %s twice", v.Name)
}
byName[v.Name] = v
}
return &EnvManager{dir: dir, vars: vars, byName: byName}, nil
}
// Vars returns the registry in file order, which is the order the panel
// shows.
func (m *EnvManager) Vars() []EnvVar {
return m.vars
}
// Validate checks one proposed value. The empty string clears the variable
// and is always acceptable for an editable one.
//
// The control-character rule is the security-relevant one: .env is line
// oriented, so a newline in a value would let an edit to an allowed variable
// write a second, arbitrary one.
func (m *EnvManager) Validate(name, value string) error {
v, ok := m.byName[name]
if !ok {
return fmt.Errorf("%s is not a known variable", name)
}
if !v.Editable {
return fmt.Errorf("%s cannot be changed from the panel", name)
}
if value == "" {
return nil
}
if len(value) > envValueMaxLen {
return fmt.Errorf("%s is too long", name)
}
for _, r := range value {
if r < 0x20 || r == 0x7f {
return fmt.Errorf("%s contains a control character", name)
}
}
// The host writes values single-quoted, and a dotenv single-quoted
// string has no escape for the quote itself.
if strings.ContainsRune(value, '\'') {
return fmt.Errorf("%s cannot contain a single quote", name)
}
switch v.Kind {
case "url":
u, err := url.Parse(value)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return fmt.Errorf("%s must be an http(s) URL", name)
}
case "bool":
if value != "true" && value != "false" {
return fmt.Errorf("%s must be true or false", name)
}
case "duration":
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
return fmt.Errorf("%s must be a duration such as 30m", name)
}
case "number":
if n, err := strconv.Atoi(value); err != nil || n <= 0 {
return fmt.Errorf("%s must be a positive whole number", name)
}
case "enum":
if !slices.Contains(v.Options, value) {
return fmt.Errorf("%s must be one of: %s", name, strings.Join(v.Options, ", "))
}
}
return nil
}
// ServicesFor is the set of compose services a change to names recreates.
// The backend is always among them: the panel reports state from this
// process's own environment, which only a recreate refreshes.
func (m *EnvManager) ServicesFor(names []string) []string {
services := []string{"backend"}
for _, name := range names {
for _, s := range m.byName[name].Services {
if !slices.Contains(services, s) {
services = append(services, s)
}
}
}
slices.Sort(services)
return services
}
// Submit validates a batch of edits and hands it to the host. set holds
// explicit values ("" clears); generate names variables to mint a random
// value for. The generated values are returned and exist nowhere else on
// this side — the caller shows them once.
//
// Nothing is written unless the whole batch is valid.
//
// A request the host has not yet claimed is merged into rather than
// refused, so edits are not stuck behind an absent watcher. The host claims
// a request by renaming it, so the worst a race can do is hand it values it
// has already applied.
func (m *EnvManager) Submit(set map[string]string, generate []string) (map[string]string, []string, error) {
changes := make(map[string]string, len(set)+len(generate))
for name, value := range set {
value = strings.TrimSpace(value)
if err := m.Validate(name, value); err != nil {
return nil, nil, err
}
changes[name] = value
}
generated := make(map[string]string, len(generate))
for _, name := range generate {
if v, ok := m.byName[name]; !ok || !v.Editable || v.Kind != "generated" {
return nil, nil, fmt.Errorf("%s cannot be generated", name)
}
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return nil, nil, err
}
generated[name] = hex.EncodeToString(raw)
changes[name] = generated[name]
}
if len(changes) == 0 {
return nil, nil, errors.New("no changes given")
}
m.mu.Lock()
defer m.mu.Unlock()
if status := m.readStatus(); status != nil && status.State == "applying" &&
status.At != nil && time.Since(*status.At) < envApplyingStale {
return nil, nil, ErrEnvApplying
}
request := envApplyRequest{Set: changes}
if pending := m.readRequest(); pending != nil {
for name, value := range pending.Set {
if _, replaced := changes[name]; !replaced {
request.Set[name] = value
}
}
}
id := make([]byte, 8)
if _, err := rand.Read(id); err != nil {
return nil, nil, err
}
request.ID = hex.EncodeToString(id)
request.RequestedAt = time.Now().UTC()
if err := m.writeRequest(&request); err != nil {
return nil, nil, err
}
names := make([]string, 0, len(request.Set))
for name := range request.Set {
names = append(names, name)
}
return generated, m.ServicesFor(names), nil
}
// writeRequest writes request.json so the host only ever sees a complete
// file it can read: temp name, owner and mode set, then rename.
//
// This process runs as root in the container while the host script runs as
// the checkout's owner, so the file is handed to whoever owns the shared
// directory. 0600 because it holds the new secrets in the clear until the
// host consumes it.
func (m *EnvManager) writeRequest(request *envApplyRequest) error {
info, err := os.Stat(m.dir)
if err != nil {
return fmt.Errorf("the env-apply directory is not mounted: %w", err)
}
data, err := json.Marshal(request)
if err != nil {
return err
}
tmp := filepath.Join(m.dir, envRequestFile+".tmp")
if err := os.WriteFile(tmp, data, 0600); err != nil {
return fmt.Errorf("writing env request: %w", err)
}
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
if err := os.Chown(tmp, int(stat.Uid), int(stat.Gid)); err != nil {
os.Remove(tmp)
return fmt.Errorf("handing env request to the host user: %w", err)
}
}
if err := os.Rename(tmp, filepath.Join(m.dir, envRequestFile)); err != nil {
os.Remove(tmp)
return fmt.Errorf("writing env request: %w", err)
}
return nil
}
// Cancel withdraws a request the host has not claimed. Once claimed it is
// too late, and this is a no-op.
func (m *EnvManager) Cancel() error {
m.mu.Lock()
defer m.mu.Unlock()
if err := os.Remove(filepath.Join(m.dir, envRequestFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("removing env request: %w", err)
}
return nil
}
func (m *EnvManager) readRequest() *envApplyRequest {
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
if err != nil {
return nil
}
var request envApplyRequest
if json.Unmarshal(raw, &request) != nil {
return nil
}
return &request
}
func (m *EnvManager) readStatus() *EnvApplyStatus {
raw, err := os.ReadFile(filepath.Join(m.dir, envStatusFile))
if err != nil {
return nil
}
var status EnvApplyStatus
if json.Unmarshal(raw, &status) != nil {
return nil
}
return &status
}
// Status reports where the latest change has got to. An unclaimed request
// takes precedence over status.json, which then describes an older change.
func (m *EnvManager) Status() EnvApplyStatus {
if request := m.readRequest(); request != nil {
names := make([]string, 0, len(request.Set))
for name := range request.Set {
names = append(names, name)
}
slices.Sort(names)
at := request.RequestedAt
return EnvApplyStatus{
State: "pending",
ID: request.ID,
At: &at,
Pending: names,
Services: m.ServicesFor(names),
Watcher: time.Since(at) < envWatcherGrace,
}
}
if status := m.readStatus(); status != nil {
status.Watcher = true
return *status
}
return EnvApplyStatus{State: "idle", Watcher: true}
}
-374
View File
@@ -1,374 +0,0 @@
package services
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"time"
)
func newEnvManager(t *testing.T) *EnvManager {
t.Helper()
m, err := NewEnvManager(t.TempDir())
if err != nil {
t.Fatalf("NewEnvManager: %v", err)
}
return m
}
func readRequestFile(t *testing.T, m *EnvManager) envApplyRequest {
t.Helper()
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
if err != nil {
t.Fatalf("reading request: %v", err)
}
var request envApplyRequest
if err := json.Unmarshal(raw, &request); err != nil {
t.Fatalf("parsing request: %v", err)
}
return request
}
// The registry and .env.example describe the same variables; a name added to
// one and not the other is either invisible in the panel or undocumented.
func TestEnvRegistryMatchesEnvExample(t *testing.T) {
raw, err := os.ReadFile("../../.env.example")
if err != nil {
t.Fatalf("reading .env.example: %v", err)
}
var example []string
for _, match := range regexp.MustCompile(`(?m)^([A-Z][A-Z0-9_]*)=`).FindAllStringSubmatch(string(raw), -1) {
example = append(example, match[1])
}
var registry []string
for _, v := range newEnvManager(t).Vars() {
registry = append(registry, v.Name)
}
for _, name := range example {
if !slices.Contains(registry, name) {
t.Errorf("%s is in .env.example but not in env_registry.json", name)
}
}
for _, name := range registry {
if !slices.Contains(example, name) {
t.Errorf("%s is in env_registry.json but not in .env.example", name)
}
}
}
// composeServiceEnv returns the variable names in the `environment:` list of
// one service in docker-compose.yml.
//
// It reads the file as text rather than through a YAML library — there is
// none among this module's direct dependencies, and the shape needed is
// narrow: a two-space-indented `<service>:` key under `services:`, a
// four-space-indented `environment:` under it, and `- NAME=value` items. If
// the compose file is ever restructured so that this finds nothing, the test
// below fails loudly rather than passing on an empty list.
func composeServiceEnv(t *testing.T, service string) []string {
t.Helper()
raw, err := os.ReadFile("../../docker-compose.yml")
if err != nil {
t.Fatalf("reading docker-compose.yml: %v", err)
}
item := regexp.MustCompile(`^ - ["']?([A-Z][A-Z0-9_]*)(=|["']?\s*$)`)
var names []string
inService, inEnvironment := false, false
for _, line := range strings.Split(string(raw), "\n") {
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
indent := len(line) - len(strings.TrimLeft(line, " "))
switch {
case indent <= 2:
// A new service (or a top-level key) ends the block.
inService, inEnvironment = line == " "+service+":", false
case inService && indent == 4:
inEnvironment = trimmed == "environment:"
case inService && inEnvironment:
match := item.FindStringSubmatch(line)
if match == nil {
t.Fatalf("%s.environment has an entry this test cannot read: %q", service, line)
}
names = append(names, match[1])
}
}
if len(names) == 0 {
t.Fatalf("found no %s.environment list in docker-compose.yml; has the file's layout changed?", service)
}
return names
}
// explicitEnvServices are the containers given an explicit `environment:`
// list instead of the whole .env, so that they never hold the database
// password or the JWT secret: the Python service, and the job tracker (an
// image from its own repo, which gets its own database role besides). The
// cost is a third place a new variable for one of them has to be added — the
// registry, .env.example and that list — and forgetting the third is silent:
// the variable is simply empty inside the container.
var explicitEnvServices = []string{"python", "jobs"}
// So the registry's claim "this service reads this" and the compose list must
// agree, in both directions:
//
// - a variable the registry says the service reads must be passed to it;
// - an editable variable that is passed to it must say so in the registry,
// or changing it in the admin panel would not recreate the container.
//
// Locked variables are exempt from the second rule. They are never applied
// through the panel, so the registry gives none of them a services list
// (PYTHON_PORT is passed to python and is one of these). Names in the compose
// list that are not registry variables at all, such as the literal ROOT_PATH
// or the jobs service's composed DATABASE_URL, are not this test's business.
func TestEnvRegistryMatchesComposeEnvironments(t *testing.T) {
registry := map[string]EnvVar{}
for _, v := range newEnvManager(t).Vars() {
registry[v.Name] = v
}
for _, service := range explicitEnvServices {
compose := composeServiceEnv(t, service)
for _, v := range registry {
if slices.Contains(v.Services, service) && !slices.Contains(compose, v.Name) {
t.Errorf("%s lists the %s service in env_registry.json but is not in "+
"%s.environment in docker-compose.yml, so the container never receives it", v.Name, service, service)
}
}
for _, name := range compose {
v, known := registry[name]
if !known || !v.Editable {
continue
}
if !slices.Contains(v.Services, service) {
t.Errorf("%s is passed to the %s service in docker-compose.yml but env_registry.json "+
"does not list %s among its services, so editing it would not recreate the container", name, service, service)
}
}
}
}
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
for _, v := range newEnvManager(t).Vars() {
if !slices.Contains(kinds, v.Kind) {
t.Errorf("%s has unknown kind %q", v.Name, v.Kind)
}
if v.Group == "" || v.Purpose == "" {
t.Errorf("%s is missing its group or purpose", v.Name)
}
if v.Editable && len(v.Services) == 0 {
t.Errorf("%s is editable but names no service to recreate", v.Name)
}
if !v.Editable && v.LockedReason == "" {
t.Errorf("%s is locked without a reason", v.Name)
}
if v.Kind == "enum" && len(v.Options) == 0 {
t.Errorf("%s is an enum with no options", v.Name)
}
}
}
func TestEnvValidate(t *testing.T) {
m := newEnvManager(t)
cases := []struct {
name, value string
ok bool
}{
{"CLAUDE_API_KEY", "sk-ant-abc123", true},
{"CLAUDE_API_KEY", "", true},
// The injection case: a newline would start a second variable.
{"CLAUDE_API_KEY", "x\nPOSTGRES_PASSWORD=owned", false},
{"CLAUDE_API_KEY", "x\rY", false},
{"CLAUDE_API_KEY", "it's", false},
{"CLAUDE_API_KEY", strings.Repeat("a", envValueMaxLen+1), false},
{"POSTGRES_PASSWORD", "anything", false},
{"NOT_A_VARIABLE", "anything", false},
{"EMAIL_BACKEND", "graph", true},
{"EMAIL_BACKEND", "pop3", false},
{"EMAIL_SYNC_INTERVAL", "45m", true},
{"EMAIL_SYNC_INTERVAL", "soon", false},
{"EMAIL_SYNC_INTERVAL", "-5m", false},
{"EMAIL_SYNC_ENABLED", "true", true},
{"EMAIL_SYNC_ENABLED", "yes", false},
{"IMAP_PORT", "993", true},
{"IMAP_PORT", "imaps", false},
{"SPOTIFY_REDIRECT_URI", "https://example.com/api/spotify/callback", true},
{"SPOTIFY_REDIRECT_URI", "example.com/callback", false},
{"SPOTIFY_REDIRECT_URI", "javascript:alert(1)", false},
}
for _, c := range cases {
err := m.Validate(c.name, c.value)
if (err == nil) != c.ok {
t.Errorf("Validate(%s, %q) error = %v, want ok = %v", c.name, c.value, err, c.ok)
}
}
}
func TestEnvSubmitWritesRequest(t *testing.T) {
m := newEnvManager(t)
generated, services, err := m.Submit(
map[string]string{"TFL_APP_KEY": " tfl-key ", "STEAM_ID": ""},
[]string{"ICECAST_RELAY_PASSWORD"},
)
if err != nil {
t.Fatalf("Submit: %v", err)
}
if len(generated["ICECAST_RELAY_PASSWORD"]) != 64 {
t.Fatalf("generated value = %q, want 64 hex characters", generated["ICECAST_RELAY_PASSWORD"])
}
if want := []string{"backend", "icecast2", "python"}; !slices.Equal(services, want) {
t.Fatalf("services = %v, want %v", services, want)
}
request := readRequestFile(t, m)
want := map[string]string{
"TFL_APP_KEY": "tfl-key", // surrounding whitespace from a paste is dropped
"STEAM_ID": "",
"ICECAST_RELAY_PASSWORD": generated["ICECAST_RELAY_PASSWORD"],
}
if len(request.Set) != len(want) {
t.Fatalf("request.Set = %v, want %v", request.Set, want)
}
for name, value := range want {
if request.Set[name] != value {
t.Errorf("request.Set[%s] = %q, want %q", name, request.Set[name], value)
}
}
info, err := os.Stat(filepath.Join(m.dir, envRequestFile))
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0600 {
t.Errorf("request mode = %v, want 0600: it holds secrets in the clear", info.Mode().Perm())
}
}
func TestEnvSubmitRejectsWholeBatch(t *testing.T) {
m := newEnvManager(t)
cases := []struct {
name string
set map[string]string
generate []string
}{
{"one bad value", map[string]string{"STEAM_ID": "1", "EMAIL_BACKEND": "pop3"}, nil},
{"a locked variable", map[string]string{"STEAM_ID": "1", "DOMAIN": "evil.example"}, nil},
{"generating a pasted secret", nil, []string{"CLAUDE_API_KEY"}},
{"generating a locked secret", nil, []string{"POSTGRES_PASSWORD"}},
{"nothing at all", nil, nil},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if _, _, err := m.Submit(c.set, c.generate); err == nil {
t.Fatal("Submit succeeded, want an error")
}
if _, err := os.Stat(filepath.Join(m.dir, envRequestFile)); !errors.Is(err, os.ErrNotExist) {
t.Fatal("a rejected batch left a request file behind")
}
})
}
}
func TestEnvSubmitMergesUnclaimedRequest(t *testing.T) {
m := newEnvManager(t)
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1", "TFL_APP_KEY": "old"}, nil); err != nil {
t.Fatalf("first Submit: %v", err)
}
if _, _, err := m.Submit(map[string]string{"TFL_APP_KEY": "new"}, nil); err != nil {
t.Fatalf("second Submit: %v", err)
}
request := readRequestFile(t, m)
if request.Set["STEAM_ID"] != "1" || request.Set["TFL_APP_KEY"] != "new" {
t.Fatalf("merged request = %v, want the earlier STEAM_ID kept and TFL_APP_KEY replaced", request.Set)
}
}
func TestEnvSubmitWithoutMount(t *testing.T) {
m, err := NewEnvManager(filepath.Join(t.TempDir(), "absent"))
if err != nil {
t.Fatalf("NewEnvManager: %v", err)
}
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err == nil {
t.Fatal("Submit succeeded with no shared directory")
}
if got := m.Status().State; got != "idle" {
t.Fatalf("Status().State = %q, want idle", got)
}
}
func writeStatusFile(t *testing.T, m *EnvManager, state string, at time.Time) {
t.Helper()
data, _ := json.Marshal(EnvApplyStatus{State: state, ID: "abc", At: &at})
if err := os.WriteFile(filepath.Join(m.dir, envStatusFile), data, 0644); err != nil {
t.Fatal(err)
}
}
func TestEnvStatus(t *testing.T) {
m := newEnvManager(t)
if got := m.Status(); got.State != "idle" || !got.Watcher {
t.Fatalf("fresh status = %+v, want idle with watcher assumed", got)
}
writeStatusFile(t, m, "applied", time.Now())
if got := m.Status(); got.State != "applied" || got.ID != "abc" {
t.Fatalf("status = %+v, want the host's applied report", got)
}
// An unclaimed request outranks the report of an older change.
if _, _, err := m.Submit(map[string]string{"CLAUDE_API_KEY": "sk-secret"}, nil); err != nil {
t.Fatalf("Submit: %v", err)
}
got := m.Status()
if got.State != "pending" || !slices.Equal(got.Pending, []string{"CLAUDE_API_KEY"}) || !got.Watcher {
t.Fatalf("status = %+v, want pending CLAUDE_API_KEY", got)
}
if encoded, _ := json.Marshal(got); strings.Contains(string(encoded), "sk-secret") {
t.Fatal("the status leaks a pending value")
}
// Backdate the request past the grace period: nothing is watching.
request := readRequestFile(t, m)
request.RequestedAt = time.Now().Add(-2 * envWatcherGrace)
if err := m.writeRequest(&request); err != nil {
t.Fatal(err)
}
if m.Status().Watcher {
t.Fatal("a long-unclaimed request still reports a watcher")
}
if err := m.Cancel(); err != nil {
t.Fatalf("Cancel: %v", err)
}
if got := m.Status().State; got != "applied" {
t.Fatalf("after Cancel state = %q, want the earlier applied report", got)
}
if err := m.Cancel(); err != nil {
t.Fatalf("Cancel with nothing pending: %v", err)
}
}
func TestEnvSubmitRefusedWhileApplying(t *testing.T) {
m := newEnvManager(t)
writeStatusFile(t, m, "applying", time.Now())
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); !errors.Is(err, ErrEnvApplying) {
t.Fatalf("Submit error = %v, want ErrEnvApplying", err)
}
// A host script that died mid-run must not block the panel for ever.
writeStatusFile(t, m, "applying", time.Now().Add(-2*envApplyingStale))
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err != nil {
t.Fatalf("Submit after a stale applying status: %v", err)
}
}
-77
View File
@@ -1,77 +0,0 @@
[
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls: the job tracker (lead scorer, email classifier, posting reader) and the Python service (rowing photo reader)", "kind": "secret", "editable": true, "services": ["python", "jobs"], "docsUrl": "https://console.anthropic.com/settings/keys"},
{"name": "CLAUDE_MODEL", "group": "API keys", "purpose": "Model for every Claude call: lead scoring, email classifier, posting reader (job tracker), rowing photo reader (Python). Blank uses claude-sonnet-5-5. Rough cost per million tokens in/out: Haiku $1/$5, Sonnet $2/$10, Opus $4/$20", "kind": "enum", "options": ["claude-haiku-4-5", "claude-sonnet-5-5", "claude-opus-5-5"], "editable": true, "services": ["python", "jobs"]},
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
{"name": "SPOTIFY_CLIENT_ID", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
{"name": "SPOTIFY_CLIENT_SECRET", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
{"name": "SPOTIFY_REDIRECT_URI", "group": "Spotify", "purpose": "Must match the URI registered in the Spotify dashboard exactly", "kind": "url", "editable": true, "services": ["backend"]},
{"name": "SPOTIFY_AUTH_STATE", "group": "Spotify", "purpose": "Former fixed OAuth state", "kind": "secret", "editable": false, "lockedReason": "No longer read: the OAuth state is a per-request nonce."},
{"name": "EMAIL_BACKEND", "group": "Email ingest", "purpose": "Mail source for the email pipeline", "kind": "enum", "options": ["graph", "imap"], "editable": true, "services": ["jobs"]},
{"name": "EMAIL_SYNC_ENABLED", "group": "Email ingest", "purpose": "Run the periodic email sync", "kind": "bool", "editable": true, "services": ["jobs"]},
{"name": "EMAIL_SYNC_INTERVAL", "group": "Email ingest", "purpose": "Time between syncs, as a Go duration such as 30m (default 30m)", "kind": "duration", "editable": true, "services": ["jobs"]},
{"name": "MSGRAPH_CLIENT_ID", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "text", "editable": true, "services": ["jobs"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
{"name": "MSGRAPH_CLIENT_SECRET", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "secret", "editable": true, "services": ["jobs"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
{"name": "MSGRAPH_TENANT_ID", "group": "Email ingest", "purpose": "\"consumers\" for a personal outlook.com account", "kind": "text", "editable": true, "services": ["jobs"]},
{"name": "MSGRAPH_REDIRECT_URI", "group": "Email ingest", "purpose": "OAuth callback: https://<domain>/jobs/api/email/callback, registered in Entra", "kind": "url", "editable": true, "services": ["jobs"]},
{"name": "IMAP_HOST", "group": "Email ingest", "purpose": "IMAP fallback server", "kind": "text", "editable": true, "services": ["jobs"]},
{"name": "IMAP_PORT", "group": "Email ingest", "purpose": "IMAP fallback port (993)", "kind": "number", "editable": true, "services": ["jobs"]},
{"name": "IMAP_EMAIL", "group": "Email ingest", "purpose": "IMAP fallback account", "kind": "text", "editable": true, "services": ["jobs"]},
{"name": "IMAP_PASSWORD", "group": "Email ingest", "purpose": "App-specific password, not the account password", "kind": "secret", "editable": true, "services": ["jobs"]},
{"name": "JOB_LEADS_ENABLED", "group": "Job leads", "purpose": "Run the periodic job-lead fetch; \"Check now\" on /jobs/leads works either way", "kind": "bool", "editable": true, "services": ["jobs"]},
{"name": "JOB_LEADS_INTERVAL", "group": "Job leads", "purpose": "Time between fetches, as a Go duration such as 6h (default 6h)", "kind": "duration", "editable": true, "services": ["jobs"]},
{"name": "ADZUNA_APP_ID", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "text", "editable": true, "services": ["jobs"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
{"name": "ADZUNA_APP_KEY", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "secret", "editable": true, "services": ["jobs"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
{"name": "REED_API_KEY", "group": "Job leads", "purpose": "Reed job search, for reed lead sources", "kind": "secret", "editable": true, "services": ["jobs"], "docsUrl": "https://www.reed.co.uk/developers/jobseeker"},
{"name": "ICECAST_SOURCE_PASSWORD", "group": "Radio", "purpose": "Liquidsoap to Icecast, and live broadcasters to the harbor port", "kind": "generated", "editable": true, "services": ["icecast2"], "warning": "Live broadcasting clients must be given the new password."},
{"name": "ICECAST_RELAY_PASSWORD", "group": "Radio", "purpose": "Icecast relay clients", "kind": "generated", "editable": true, "services": ["icecast2"]},
{"name": "ICECAST_ADMIN_USER", "group": "Radio", "purpose": "Icecast web admin login", "kind": "text", "editable": true, "services": ["icecast2"]},
{"name": "ICECAST_ADMIN_PASSWORD", "group": "Radio", "purpose": "Icecast web admin login", "kind": "generated", "editable": true, "services": ["icecast2"]},
{"name": "BACKEND_SECRET", "group": "Backend", "purpose": "Signs the JWTs in the auth cookies", "kind": "generated", "editable": true, "services": ["backend"], "warning": "Rotating this logs everyone out, including you."},
{"name": "SILVERBULLET_GIT_INTERVAL", "group": "Backend", "purpose": "Seconds between notes commit/push cycles (default 300)", "kind": "number", "editable": true, "services": ["silverbullet-git"]},
{"name": "DOMAIN", "group": "Infrastructure", "purpose": "Apex domain: TLS certificate, cookie domain, nginx server name", "kind": "text", "editable": false, "lockedReason": "Changing the domain needs a new certificate and a full restart."},
{"name": "EMAIL", "group": "Infrastructure", "purpose": "Let's Encrypt account address", "kind": "text", "editable": false, "lockedReason": "Only read by certbot when it registers the account."},
{"name": "OBSIDIAN_DIR", "group": "Infrastructure", "purpose": "Host path of the notes vault", "kind": "text", "editable": false, "lockedReason": "A bind-mount path: a wrong value stops the stack from starting."},
{"name": "SEED_DB", "group": "Infrastructure", "purpose": "Development-only test data switch", "kind": "bool", "editable": false, "lockedReason": "Would inject test data into the live site."},
{"name": "BACKEND_HOST", "group": "Infrastructure", "purpose": "Backend container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
{"name": "BACKEND_PORT", "group": "Infrastructure", "purpose": "Backend listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
{"name": "BACKEND_ENDPOINT", "group": "Infrastructure", "purpose": "URL prefix nginx mounts the API at", "kind": "text", "editable": false, "lockedReason": "The Vue app assumes /api."},
{"name": "PYTHON_HOST", "group": "Infrastructure", "purpose": "Python container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
{"name": "PYTHON_PORT", "group": "Infrastructure", "purpose": "Python listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
{"name": "JOBS_IMAGE_TAG", "group": "Infrastructure", "purpose": "Job tracker image tag to run (default latest)", "kind": "text", "editable": false, "lockedReason": "Changing it needs a pull: docker compose pull jobs && docker compose up -d jobs."},
{"name": "ICECAST_HOST", "group": "Infrastructure", "purpose": "Icecast container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
{"name": "ICECAST_PORT", "group": "Infrastructure", "purpose": "Icecast listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
{"name": "ICECAST_MOUNT", "group": "Infrastructure", "purpose": "Listener-facing stream mount", "kind": "text", "editable": false, "lockedReason": "The player and nginx both assume this mount."},
{"name": "LIQUIDSOAP_HARBOR_MOUNT", "group": "Infrastructure", "purpose": "Live broadcast mount", "kind": "text", "editable": false, "lockedReason": "Broadcasting clients are configured against it."},
{"name": "LIQUIDSOAP_HARBOR_PORT", "group": "Infrastructure", "purpose": "Live broadcast port, published to the host", "kind": "text", "editable": false, "lockedReason": "A published port: changing it needs the router and clients updated."},
{"name": "SILVERBULLET_HOST", "group": "Infrastructure", "purpose": "Notes editor container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
{"name": "SILVERBULLET_PORT", "group": "Infrastructure", "purpose": "Notes editor port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
{"name": "SILVERBULLET_PUBLIC_HOST", "group": "Infrastructure", "purpose": "Public notes container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
{"name": "SILVERBULLET_PUBLIC_PORT", "group": "Infrastructure", "purpose": "Public notes port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
{"name": "POSTGRES_HOST", "group": "Database", "purpose": "Database container name", "kind": "text", "editable": false, "lockedReason": "Renames the database container."},
{"name": "POSTGRES_PORT", "group": "Database", "purpose": "Database port", "kind": "text", "editable": false, "lockedReason": "Every client of the database assumes it."},
{"name": "POSTGRES_USER", "group": "Database", "purpose": "Database role", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
{"name": "POSTGRES_PASSWORD", "group": "Database", "purpose": "Database password", "kind": "secret", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
{"name": "POSTGRES_DB", "group": "Database", "purpose": "Backend database name", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised."},
{"name": "POSTGRES_GITEA_DB", "group": "Database", "purpose": "Gitea database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on a fresh volume."},
{"name": "POSTGRES_JOBS_DB", "group": "Database", "purpose": "Job tracker database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on first install; see the job-tracker README."},
{"name": "POSTGRES_JOBS_USER", "group": "Database", "purpose": "Job tracker database role", "kind": "text", "editable": false, "lockedReason": "Created by hand on first install; changing it here locks the tracker out."},
{"name": "POSTGRES_JOBS_PASSWORD", "group": "Database", "purpose": "Job tracker database password", "kind": "secret", "editable": false, "lockedReason": "Set on the role by hand; changing it here locks the tracker out."},
{"name": "GITEA_HOST", "group": "Gitea", "purpose": "Gitea container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
{"name": "GITEA_PORT", "group": "Gitea", "purpose": "Gitea HTTP port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
{"name": "GITEA_INTERNAL_TOKEN", "group": "Gitea", "purpose": "Gitea internal API token", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
{"name": "GITEA_LFS_JWT_SECRET", "group": "Gitea", "purpose": "Gitea LFS token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
{"name": "GITEA_OAUTH2_JWT_SECRET", "group": "Gitea", "purpose": "Gitea OAuth2 token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
{"name": "GITEA_RUNNER_HOST", "group": "Gitea", "purpose": "Gitea URL the Actions runner registers against", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
{"name": "GITEA_RUNNER_NAME", "group": "Gitea", "purpose": "Actions runner name", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
{"name": "GITEA_RUNNER_REGISTRATION_TOKEN", "group": "Gitea", "purpose": "Single-use runner registration token", "kind": "secret", "editable": false, "lockedReason": "Single-use, and ignored once the runner is registered."}
]
+49
View File
@@ -0,0 +1,49 @@
package services
import (
"slices"
"adam-french.co.uk/backend/models"
)
// Per-service permissions: how a non-admin account is let into one gated
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
Label string
Path string
}
// PermissionTypes is the full set of grantable permissions, in display order.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
}
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key
})
}
// HasPermission reports whether user may use the service gated on key. It
// reads the row, not a token, so Admin here is the current database value.
func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key)
}
+54
View File
@@ -0,0 +1,54 @@
package services
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidPermission(t *testing.T) {
for _, p := range PermissionTypes {
if !ValidPermission(p.Key) {
t.Errorf("listed key %q reported invalid", p.Key)
}
}
for _, key := range []string{"", "admin", "Receipt", "receipt "} {
if ValidPermission(key) {
t.Errorf("unlisted key %q reported valid", key)
}
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
if seen[p.Key] {
t.Errorf("duplicate key %q", p.Key)
}
seen[p.Key] = true
for _, r := range p.Key {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
t.Errorf("key %q has %q; use lowercase letters, digits and '-'", p.Key, r)
}
}
}
}
func TestHasPermission(t *testing.T) {
cases := []struct {
name string
user models.User
want bool
}{
{"admin passes without a grant", models.User{Admin: true}, true},
{"granted user passes", models.User{Permissions: []string{"receipt"}}, true},
{"other grant does not count", models.User{Permissions: []string{"other"}}, false},
{"no grants (NULL column) fails", models.User{}, false},
}
for _, c := range cases {
if got := HasPermission(&c.user, "receipt"); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
+6 -1
View File
@@ -29,6 +29,11 @@ var logQuietDrop = map[string]bool{
"/auth/check": true, // front-end session check
}
// logQuietDropPrefix is the permission gate's auth_request subrequest
// (/auth/validate/<key>), dropped on 2xx for the same reason as
// /auth/validate-admin above: it repeats on every request to a gated page.
const logQuietDropPrefix = "/auth/validate/"
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
// signature so it plugs into gin.LoggerWithFormatter.
func TrafficLogFormatter(params gin.LogFormatterParams) string {
@@ -63,7 +68,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
// is still interesting (an expired session raging against refresh, a
// broken admin gate) and is kept.
if logQuietDrop[path] && params.StatusCode < 400 {
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
return ""
}
+9
View File
@@ -25,6 +25,15 @@ func TestTrafficFormatterDropsQuietHeartbeats(t *testing.T) {
}
}
func TestTrafficFormatterDropsPermissionGate(t *testing.T) {
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 200, "172.28.0.6", time.Millisecond)); out != "" {
t.Fatalf("permission-gate 200 should be dropped, got %q", out)
}
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 403, "172.28.0.6", time.Millisecond)); out == "" {
t.Fatal("a refused permission check must stay visible")
}
}
func TestTrafficFormatterKeepsHeartbeatFailures(t *testing.T) {
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 401, "172.28.0.6", time.Millisecond))
if out == "" {
+409
View File
@@ -0,0 +1,409 @@
package services
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// Uploaded files: everything the site stores from a user and serves back at
// /uploads/. One entry point for any handler that takes a file:
//
// url, err := store.Uploads.Save(ctx, fileHeader, private)
//
// Save validates the file against UploadTypes and MaxUploadSize, gives it a
// random name, stores it, and returns the URL to put in the page. An
// *UploadError is the uploader's fault and its message is safe to show them;
// any other error is ours (log it, answer 500).
//
// WHERE FILES GO
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
// the `uploads` volume as a fallback for when Garage refuses a write. nginx
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (nginx.conf.template), so the URL is the same wherever the
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
// the only store.
// Private files (admin-only chat attachments) always go to the volume, under
// /uploads/private/, which nginx gates behind an admin check. nginx can't
// sign S3 requests, so it has no way to gate a bucket.
//
// Everything public is reachable by anyone who has the URL, with no login.
// That is why the type checks below are strict, and why names are random.
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
// disk or the bucket; nginx rate-limits the route as well.
const MaxUploadSize = 10 << 20 // 10MB
// UploadType describes one allowed file extension.
type UploadType struct {
// ContentType is stored with the file and served back with it. Garage
// returns exactly this, and the browser renders by it: nginx adds
// `nosniff`, so a wrong type means the file doesn't display.
ContentType string
// SniffPrefix is what http.DetectContentType must report for the file's
// first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty
// means "not checked": DetectContentType is too unreliable for audio and
// gif files, and checking would reject legitimate ones.
SniffPrefix string
}
// UploadTypes is the allow-list, keyed by lower-cased extension with its dot.
// Nothing a browser would execute or render as markup (.html, .svg, .js, ...)
// may ever be added: these files are served from our own origin. The
// frontend's file pickers (vue/src/uploads.js, ACCEPT) list the same types.
var UploadTypes = map[string]UploadType{
".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".png": {ContentType: "image/png", SniffPrefix: "image/"},
".gif": {ContentType: "image/gif"},
".webp": {ContentType: "image/webp", SniffPrefix: "image/"},
".mp4": {ContentType: "video/mp4", SniffPrefix: "video/"},
".webm": {ContentType: "video/webm", SniffPrefix: "video/"},
".mp3": {ContentType: "audio/mpeg"},
".ogg": {ContentType: "audio/ogg"},
".pdf": {ContentType: "application/pdf", SniffPrefix: "application/pdf"},
".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"},
}
// UploadError is a rejected upload: the uploader's mistake, with a message
// meant for them. The handler answers 400 with it.
type UploadError struct{ Message string }
func (e *UploadError) Error() string { return e.Message }
var (
ErrUploadTooLarge = &UploadError{"file too large (the limit is 10MB)"}
ErrUploadType = &UploadError{"file type not allowed"}
ErrUploadContent = &UploadError{"file content does not match extension"}
ErrUploadUnreadable = &UploadError{"failed to read file content"}
)
// Uploads stores files. Build it with NewUploads.
type Uploads struct {
public FileStore
private FileStore
}
// URL prefixes the files are served under; nginx owns both paths.
const (
publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/"
)
// NewUploads picks the stores. publicDir and privateDir are directories on the
// shared `uploads` volume (/backend/uploads/ and its private/ subdirectory in
// the container).
//
// With no S3 endpoint the public store is the volume alone, the behaviour
// before Garage. An endpoint with missing credentials is a configuration
// mistake: it is logged and the volume is used rather than failing every
// upload.
func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
disk := DiskFileStore{Dir: publicDir}
u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}}
switch {
case cfg.Endpoint == "":
log.Printf("[upload] S3_ENDPOINT unset; storing uploads on disk in %s", publicDir)
case cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" || cfg.Bucket == "":
log.Printf("[upload] S3_ENDPOINT is set but S3_BUCKET or the S3 key is missing; storing uploads on disk in %s", publicDir)
default:
log.Printf("[upload] storing uploads in bucket %s at %s (disk fallback: %s)", cfg.Bucket, cfg.Endpoint, publicDir)
u.public = FallbackFileStore{Primary: NewS3FileStore(cfg), Fallback: disk}
}
return u
}
// Save validates and stores one uploaded file and returns its URL
// (/uploads/<name>, or /uploads/private/<name>). Authorisation is the
// caller's job: only an admin may save a private file.
func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) {
if fh.Size > MaxUploadSize {
return "", ErrUploadTooLarge
}
ext := strings.ToLower(filepath.Ext(fh.Filename))
kind, ok := UploadTypes[ext]
if !ok {
return "", ErrUploadType
}
f, err := fh.Open()
if err != nil {
return "", fmt.Errorf("opening upload: %w", err)
}
defer f.Close()
if kind.SniffPrefix != "" {
// 512 bytes is all http.DetectContentType looks at. A short read is
// fine; sniffing works on a prefix, so only an empty file is an error.
buf := make([]byte, 512)
n, err := io.ReadFull(f, buf)
if n == 0 {
return "", ErrUploadUnreadable
}
if err != nil && err != io.ErrUnexpectedEOF {
return "", fmt.Errorf("reading upload: %w", err)
}
if !strings.HasPrefix(http.DetectContentType(buf[:n]), kind.SniffPrefix) {
return "", ErrUploadContent
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewinding upload: %w", err)
}
}
// The uploaded name is thrown away for 16 random bytes. That rules out
// path traversal and collisions in one go, and makes the URL unguessable.
// Only the extension survives, and it is on the allow-list.
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generating filename: %w", err)
}
name := hex.EncodeToString(b) + ext
store, prefix := u.public, publicURLPrefix
if private {
store, prefix = u.private, privateURLPrefix
}
if err := store.Put(ctx, name, kind.ContentType, f, fh.Size); err != nil {
return "", err
}
return prefix + name, nil
}
// StoredFile is one public upload, as listed for the admin's upload picker.
type StoredFile struct {
Name string `json:"name"`
URL string `json:"url"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
// List returns every public upload, newest first. Private files are never
// listed: they live in their own store, which this doesn't touch.
//
// The caller must be an admin. An upload's URL is public but unguessable, and
// that is the only thing keeping a file nobody linked to from being found; a
// listing anyone could read would hand every one of them out.
//
// Only names with an extension on the allow-list are returned, so anything
// else that ends up in the bucket or the directory (by hand, through
// garage-webui) never reaches a page through the picker.
func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
files, err := u.public.List(ctx)
if err != nil {
return nil, err
}
out := files[:0]
for _, f := range files {
if _, ok := UploadTypes[strings.ToLower(filepath.Ext(f.Name))]; ok {
f.URL = publicURLPrefix + f.Name
out = append(out, f)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Modified.After(out[j].Modified) })
return out, nil
}
// ---- Stores ----------------------------------------------------------------
// FileStore stores one file under key, and lists what it holds. r is a
// ReadSeeker because the S3 client must hash the body before sending it over
// plain HTTP, and because FallbackFileStore rewinds it to retry; a
// multipart.File satisfies it.
//
// List returns top-level files only, with URL unset (Uploads.List fills it).
type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
List(ctx context.Context) ([]StoredFile, error)
}
// DiskFileStore writes files into Dir, creating it if needed.
type DiskFileStore struct{ Dir string }
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
// 0755 and 0644 so nginx, a different user, can reach and read the files.
if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err
}
out, err := os.OpenFile(filepath.Join(d.Dir, key), os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
if _, err := io.Copy(out, r); err != nil {
out.Close()
return err
}
return out.Close()
}
// List skips subdirectories, which is what keeps the private/ directory
// (inside the public one on the volume) out of the listing. A directory that
// doesn't exist yet just holds nothing.
func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
entries, err := os.ReadDir(d.Dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var files []StoredFile
for _, e := range entries {
if !e.Type().IsRegular() {
continue
}
info, err := e.Info()
if err != nil {
continue // deleted between ReadDir and here
}
files = append(files, StoredFile{Name: e.Name(), Size: info.Size(), Modified: info.ModTime()})
}
return files, nil
}
// S3FileStore writes files into one bucket of an S3-compatible server.
type S3FileStore struct {
client *s3.Client
bucket string
}
// S3Config is the S3_* block of .env.
type S3Config struct {
Endpoint string // e.g. http://garage:3900
Region string // must match garage.toml's s3_region
Bucket string
AccessKeyID string
SecretAccessKey string
}
// s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on
// the same Docker network, so anything near this is a hang, and the fallback
// to disk is better than holding the request open.
const s3Timeout = 30 * time.Second
func NewS3FileStore(cfg S3Config) *S3FileStore {
client := s3.New(s3.Options{
BaseEndpoint: aws.String(cfg.Endpoint),
Region: cfg.Region,
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
// Garage addresses buckets by path (/bucket/key); virtual-host style
// would need a DNS name per bucket.
UsePathStyle: true,
// Recent SDKs add CRC32 checksums to every PUT by default. Only send
// them where S3 requires them, which is what third-party servers
// handle reliably.
RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
})
return &S3FileStore{client: client, bucket: cfg.Bucket}
}
func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: r,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
})
if err != nil {
return fmt.Errorf("s3 put %s/%s: %w", s.bucket, key, err)
}
return nil
}
// List pages through the whole bucket. Keys containing "/" are skipped: they
// are not uploads (Save never makes one) but something put under a prefix by
// hand, and nginx's /uploads/<name> only ever serves a top-level name anyway.
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
var files []StoredFile
pages := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{Bucket: aws.String(s.bucket)})
for pages.HasMorePages() {
page, err := pages.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("s3 list %s: %w", s.bucket, err)
}
for _, obj := range page.Contents {
key := aws.ToString(obj.Key)
if key == "" || strings.Contains(key, "/") {
continue
}
files = append(files, StoredFile{Name: key, Size: aws.ToInt64(obj.Size), Modified: aws.ToTime(obj.LastModified)})
}
}
return files, nil
}
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
// Fallback instead. The upload still succeeds and its URL still works (nginx
// looks in both places), so a Garage outage costs a log line rather than
// broken uploads.
type FallbackFileStore struct {
Primary FileStore
Fallback FileStore
}
func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error {
err := f.Primary.Put(ctx, key, contentType, r, size)
if err == nil {
return nil
}
log.Printf("[upload] primary store failed, writing %s to fallback: %v", key, err)
if _, seekErr := r.Seek(0, io.SeekStart); seekErr != nil {
return fmt.Errorf("rewinding for fallback after %v: %w", err, seekErr)
}
return f.Fallback.Put(ctx, key, contentType, r, size)
}
// List is the union of both stores, since nginx serves from both: the
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the
// fallback's files are returned alone, as for Put.
func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) {
primary, err := f.Primary.List(ctx)
if err != nil {
log.Printf("[upload] primary store failed to list, listing fallback only: %v", err)
primary = nil
}
fallback, fbErr := f.Fallback.List(ctx)
if fbErr != nil {
if err != nil {
return nil, fmt.Errorf("listing both stores: %v; %w", err, fbErr)
}
log.Printf("[upload] fallback store failed to list: %v", fbErr)
}
seen := make(map[string]bool, len(primary))
for _, file := range primary {
seen[file.Name] = true
}
for _, file := range fallback {
if !seen[file.Name] {
primary = append(primary, file)
}
}
return primary, nil
}
+308
View File
@@ -0,0 +1,308 @@
package services
import (
"bytes"
"context"
"errors"
"image"
"image/png"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// Covered here: the type table (the upload trust boundary's data), Save's
// validation, naming and routing, which store NewUploads picks, and the
// fallback — including against a real S3 client talking to a server that
// refuses the write, since "Garage said no" is the case it exists for.
//
// Not covered: a successful PutObject or ListObjectsV2 against Garage. That needs the garage
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
// fileHeader builds the *multipart.FileHeader a handler would get from
// ctx.FormFile, by round-tripping a real multipart body.
func fileHeader(t *testing.T, name string, content []byte) *multipart.FileHeader {
t.Helper()
var body bytes.Buffer
w := multipart.NewWriter(&body)
part, _ := w.CreateFormFile("file", name)
part.Write(content)
w.Close()
form, err := multipart.NewReader(&body, w.Boundary()).ReadForm(32 << 20)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { form.RemoveAll() })
return form.File["file"][0]
}
func pngBytes() []byte {
var b bytes.Buffer
png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 2, 2)))
return b.Bytes()
}
// recordingStore remembers what it was asked to store.
type recordingStore struct {
key, contentType string
body []byte
}
func (r *recordingStore) Put(_ context.Context, key, contentType string, rd io.ReadSeeker, _ int64) error {
r.key, r.contentType = key, contentType
r.body, _ = io.ReadAll(rd)
return nil
}
func (r *recordingStore) List(context.Context) ([]StoredFile, error) { return nil, nil }
// listStore lists a fixed set of files, or fails.
type listStore struct {
files []StoredFile
err error
}
func (l listStore) Put(context.Context, string, string, io.ReadSeeker, int64) error { return nil }
func (l listStore) List(context.Context) ([]StoredFile, error) { return l.files, l.err }
func TestUploadTypes(t *testing.T) {
t.Run("nothing executable or markup is allowed", func(t *testing.T) {
// Served from our own origin with no login, so anything a browser
// would run or render as a page must never be storable.
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".mjs", ".php", ".exe", ".sh", ".xml", ".xhtml", ""} {
if _, ok := UploadTypes[ext]; ok {
t.Errorf("%q must not be an allowed upload type", ext)
}
}
})
for ext, kind := range UploadTypes {
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("key %q: Save looks up the lower-cased extension with its dot, so this is unreachable", ext)
}
if kind.ContentType == "" {
// Stored and served as-is; under nosniff an empty type renders nothing.
t.Errorf("%q has no ContentType", ext)
}
}
t.Run("audio and gif are not sniffed", func(t *testing.T) {
// DetectContentType misreads these; checking them would reject
// legitimate files.
for _, ext := range []string{".mp3", ".ogg", ".gif"} {
if UploadTypes[ext].SniffPrefix != "" {
t.Errorf("%q should not be content-checked", ext)
}
}
})
}
func TestUploadsSave(t *testing.T) {
ctx := context.Background()
public, private := &recordingStore{}, &recordingStore{}
u := &Uploads{public: public, private: private}
t.Run("public file", func(t *testing.T) {
img := pngBytes()
url, err := u.Save(ctx, fileHeader(t, "Holiday Photo.PNG", img), false)
if err != nil {
t.Fatal(err)
}
// The name is replaced by 32 hex chars; the lower-cased extension stays.
if !strings.HasPrefix(url, "/uploads/") || len(strings.TrimPrefix(url, "/uploads/")) != 32+len(".png") || !strings.HasSuffix(url, ".png") {
t.Errorf("url = %q, want /uploads/<32 hex>.png", url)
}
if public.key != strings.TrimPrefix(url, "/uploads/") || public.contentType != "image/png" {
t.Errorf("stored as %q (%q)", public.key, public.contentType)
}
// The whole file, not just what was left after sniffing.
if !bytes.Equal(public.body, img) {
t.Errorf("stored %d bytes, want %d", len(public.body), len(img))
}
})
t.Run("private file goes to the private store", func(t *testing.T) {
url, err := u.Save(ctx, fileHeader(t, "note.txt", []byte("hello")), true)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(url, "/uploads/private/") || private.key == "" {
t.Errorf("url = %q, private store got %q", url, private.key)
}
})
t.Run("rejections", func(t *testing.T) {
cases := []struct {
name string
file string
content []byte
want error
}{
{"disallowed type", "page.html", []byte("<html></html>"), ErrUploadType},
{"markup dressed as an image", "evil.png", []byte("<html><script>alert(1)</script></html>"), ErrUploadContent},
{"empty sniffed file", "empty.png", nil, ErrUploadUnreadable},
{"too large", "big.mp3", make([]byte, MaxUploadSize+1), ErrUploadTooLarge},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
_, err := u.Save(ctx, fileHeader(t, c.file, c.content), false)
if !errors.Is(err, c.want) {
t.Errorf("err = %v, want %v", err, c.want)
}
})
}
})
}
func TestNewUploads(t *testing.T) {
dir := t.TempDir()
if _, ok := NewUploads(S3Config{}, dir, dir).public.(DiskFileStore); !ok {
t.Error("no S3 endpoint should mean the disk store")
}
if _, ok := NewUploads(S3Config{Endpoint: "http://garage:3900", Bucket: "uploads"}, dir, dir).public.(DiskFileStore); !ok {
t.Error("an endpoint without credentials should fall back to the disk store")
}
full := S3Config{Endpoint: "http://garage:3900", Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}
u := NewUploads(full, dir, dir)
if _, ok := u.public.(FallbackFileStore); !ok {
t.Error("a full S3 config should mean the bucket with a disk fallback")
}
if _, ok := u.private.(DiskFileStore); !ok {
t.Error("private files must always stay on disk")
}
}
func TestDiskFileStorePut(t *testing.T) {
// A directory that doesn't exist yet: the private one is created on demand.
dir := filepath.Join(t.TempDir(), "private")
body := []byte("hello")
if err := (DiskFileStore{Dir: dir}).Put(context.Background(), "a.txt", "text/plain", bytes.NewReader(body), int64(len(body))); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(dir, "a.txt"))
if err != nil || !bytes.Equal(got, body) {
t.Fatalf("read back %q, %v; want %q", got, err, body)
}
}
func TestFallbackWhenBucketRefuses(t *testing.T) {
// 403 rather than 500: the SDK retries 5xx with backoff, which would only
// make the test slow. Either way PutObject returns an error.
var hits int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits++
_, _ = io.Copy(io.Discard, r.Body)
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
dir := t.TempDir()
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
img := pngBytes()
url, err := u.Save(context.Background(), fileHeader(t, "pic.png", img), false)
if err != nil {
t.Fatalf("Save should succeed through the fallback, got %v", err)
}
if hits == 0 {
t.Fatal("the bucket was never tried")
}
// The whole file, not just what the S3 attempt left unread: this is what
// the rewind in FallbackFileStore is for.
got, err := os.ReadFile(filepath.Join(dir, strings.TrimPrefix(url, "/uploads/")))
if err != nil || !bytes.Equal(got, img) {
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(img))
}
}
func TestDiskFileStoreList(t *testing.T) {
if files, err := (DiskFileStore{Dir: filepath.Join(t.TempDir(), "missing")}).List(context.Background()); err != nil || len(files) != 0 {
t.Fatalf("missing dir: got %v, %v; want nothing and no error", files, err)
}
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "a.png"), []byte("abc"), 0644)
os.MkdirAll(filepath.Join(dir, "private"), 0755)
os.WriteFile(filepath.Join(dir, "private", "secret.png"), []byte("x"), 0644)
files, err := (DiskFileStore{Dir: dir}).List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 1 || files[0].Name != "a.png" || files[0].Size != 3 {
t.Fatalf("got %+v, want just a.png (3 bytes): private/ must not be listed", files)
}
}
func TestFallbackFileStoreList(t *testing.T) {
ctx := context.Background()
bucket := listStore{files: []StoredFile{{Name: "a.png", Size: 1}, {Name: "b.png"}}}
disk := listStore{files: []StoredFile{{Name: "a.png", Size: 2}, {Name: "c.png"}}}
files, err := FallbackFileStore{Primary: bucket, Fallback: disk}.List(ctx)
if err != nil {
t.Fatal(err)
}
names := map[string]int64{}
for _, f := range files {
names[f.Name] = f.Size
}
if len(files) != 3 || names["a.png"] != 1 || len(names) != 3 {
t.Errorf("got %+v, want a (from the bucket), b and c once each", files)
}
t.Run("bucket down", func(t *testing.T) {
files, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: disk}.List(ctx)
if err != nil || len(files) != 2 {
t.Errorf("got %+v, %v; want the disk's two files", files, err)
}
})
t.Run("both down", func(t *testing.T) {
_, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: listStore{err: errors.New("gone")}}.List(ctx)
if err == nil {
t.Error("want an error when neither store can list")
}
})
}
func TestFallbackListWhenBucketRefuses(t *testing.T) {
// The real S3 client against a server that refuses: the listing still
// comes back, from disk.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "on-disk.png"), pngBytes(), 0644)
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
files, err := u.List(context.Background())
if err != nil || len(files) != 1 || files[0].URL != "/uploads/on-disk.png" {
t.Fatalf("got %+v, %v; want the one disk file", files, err)
}
}
func TestUploadsList(t *testing.T) {
now := time.Now()
u := &Uploads{public: listStore{files: []StoredFile{
{Name: "old.png", Modified: now.Add(-time.Hour)},
{Name: "page.html", Modified: now},
{Name: "new.JPG", Modified: now.Add(-time.Minute)},
{Name: "noext", Modified: now},
}}}
files, err := u.List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 2 || files[0].URL != "/uploads/new.JPG" || files[1].URL != "/uploads/old.png" {
t.Fatalf("got %+v, want new.JPG then old.png, nothing off the allow-list", files)
}
}
+42 -7
View File
@@ -12,8 +12,24 @@
# profile, so `docker compose -f docker-compose.yml -f docker-compose.dev.yml
# up` never starts it and dev uses nginx's self-signed localhost cert instead.
#
# HOW VALIDATION WORKS (--webroot)
# Let's Encrypt HTTP-01: certbot writes a challenge token into
# HOW VALIDATION WORKS: DNS-01 (--dns-cloudflare) when CLOUDFLARE_DNS_API_TOKEN
# is set, otherwise HTTP-01 (--webroot)
# DNS-01: certbot creates a _acme-challenge TXT record through the Cloudflare
# API, Let's Encrypt looks it up, and certbot deletes it. Nothing has to
# reach the Pi, which is the point: with the site behind the Cloudflare
# tunnel, ports 80 and 443 need not be forwarded at all. The token needs
# Zone -> DNS -> Edit on this zone only. certbot insists its credentials
# arrive as a mode-600 ini file, not an environment variable, so the script
# writes one to /tmp on every start; nothing is stored on disk outside the
# container.
#
# Switching method on an existing certificate: certbot records the method
# in renewal/<DOMAIN>.conf and `renew` would keep using webroot. Flags on
# the command line override the stored ones, and the next successful
# renewal saves them, so the method flags are passed to BOTH commands below.
# An unset token after a switch therefore puts it back on webroot, too.
#
# HTTP-01, the fallback: certbot writes a challenge token into certbot writes a challenge token into
# /var/www/certbot/.well-known/acme-challenge/ and Let's Encrypt fetches it
# over plain HTTP on port 80. certbot itself listens on nothing — nginx is
# the server that answers. /var/www/certbot is the ./certbot/www bind mount,
@@ -47,12 +63,14 @@
# root-equivalent on the host, and the shared cert directory is a capability
# both containers already have.
#
# ENV VARS REQUIRED (from ./.env via `env_file`)
# ENV VARS (from ./.env via `env_file`)
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
# filed under --cert-name $DOMAIN so the path nginx expects
# (/etc/letsencrypt/live/$DOMAIN/) is stable regardless of which
# name certbot would otherwise have chosen.
# EMAIL registration/expiry-notice address for the ACME account.
# CLOUDFLARE_DNS_API_TOKEN
# optional; selects DNS-01. See HOW VALIDATION WORKS.
#
# FLAGS WORTH KNOWING
# --agree-tos --non-interactive never prompt; required in a container.
@@ -61,9 +79,10 @@
# rather than erroring out.
#
# ASSUMES EXISTS
# /var/www/certbot (shared ACME webroot, served by nginx on port 80)
# /etc/letsencrypt (persistent cert store, shared with nginx)
# Port 80 reachable from the public internet for $DOMAIN and www.$DOMAIN.
# Webroot method only: /var/www/certbot (shared ACME webroot, served by
# nginx on port 80) and port 80 reachable from the public internet for
# $DOMAIN and www.$DOMAIN.
# =============================================================================
# The reload sentinel: a file in the SHARED /etc/letsencrypt mount that nginx's
@@ -71,7 +90,23 @@
# — see RELOAD SIGNAL above.
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
certbot certonly --webroot -w /var/www/certbot \
if [ -n "${CLOUDFLARE_DNS_API_TOKEN}" ]; then
CREDENTIALS=/tmp/cloudflare.ini
# umask rather than a chmod afterwards, so the token is never readable
# by anyone else even for an instant.
(umask 077 && printf 'dns_cloudflare_api_token = %s\n' "${CLOUDFLARE_DNS_API_TOKEN}" >"${CREDENTIALS}")
# 30s rather than the plugin's 10: Let's Encrypt queries from several
# vantage points, and a lookup that lands before Cloudflare has the record
# everywhere fails the whole order.
set -- --dns-cloudflare --dns-cloudflare-credentials "${CREDENTIALS}" \
--dns-cloudflare-propagation-seconds 30
echo "Validating over DNS (Cloudflare API)."
else
set -- --webroot -w /var/www/certbot
echo "Validating over HTTP (webroot); needs port 80 reachable."
fi
certbot certonly "$@" \
--email "${EMAIL}" \
-d "${DOMAIN}" -d "www.${DOMAIN}" \
--cert-name "${DOMAIN}" \
@@ -82,7 +117,7 @@ certbot certonly --webroot -w /var/www/certbot \
trap exit TERM;
while :; do
certbot renew --webroot -w /var/www/certbot \
certbot renew "$@" \
--deploy-hook "touch ${RELOAD_SENTINEL}";
sleep 12h;
done
+8
View File
@@ -0,0 +1,8 @@
# Dev notes vault
`OBSIDIAN_DIR` in `.env.dev` points here, so the dev stack's SilverBullet
instances and the backend's `/notes` endpoint have a vault to mount. Anything
you write here is gitignored; only this README is tracked.
It is deliberately not a git repository, so `silverbullet-git` logs that and
idles instead of syncing it anywhere.
+12 -7
View File
@@ -16,6 +16,7 @@
# nginx_dev.conf.template and self-sign a localhost certificate.
# - python : uvicorn --reload with the app source bind-mounted.
# - certbot : disabled entirely.
# - cloudflared : disabled entirely.
#
# HOW TO REACH IT
# http://localhost (HTTPS also works on :443 with the self-signed cert, which
@@ -31,14 +32,12 @@ services:
command: ["npm", "run", "dev"]
volumes:
- ./vue:/app
# The two bare paths are ANONYMOUS-VOLUME MASKS, not typos. Binding
# ./vue over /app would otherwise hide the node_modules and WASM
# output that were installed/built *inside* the image. Declaring
# them as anonymous volumes re-exposes the image's copies on top of
# the bind mount, so `npm ci` and wasm-pack results survive and the
# host does not need node_modules or a Rust toolchain at all.
# The bare path is an ANONYMOUS-VOLUME MASK, not a typo. Binding
# ./vue over /app would otherwise hide the node_modules that were
# installed *inside* the image. Declaring it as an anonymous volume
# re-exposes the image's copy on top of the bind mount, so the
# `npm ci` result survives and the host does not need node_modules.
- /app/node_modules
- /app/src/wasm
environment:
- NODE_ENV=development
backend:
@@ -93,3 +92,9 @@ services:
# Let's Encrypt could not validate localhost anyway.
profiles:
- disabled
cloudflared:
# Same profile trick as certbot. A dev stack must never join the
# production tunnel: Cloudflare would load-balance real visitors onto
# this machine's seeded database.
profiles:
- disabled
+383 -16
View File
@@ -13,8 +13,8 @@
#
# ENV VARS
# Everything interpolated as ${VAR} below is read by the docker compose CLI
# from ./.env at the repo root (which is gitignored — see sync-secrets.sh for
# how it is distributed to the Pi). Note the two distinct mechanisms:
# from ./.env at the repo root (gitignored, and edited by hand on the host).
# Note the two distinct mechanisms:
# - ${VAR} in this file -> substituted by compose when parsing
# - `env_file: ./.env` -> the whole file injected into the container
# Many services need both: the container name comes from substitution, the
@@ -37,7 +37,8 @@
# Only nginx (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor
# port. Everything else is reachable only from inside app-network, which is
# why the backend, db, silverbullet and python have no `ports:` — they are
# deliberately not exposed and are reached through nginx.
# deliberately not exposed and are reached through nginx. Web traffic can
# also arrive through the `cloudflared` tunnel, which publishes nothing.
# =============================================================================
networks:
@@ -50,6 +51,13 @@ networks:
ipam:
config:
- subnet: 172.28.0.0/16
# The usaco site's code runner and nothing else but the site. internal:
# no route out, so code submitted to it cannot reach the internet, and
# being off app-network keeps it away from postgres, gitea, garage and the
# backend. Docker picks the subnet; nothing here pins an address on it.
usaco-runner-net:
driver: bridge
internal: true
# PERSISTENT vs EPHEMERAL state
# Named volumes below survive `docker compose down` and container rebuilds;
@@ -64,8 +72,17 @@ volumes:
dbdata:
# File upload — PERSISTENT. Written by the backend at /backend/uploads,
# served read-only by nginx at /uploads/. Shared so nginx can serve user
# uploads without proxying through the Go process.
# uploads without proxying through the Go process. Since Garage, it holds
# private attachments (always), the uploads from before the bucket, and any
# upload the backend wrote here because Garage refused it. nginx serves
# /uploads/ from the bucket first and only then from here.
uploads:
# Garage object store — PERSISTENT, both. garage_meta is the metadata DB
# (buckets, keys, the object index, the cluster layout); garage_data is the
# object bytes. Lose meta and the bytes in data are unreadable, so back up
# the two together. A fresh pair needs garage/bootstrap.sh run once.
garage_meta:
garage_data:
# Vue build — EPHEMERAL in spirit but a named volume for handoff: the
# one-shot `vue` container writes the built SPA here and exits; nginx mounts
# it at /etc/nginx/html and serves it. Repopulated on every rebuild.
@@ -115,8 +132,25 @@ services:
- silverbullet-public
- python
- jobs
- activity-tracker
- dozzle
networks:
- app-network
app-network:
# The site's public names, resolving to this container for everything
# on app-network. They exist for cloudflared: its tunnel origin is
# https://www.DOMAIN, which lands here over the bridge with a name the
# Let's Encrypt certificate actually covers, so the tunnel verifies
# TLS with no extra dashboard settings (`https://nginx` would fail the
# name check). Any other container that calls the public site now
# reaches nginx directly instead of hairpinning through the internet.
aliases:
- ${DOMAIN}
- www.${DOMAIN}
# Fixed for cloudflared's extra_hosts (see there): an alias only
# exists while nginx is running, and this address is pinned to the
# same names for when it is not. Top of the /16 beside cloudflared's,
# away from docker's dynamic allocations.
ipv4_address: 172.28.255.251
ports:
- 80:80
- 443:443
@@ -130,14 +164,36 @@ services:
- uploads:/uploads
# The SPA written by the one-shot `vue` container.
- vue_dist:/etc/nginx/html
# The JSON request-body log (nginx/payload_log.conf), kept on the host so
# it survives rebuilds and the `traffic` container can tail it. Grows
# without bound unless rotated — see DEPLOYMENT.md.
- ./logs/nginx:/var/log/nginx/payloads
# restart: always only acts when nginx's master exits. On 2026-10-19 the
# worker stalled while the master lived, and the site was down 4.6 hours
# with the container "Up". /nginx-health is answered by a worker, so a
# stall shows here; Docker only marks it unhealthy, and the `autoheal`
# label is what gets it restarted (see the autoheal service). Plain HTTP
# on :80 so it also passes in the first-boot setup config, which has no
# :443; the workers that serve :80 are the ones serving TLS.
healthcheck:
test: ["CMD", "curl", "-fsS", "--max-time", "5", "-o", "/dev/null", "http://127.0.0.1/nginx-health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
labels:
- autoheal=true
# Obtains the cert once, then renews every 12h forever. Disabled in dev via
# the `disabled` profile in docker-compose.dev.yml. Note this is the stock
# certbot image with our script bind-mounted over the entrypoint, so editing
# certbot/entrypoint.sh takes effect on restart with no rebuild. Version is
# pinned so a certbot release cannot change behaviour under us on redeploy.
# The dns-cloudflare variant is plain certbot plus the Cloudflare DNS plugin:
# with CLOUDFLARE_DNS_API_TOKEN set it validates over DNS, so renewal needs
# no inbound port, and without it falls back to the webroot method.
certbot:
image: certbot/certbot:v3.1.0
image: certbot/dns-cloudflare:v3.1.0
container_name: certbot
volumes:
- ./certbot/entrypoint.sh:/entrypoint.sh
@@ -149,6 +205,46 @@ services:
networks:
- app-network
# Cloudflare Tunnel: an OUTBOUND connection from here to Cloudflare's edge,
# which then forwards visitors' requests back down it to nginx. Nothing is
# published to the host, so with the tunnel live the router's 80/443
# forwards can be closed. The tunnel is "remotely managed": its public
# hostnames and origin settings live in the Cloudflare dashboard, and this
# container only needs the token. The routing set up there (DEPLOYMENT.md,
# "Cloudflare Tunnel") is https://www.DOMAIN, which nginx's network aliases
# resolve to nginx itself, so the certificate verifies; nginx's config,
# redirects and security headers apply to tunnel traffic exactly as to
# direct traffic, and both paths work side by side.
#
# Fixed address so nginx can trust the CF-Connecting-IP header from this
# container and no other (set_real_ip_from in nginx.conf.template). It sits
# at the top of the /16 because docker hands out dynamic addresses from the
# bottom; the two must change together.
#
# Disabled in dev via the `disabled` profile in docker-compose.dev.yml.
cloudflared:
image: cloudflare/cloudflared:2026.9.3
container_name: cloudflared
restart: always
command: ["tunnel", "--no-autoupdate", "run"]
# Explicit, not env_file: the container only ever needs the token.
environment:
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
depends_on:
- nginx
# Pins the tunnel origin's names to nginx's fixed address. nginx's aliases
# vanish while it is stopped (every deploy and the weekly maintenance), and
# docker's DNS then forwards the name to public DNS, which answers with
# Cloudflare's own IPs: the tunnel sent requests back to the edge and
# visitors got error 1000. /etc/hosts wins over DNS, so a stopped nginx is
# now a refused connection, which cloudflared reports as a plain 502.
extra_hosts:
- "${DOMAIN}:172.28.255.251"
- "www.${DOMAIN}:172.28.255.251"
networks:
app-network:
ipv4_address: 172.28.255.250
backend:
build:
context: ./backend
@@ -177,10 +273,6 @@ services:
# rebuild, forcing a manual re-authorisation of Spotify after each
# deploy. Gitignored (it is a credential).
- ./backend/token/:/backend/token
# Hand-off directory for the admin panel's Environment tab: the backend
# queues a change here and env-apply/apply.py on the host applies it.
# The backend gets this instead of .env itself or the Docker socket.
- ./env-apply/run:/backend/env-apply
# The Obsidian vault on the host, read by the backend for the notes API.
# Same directory is mounted read-write into silverbullet (the editor) and
# read-only into silverbullet-public (the /notes/ site).
@@ -246,7 +338,8 @@ services:
#
# This is the only non-nginx service that publishes a host port, and it has
# to: LIQUIDSOAP_HARBOR_PORT is the live-DJ input. A broadcasting client
# (e.g. butt) connects straight to the Pi on that port with the icecast
# (e.g. butt) connects straight to the Pi on that port, by its Tailscale
# name now that the public domain resolves to Cloudflare, with the icecast
# source password and pre-empts the fallback playlist. It is NOT proxied
# through nginx because it is a raw source protocol, not HTTP the SPA uses.
# Note the host:container mapping uses the same variable on both sides, so
@@ -374,6 +467,13 @@ services:
restart: always
networks:
- app-network
# The vault's remotes are ssh://git@DOMAIN:2222/..., but nginx's network
# aliases make DOMAIN resolve to nginx on app-network, which has no :2222,
# so every pull and push was refused. /etc/hosts wins over Docker's DNS, so
# this sends DOMAIN back to the host, where gitea publishes 2222. The name
# is unchanged, so known_hosts still matches.
extra_hosts:
- "${DOMAIN}:host-gateway"
# Same uid SilverBullet writes as, so commits don't leave root-owned objects
# in .git that the host user can no longer clean up.
user: "1000:1000"
@@ -431,12 +531,14 @@ services:
#
# Like python, it gets an explicit `environment:` list rather than the whole
# .env: it never sees the site's database password or JWT secret, and has a
# database role of its own. backend/services/env_manager_test.go checks the
# list against env_registry.json.
# database role of its own. A variable the tracker reads must be added to
# the list below as well as .env.example.
#
# It has no login. AUTH_VALIDATE_URL is the backend's validate-admin route
# (the one nginx's auth_request uses), which the tracker asks with the
# visitor's cookies on each admin request.
# It has no login. nginx's auth_request gates /jobs/ like /sb/ (except the
# bearer-token capture API and the userscript), and the tracker checks
# again itself: AUTH_VALIDATE_URL is the backend's validate-admin route
# (the one nginx's auth_request uses), which it asks with the visitor's
# cookies on each admin request.
#
# ./jobs-data holds the Microsoft Graph session and the capture token. The
# image runs as uid 1000, so the directory must be owned by it.
@@ -473,6 +575,261 @@ services:
volumes:
- ./jobs-data:/data
# The USACO practice log, served at /usaco/. Built and published by the
# usaco repo's CI (adamf/usaco on this Gitea; the server is in its site/
# directory), which pulls :latest into this service on every push to main
# that touches the site. Pin USACO_IMAGE_TAG to hold a version.
#
# It has no database: git is its store. It keeps a clone of adamf/usaco in
# ./usaco-data, pulled over the Docker network when Gitea's push webhook
# fires (USACO_WEBHOOK_SECRET signs it), and commits the admin's edits
# (status, link, notes, statement, explanations) back with USACO_GIT_TOKEN.
# CLAUDE_API_KEY powers the admin's Explain button (USACO_CLAUDE_MODEL picks
# the model; blank is claude-opus-5-5). Recording reviews also need
# USACO_OPENAI_API_KEY to transcribe, and keep the audio in Garage's
# private usaco-audio bucket when USACO_S3_* is set (the site refuses to
# start with only some S3_* set, so all five go together or not at all:
# the blank-key case blanks the rest). USACO_CLAUDE_MONTHLY_BUDGET (dollars,
# blank for none) stops new Claude jobs once a month's estimated spend
# reaches it. ./usaco-data holds that clone, the background jobs' records
# and the Claude spend ledger; deleting it is safe (it re-clones) but loses
# any answer not yet committed. The image runs as uid 1000, so the
# directory must be owned by it.
#
# On stop it lets running Claude jobs finish for up to SHUTDOWN_GRACE (5m
# by default) before exiting, so stop_grace_period must be longer than
# that, or Docker kills it mid-job.
#
# Same explicit `environment:` list as jobs. Like the tracker it has no
# login: visitors see solved problems, and AUTH_VALIDATE_URL decides who
# is the admin from the visitor's cookies.
usaco:
image: adam-french.co.uk/adamf/usaco:${USACO_IMAGE_TAG:-latest}
container_name: usaco
restart: always
stop_grace_period: 6m
depends_on:
- gitea
- usaco-runner
networks:
- app-network
- usaco-runner-net
environment:
- GIT_REMOTE_URL=http://${GITEA_HOST}:${GITEA_PORT}/adamf/usaco.git
- GIT_TOKEN=${USACO_GIT_TOKEN:-}
- WEBHOOK_SECRET=${USACO_WEBHOOK_SECRET:-}
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
- CLAUDE_API_KEY=${CLAUDE_API_KEY:-}
- CLAUDE_MODEL=${USACO_CLAUDE_MODEL:-}
- CLAUDE_MONTHLY_BUDGET=${USACO_CLAUDE_MONTHLY_BUDGET:-}
- TRANSCRIBE_API_KEY=${USACO_OPENAI_API_KEY:-}
- S3_ACCESS_KEY_ID=${USACO_S3_ACCESS_KEY_ID:-}
- S3_SECRET_ACCESS_KEY=${USACO_S3_SECRET_ACCESS_KEY:-}
- S3_ENDPOINT=${USACO_S3_ACCESS_KEY_ID:+http://garage:3900}
- S3_REGION=${USACO_S3_ACCESS_KEY_ID:+garage}
- S3_BUCKET=${USACO_S3_ACCESS_KEY_ID:+usaco-audio}
- RUNNER_URL=http://usaco-runner:8081
volumes:
- ./usaco-data:/data
# The usaco site's code runner (site/Dockerfile.runner in adamf/usaco):
# compiles and runs solutions against their tests, and lints them, for the
# admin's solve page. It runs submitted code, so it has no secrets (no
# environment at all) and is only on usaco-runner-net, which is internal:
# no internet, and nothing but the site can reach it. Published by
# adamf/usaco's CI, which rolls it before `usaco`; pin
# USACO_RUNNER_IMAGE_TAG to hold a version.
#
# The hardening is the point:
# read_only the image is not writable; only /tmp is
# tmpfs /tmp one directory per request, removed after. Must NOT be
# noexec: the compiled program runs from it. Its pages count
# against mem_limit.
# mem_limit, cpus
# on top of the runner's own per-program limits (512 MB
# address space, CPU time, 64 MB files, wall clock)
# pids_limit what stops a fork bomb: the runner does not set
# RLIMIT_NPROC (it counts the whole uid, the server's own
# threads included). The image's tini reaps the leftovers.
# cap_drop, no-new-privileges
# the runner needs no capabilities, and runs as uid 1000
usaco-runner:
image: adam-french.co.uk/adamf/usaco-runner:${USACO_RUNNER_IMAGE_TAG:-latest}
container_name: usaco-runner
restart: always
networks:
- usaco-runner-net
read_only: true
tmpfs:
- /tmp:size=256m,exec
mem_limit: 1g
cpus: 2
pids_limit: 128
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
# The activity tracker (time spent per app, site, walk...), served at
# /tracker/ with the prefix stripped. Built and published by its own repo
# (adamf/ccp on this Gitea), whose CI pulls :latest into this service on
# every push to main; pin ACTIVITY_TRACKER_IMAGE_TAG to hold a version.
#
# Same shape as jobs: an explicit `environment:` list and a database role of
# its own, created by hand once (the ccp README has the command). It applies
# its own migrations on start. No state outside Postgres.
#
# Two kinds of auth. Collectors send per-device bearer keys, made on the
# tracker's /tracker/setup page or with `docker exec activity-tracker
# tracker apikey create`. The dashboard and setup pages have no login of
# their own: nginx's auth_request gates them like /sb/ (everything but
# /tracker/api/v1/ and the userscript), and like jobs the tracker also asks
# AUTH_VALIDATE_URL (the backend's validate-admin) with the visitor's
# cookies and sends anyone else to /admin/login.
activity-tracker:
image: adam-french.co.uk/adamf/activity-tracker:${ACTIVITY_TRACKER_IMAGE_TAG:-latest}
container_name: activity-tracker
restart: always
depends_on:
db:
condition: service_healthy
networks:
- app-network
environment:
- DATABASE_URL=postgres://${POSTGRES_TRACKER_USER:-tracker}:${POSTGRES_TRACKER_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_TRACKER_DB:-tracker}?sslmode=disable
- TRACKER_TZ=${TRACKER_TZ:-}
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
# Echoes nginx's JSON request-body log to its own stdout, and does nothing
# else. It exists so Dozzle shows the payloads as a stream of their own,
# rendered as JSON fields, instead of interleaved with nginx's compact access
# log and error output. -F re-opens the file after rotation; -n0 skips the
# backlog on restart, which stays in the file on the host.
traffic:
image: busybox:1.37.0
container_name: traffic
restart: always
command: ["tail", "-n0", "-F", "/logs/payloads.log"]
network_mode: none
volumes:
- ./logs/nginx:/logs:ro
# Dozzle: a live, searchable web view of every container's logs, served at
# /dozzle/ behind the admin login (nginx/nginx_routes.conf.template). The
# `traffic` container is the one to watch for incoming request bodies.
#
# The Docker socket is mounted :ro, but that only stops the file being
# replaced — the API behind it is still fully usable, which is effectively
# root on the Pi. Hence: no published port, the admin auth_request in front,
# and container actions and shell left at their default of off.
dozzle:
image: amir20/dozzle:v11.2.0
container_name: dozzle
restart: always
networks:
- app-network
environment:
- DOZZLE_BASE=/dozzle
- DOZZLE_NO_ANALYTICS=true
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
# Restarts any container labelled autoheal=true once Docker marks it
# unhealthy, which Docker itself never does (restart policies only see the
# process exit). Only nginx carries the label today; give it to another
# service with a healthcheck to cover that one too. It polls every 5s.
#
# It needs the Docker socket read-write to restart things, which is root on
# the host, so it gets no network at all: nothing can reach it, and it
# reaches nothing but the socket. For the same reason the image is pinned BY
# DIGEST, never a tag, so a push to Docker Hub cannot gain root here at the
# next pull. The digest is the multi-arch index of 1.2.0, the newest tagged
# release; it calls the API unversioned, so it keeps working as the engine's
# minimum API version moves. To bump: `docker buildx imagetools inspect
# willfarrell/autoheal:<tag>` and paste the top-level Digest.
#
# This is the watchdog retired on 2026-10-01 (.deprecated/autoheal), back
# with a label filter instead of `all`, so backend's and python's
# healthchecks stay informational.
autoheal:
image: willfarrell/autoheal@sha256:31f580ef0279eaced5b38d631b08c474d70d8403c1c2fdd6ddcf2e879d5f3f7c
container_name: autoheal
restart: always
network_mode: none
environment:
- AUTOHEAL_CONTAINER_LABEL=autoheal
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# S3-compatible object store holding public uploads (the `uploads` bucket).
# The backend writes to it on :3900 once S3_ENDPOINT is set in .env; nginx
# serves /uploads/ from it anonymously on :3902, falling back to the
# `uploads` volume; garage-webui manages it via :3903. Nothing is published
# to the host. Config is garage/garage.toml (no secrets in it); the two
# secrets come from .env through the explicit list below.
#
# Nothing depends on this container being up. nginx is deliberately NOT
# given it in depends_on: its upstream is a variable, so a missing or
# crash-looping garage only makes bucket-only files 404 (everything on the
# volume is still served), never nginx's boot; and the backend falls back
# to the volume when a write fails.
#
# FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access).
# The image is FROM scratch — no shell, so no in-container init script and
# a healthcheck that calls the binary itself.
garage:
image: dxflrs/garage:v2.4.1
container_name: garage
restart: always
networks:
- app-network
environment:
- GARAGE_RPC_SECRET=${GARAGE_RPC_SECRET}
- GARAGE_ADMIN_TOKEN=${GARAGE_ADMIN_TOKEN}
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
- garage_meta:/var/lib/garage/meta
- garage_data:/var/lib/garage/data
healthcheck:
test: ["CMD", "/garage", "status"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
# Admin web UI for Garage, served at /garage/ behind the nginx admin gate.
# Manages buckets and keys, and browses/uploads/deletes objects. Its own
# login (AUTH_USER_PASS) is left unset because nginx's auth_request already
# requires the site admin — and it holds the admin token, so never publish
# its port. It reads the s3/web settings from garage.toml; the token comes
# from .env instead, since the file has none.
#
# Files uploaded here land in the PUBLIC bucket and are served at
# /uploads/<path> with none of the backend's checks. Put hand-managed media
# under a prefix (e.g. media/) so it can't collide with the backend's
# random hex names.
garage-webui:
image: khairul169/garage-webui:1.1.0
container_name: garage-webui
restart: always
depends_on:
- garage
networks:
- app-network
environment:
- BASE_PATH=/garage
- API_BASE_URL=http://garage:3903
- API_ADMIN_KEY=${GARAGE_ADMIN_TOKEN}
- S3_ENDPOINT_URL=http://garage:3900
- S3_REGION=garage
# The image has no /tmp, and Go spools any multipart upload over 32MB to
# a temp file there, so without this every large upload fails with
# "open /tmp/multipart-…: no such file or directory".
tmpfs:
- /tmp
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
# main, executed by the act_runner that lives outside docker (gitea-runner/).
@@ -504,6 +861,16 @@ services:
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
# The host's own name, which Gitea prints in SSH clone URLs. It lives in
# .env, not app.ini, so moving to another host is a one-line change;
# environment-to-ini writes it into the live app.ini on every start.
# localhost suits dev.
- GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
- GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
# Webhooks are refused to private addresses by default ("external").
# The usaco site's push hook targets http://usaco:8080 on the Docker
# network, so that one host is allowed by name.
- GITEA__webhook__ALLOWED_HOST_LIST=external,usaco
- USER_UID=1000
- USER_GID=1000
restart: always
-266
View File
@@ -1,266 +0,0 @@
#!/usr/bin/env python3
# =============================================================================
# apply.py — the host half of the admin panel's Environment tab.
#
# WHAT IT DOES
# Takes the change the backend queued in env-apply/run/request.json, merges
# it into ./.env, recreates the containers that read the changed variables,
# and reports the outcome in env-apply/run/status.json for the panel to show.
#
# WHY IT RUNS ON THE HOST
# The backend is the internet-facing process. It is given neither write
# access to .env nor the Docker socket, so the most a hijacked admin session
# can do is ask for a change to a variable this script agrees is editable.
# The list of those is backend/services/env_registry.json, read here from
# the checkout — the same file the backend embeds.
#
# WHEN IT RUNS
# On the Pi, started by the systemd path unit that install.sh sets up, the
# moment request.json appears. By hand anywhere else:
# python3 env-apply/apply.py
# On a dev machine pass the compose files the stack was started with:
# python3 env-apply/apply.py \
# --compose-cmd "docker compose -f docker-compose.yml -f docker-compose.dev.yml"
#
# SAFETY
# - The request is claimed by rename before anything else, so it is consumed
# exactly once and its secrets leave the shared directory even on failure.
# - .env is replaced atomically (temp file + rename) and the previous
# version kept as .env.bak. If compose then rejects the file, the backup
# is put back before anything is recreated.
# - Only the services that read a changed variable are recreated (plus the
# backend, whose own environment is what the panel reports). A plain
# `docker compose up -d` would restart Postgres and nginx for any edit,
# because they load the whole file too; the next deploy catches them up.
# - An flock on run/lock keeps this from overlapping itself or the deploy
# workflow, which takes the same lock.
#
# Standard library only: it has to run on a bare Raspberry Pi OS.
# =============================================================================
import argparse
import datetime
import fcntl
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Values made only of these are written bare; anything else is single-quoted,
# which dotenv reads literally (no $ interpolation, no # comments).
BARE_VALUE = re.compile(r"^[A-Za-z0-9_./:@+,=-]*$")
# How much compose output a failed run reports back to the panel.
OUTPUT_TAIL_LINES = 40
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
def format_line(name, value):
if BARE_VALUE.match(value):
return f"{name}={value}"
return f"{name}='{value}'"
def merge(text, changes):
"""Return .env text with each changed variable's line replaced in place.
Comments, blank lines and ordering are kept. A variable with no line yet
is appended.
"""
remaining = dict(changes)
out = []
for line in text.splitlines():
match = re.match(r"^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=", line)
if match and match.group(2) in changes:
name = match.group(2)
out.append((match.group(1) or "") + format_line(name, changes[name]))
remaining.pop(name, None)
else:
out.append(line)
if remaining:
if out and out[-1].strip():
out.append("")
out.append("# Added from the admin panel")
for name in sorted(remaining):
out.append(format_line(name, remaining[name]))
return "\n".join(out) + "\n"
def write_atomically(path, text):
"""Replace path, keeping its mode and owner."""
stat = os.stat(path)
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".env.tmp.")
try:
with os.fdopen(fd, "w") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, stat.st_mode & 0o7777)
try:
os.chown(tmp, stat.st_uid, stat.st_gid)
except PermissionError:
pass # not root and not the owner; the rename below still works
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
def load_registry(path):
with open(path) as handle:
return {entry["name"]: entry for entry in json.load(handle)}
def check(changes, registry):
"""Refuse anything the backend should never have asked for."""
if not isinstance(changes, dict) or not changes:
raise ValueError("the request changes nothing")
for name, value in changes.items():
entry = registry.get(name)
if entry is None or not entry.get("editable"):
raise ValueError(f"{name} is not editable")
if not isinstance(value, str):
raise ValueError(f"{name} is not a string")
if "'" in value or any(ord(c) < 0x20 or ord(c) == 0x7F for c in value):
raise ValueError(f"{name} holds a character .env cannot carry")
def services_for(names, registry):
services = {"backend"}
for name in names:
services.update(registry[name].get("services", []))
return sorted(services)
def run(cmd, cwd):
result = subprocess.run(
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
)
return result.returncode, result.stdout
def tail(text):
return "\n".join(text.strip().splitlines()[-OUTPUT_TAIL_LINES:])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--env-file", default=os.path.join(ROOT, ".env"))
parser.add_argument("--run-dir", default=os.path.join(ROOT, "env-apply", "run"))
parser.add_argument(
"--registry",
default=os.path.join(ROOT, "backend", "services", "env_registry.json"),
)
parser.add_argument(
"--compose-cmd",
default="docker compose",
help="compose invocation, e.g. to add -f files for a dev stack",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="report what would change and leave everything untouched",
)
args = parser.parse_args()
compose = shlex.split(args.compose_cmd)
compose_dir = os.path.dirname(os.path.abspath(args.env_file))
request_path = os.path.join(args.run_dir, "request.json")
claimed_path = os.path.join(args.run_dir, "request.claimed")
status_path = os.path.join(args.run_dir, "status.json")
backup_path = args.env_file + ".bak"
def report(state, request_id, **extra):
body = {"state": state, "id": request_id, "at": now(), **extra}
tmp = status_path + ".tmp"
with open(tmp, "w") as handle:
json.dump(body, handle)
os.chmod(tmp, 0o644)
os.replace(tmp, status_path)
if args.dry_run:
if not os.path.exists(request_path):
print("No request pending.")
return 0
with open(request_path) as handle:
request = json.load(handle)
registry = load_registry(args.registry)
check(request.get("set"), registry)
names = sorted(request["set"])
print("Would set:", ", ".join(names))
print("Would recreate:", ", ".join(services_for(names, registry)))
return 0
with open(os.path.join(args.run_dir, "lock"), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
# Claim first: after this rename the request cannot be applied twice,
# and a crash below leaves no secrets where the backend can read them.
try:
os.replace(request_path, claimed_path)
except FileNotFoundError:
print("No request pending.")
return 0
try:
with open(claimed_path) as handle:
request = json.load(handle)
finally:
os.unlink(claimed_path)
request_id = str(request.get("id", ""))
try:
registry = load_registry(args.registry)
changes = request.get("set")
check(changes, registry)
names = sorted(changes)
services = services_for(names, registry)
report("applying", request_id, changed=names, services=services)
with open(args.env_file) as handle:
before = handle.read()
shutil.copy2(args.env_file, backup_path)
os.chmod(backup_path, 0o600)
write_atomically(args.env_file, merge(before, changes))
# Catch a file compose cannot parse before any container is
# stopped for it.
code, output = run(compose + ["config", "-q"], compose_dir)
if code != 0:
write_atomically(args.env_file, before)
raise RuntimeError(
"compose rejected the new .env; it was restored.\n" + tail(output)
)
code, output = run(
compose + ["up", "-d", "--no-deps", "--force-recreate"] + services,
compose_dir,
)
if code != 0:
# .env keeps the new values: they are valid, and the usual
# cause here is a container that would not start, which the
# old values would not fix.
raise RuntimeError(
".env was updated but recreating the containers failed.\n"
+ tail(output)
)
except Exception as error: # noqa: BLE001 - everything is reported
report("failed", request_id, output=str(error))
print(f"Failed: {error}", file=sys.stderr)
return 1
report("applied", request_id, changed=names, services=services)
print(f"Applied {', '.join(names)}; recreated {', '.join(services)}.")
return 0
if __name__ == "__main__":
sys.exit(main())
-80
View File
@@ -1,80 +0,0 @@
#!/usr/bin/env bash
# =============================================================================
# install.sh — one-time setup, on the Pi, of the watcher behind the admin
# panel's Environment tab.
#
# WHAT IT DOES
# Installs two systemd units:
# web-server-env-apply.path watches env-apply/run/request.json
# web-server-env-apply.service runs apply.py when that file appears
# The units are generated here rather than committed because they need this
# checkout's absolute path and the user that owns it.
#
# HOW TO RUN
# From the deploy checkout, as the user that runs docker compose there:
# ./env-apply/install.sh
# It calls sudo for the three steps that need root. Re-running is safe and
# is how to pick up a change to the units below.
#
# WHY A PATH UNIT
# PathExists fires as soon as the backend writes the request, and also at
# boot if a request was queued while the Pi was down. apply.py renames the
# request away before doing anything else, so the unit cannot retrigger on
# the same file.
#
# The service runs as the checkout's owner, not root: it needs exactly what
# the deploy workflow has (write .env, run docker compose) and no more.
# DOCKER_API_VERSION and COMPOSE_BAKE mirror .gitea/workflows/deploy.yaml.
# =============================================================================
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUN_USER="$(id -un)"
RUN_DIR="${ROOT}/env-apply/run"
if [ "$RUN_USER" = "root" ]; then
echo "Run this as the user that owns the checkout, not root." >&2
exit 1
fi
if ! command -v python3 >/dev/null; then
echo "python3 is required." >&2
exit 1
fi
# The backend bind-mounts this directory. If Docker creates it first it is
# root-owned and apply.py cannot write its status there.
mkdir -p "$RUN_DIR"
if [ "$(stat -c %U "$RUN_DIR")" != "$RUN_USER" ]; then
sudo chown "$RUN_USER" "$RUN_DIR"
fi
sudo tee /etc/systemd/system/web-server-env-apply.path >/dev/null <<EOF
[Unit]
Description=Watch for .env changes queued from the admin panel
[Path]
PathExists=${RUN_DIR}/request.json
[Install]
WantedBy=multi-user.target
EOF
sudo tee /etc/systemd/system/web-server-env-apply.service >/dev/null <<EOF
[Unit]
Description=Apply a .env change queued from the admin panel
After=docker.service
[Service]
Type=oneshot
User=${RUN_USER}
WorkingDirectory=${ROOT}
Environment=DOCKER_API_VERSION=1.41
Environment=COMPOSE_BAKE=false
ExecStart=/usr/bin/env python3 ${ROOT}/env-apply/apply.py
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now web-server-env-apply.path
echo "Installed. Watching ${RUN_DIR}/request.json as ${RUN_USER}."
echo "Logs: journalctl -u web-server-env-apply.service"
View File
+109
View File
@@ -0,0 +1,109 @@
#!/bin/sh
# =============================================================================
# One-time setup of the `garage` container. Run from the repo root, on the
# host, once the container is up:
#
# garage/bootstrap.sh
#
# Idempotent: every step checks before acting, so re-running it is harmless.
# Garage keeps all of this in the garage_meta volume, so it is only needed on
# a fresh volume — once on stpvm, and again whenever a dev stack starts from
# nothing.
#
# WHY A HOST SCRIPT
# The dxflrs/garage image is FROM scratch: a single binary, no shell. There
# is nothing to run an init script with inside it, so this drives the
# binary through `docker compose exec`.
#
# WHAT IT DOES
# 1. Gives the single node a role in the cluster layout. Until it has one,
# Garage accepts connections but refuses to store anything.
# 2. Creates the bucket (S3_BUCKET, default `uploads`).
# 3. Imports the backend's access key from .env (S3_ACCESS_KEY_ID /
# S3_SECRET_ACCESS_KEY). Importing rather than letting Garage generate
# one keeps .env the single source of truth: a wiped volume comes back
# with the same credentials and the backend needs no change.
# 4. Grants that key read+write on the bucket. garage-webui also browses
# with it: it borrows the first key that has access to a bucket.
# 5. Opens the bucket on the website endpoint, which is what nginx serves
# /uploads/ from, anonymously.
#
# ENV / .env
# S3_ACCESS_KEY_ID required; "GK" + 24 hex chars
# S3_SECRET_ACCESS_KEY required; 64 hex chars
# S3_BUCKET optional, default uploads
# GARAGE_CAPACITY optional, default 20G. Only weights data placement
# between nodes; with one node it is no quota.
# COMPOSE optional, default `docker compose`. Set it to add
# the dev override, e.g.
# COMPOSE="docker compose -f docker-compose.yml -f docker-compose.dev.yml"
# =============================================================================
set -eu
COMPOSE=${COMPOSE:-docker compose}
# Read one KEY=value from .env without sourcing it: .env is not guaranteed to
# be valid shell (unquoted spaces, `$` in secrets). A value already in the
# environment wins, so the script also runs without a .env.
envval() {
eval "current=\${$1:-}"
if [ -n "$current" ]; then
printf '%s' "$current"
return
fi
[ -f .env ] || return 0
grep -E "^$1=" .env | tail -n 1 | cut -d= -f2- | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'$/\1/"
}
garage() {
$COMPOSE exec -T garage /garage "$@"
}
KEY_ID=$(envval S3_ACCESS_KEY_ID)
SECRET=$(envval S3_SECRET_ACCESS_KEY)
BUCKET=$(envval S3_BUCKET)
BUCKET=${BUCKET:-uploads}
CAPACITY=$(envval GARAGE_CAPACITY)
CAPACITY=${CAPACITY:-20G}
KEY_NAME=site-backend
# Garage rejects other shapes at import time with a less helpful message.
if ! printf '%s' "$KEY_ID" | grep -Eq '^GK[0-9a-f]{24}$'; then
echo "S3_ACCESS_KEY_ID must be GK followed by 24 hex chars (try: echo GK\$(openssl rand -hex 12))" >&2
exit 1
fi
if ! printf '%s' "$SECRET" | grep -Eq '^[0-9a-f]{64}$'; then
echo "S3_SECRET_ACCESS_KEY must be 64 hex chars (try: openssl rand -hex 32)" >&2
exit 1
fi
# 1. Layout. `node id -q` prints "<full id>@<addr>"; the id is what
# `layout assign` takes.
if garage layout show 2>/dev/null | grep -q "No nodes currently have a role"; then
NODE_ID=$(garage node id -q 2>/dev/null | cut -d@ -f1)
echo "Assigning node $(printf '%s' "$NODE_ID" | cut -c1-16) (capacity $CAPACITY)"
garage layout assign -z dc1 -c "$CAPACITY" "$NODE_ID"
garage layout apply --version 1
else
echo "Layout already applied"
fi
# 2. Bucket.
if garage bucket info "$BUCKET" >/dev/null 2>&1; then
echo "Bucket $BUCKET exists"
else
garage bucket create "$BUCKET"
fi
# 3. Key.
if garage key info "$KEY_ID" >/dev/null 2>&1; then
echo "Key $KEY_ID exists"
else
garage key import -n "$KEY_NAME" --yes "$KEY_ID" "$SECRET"
fi
# 4 and 5 are idempotent in Garage itself.
garage bucket allow --read --write "$BUCKET" --key "$KEY_ID"
garage bucket website --allow "$BUCKET"
echo "Garage ready: bucket $BUCKET, key $KEY_ID"
+51
View File
@@ -0,0 +1,51 @@
# =============================================================================
# Garage — the S3-compatible object store behind /uploads/.
#
# One node, one copy of everything (replication_factor = 1): this is storage
# on the same disk as the rest of the site, not a resilience layer, so the
# garage_meta and garage_data volumes still need backing up like the others.
#
# NO SECRETS IN THIS FILE. It is committed and mounted read-only into both
# `garage` and `garage-webui`. rpc_secret and admin_token come from the
# GARAGE_RPC_SECRET and GARAGE_ADMIN_TOKEN environment variables, which Garage
# reads in place of the config keys.
#
# Binds are 0.0.0.0 rather than Garage's usual [::]: containers on a bridge
# network without IPv6 may refuse an IPv6 bind. None of these ports is
# published to the host; everything reaches them over app-network.
#
# PORTS
# 3900 S3 API. The backend writes uploads here (signed with the key that
# garage/bootstrap.sh imports); garage-webui browses through it.
# 3901 RPC between Garage nodes. Only this node talks to itself.
# 3902 Website endpoint. Serves a bucket ANONYMOUSLY, choosing it from the
# Host header: "<bucket><root_domain>", so nginx's /uploads/ location
# sends `Host: uploads.web.garage`. Only buckets that bootstrap.sh
# opened with `garage bucket website --allow` are served.
# 3903 Admin API, used by garage-webui and authenticated by admin_token.
# =============================================================================
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "lmdb"
# LMDB can be left unreadable by a crash mid-write; a periodic snapshot of
# the metadata is what `garage meta` restores from.
metadata_auto_snapshot_interval = "6h"
replication_factor = 1
rpc_bind_addr = "0.0.0.0:3901"
rpc_public_addr = "127.0.0.1:3901"
[s3_api]
api_bind_addr = "0.0.0.0:3900"
# Any string works; it only has to match what clients sign with (S3_REGION).
s3_region = "garage"
root_domain = ".s3.garage"
[s3_web]
bind_addr = "0.0.0.0:3902"
root_domain = ".web.garage"
index = "index.html"
[admin]
api_bind_addr = "0.0.0.0:3903"
+3 -3
View File
@@ -20,7 +20,9 @@
; 22 and cannot use the host's sshd, so Gitea runs its own Go SSH server.
; 2222 is published in docker-compose.yml; the deploy workflow clones over
; ssh://git@localhost:2222.
; SSH_DOMAIN is the Pi's Tailscale MagicDNS name, not the public domain: SSH
; SSH_DOMAIN and DOMAIN are not set here: they come from GITEA_SSH_DOMAIN in
; ./.env (see docker-compose.yml). The value is the host's Tailscale
; MagicDNS name, not the public domain: SSH
; (22 and 2222) is not forwarded by the router, so the SSH clone URL Gitea
; shows only works from a device on the tailnet. HTTPS clones go through
; nginx at ROOT_URL and stay public.
@@ -50,7 +52,6 @@ TEMP_PATH = /tmp/gitea/uploads
[server]
APP_DATA_PATH = /var/lib/gitea
SSH_DOMAIN = stppi.tailf20278.ts.net
HTTP_PORT = 3000
ROOT_URL = https://adam-french.co.uk/gitea/
DISABLE_SSH = false
@@ -60,7 +61,6 @@ SSH_PORT = 2222
SSH_LISTEN_PORT = 2222
BUILTIN_SSH_SERVER_USER = git
LFS_START_SERVER = true
DOMAIN = stppi.local
LFS_JWT_SECRET =
OFFLINE_MODE = true
+7 -1
View File
@@ -1,6 +1,6 @@
# =============================================================================
# nginx image — the public edge. Stock nginx plus two tools, three config
# templates and the two partials they include.
# templates, the two partials they include and two static includes.
#
# BASE: nginx:1.27, pinned to a minor version. Official nginx images are
# multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi
@@ -44,5 +44,11 @@ COPY nginx_routes.conf.template /etc/nginx/nginx_routes.conf.template
# Static security-header include, referenced from nginx.conf.template (and
# any location that sets its own add_header). Not templated — no envsubst.
COPY security_headers.conf /etc/nginx/security_headers.conf
# Static http-level include for the JSON request-body log (both configs). Not
# templated: its $request_body etc. are nginx variables, not env vars.
COPY payload_log.conf /etc/nginx/payload_log.conf
# The payload log's directory. Normally a bind mount (./logs/nginx); created
# here so nginx still starts when run without it.
RUN mkdir -p /var/log/nginx/payloads
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+8 -1
View File
@@ -87,6 +87,11 @@
# SILVERBULLET_PUBLIC_HOST / _PORT
# public notes viewer upstream (defaulted below)
# PYTHON_HOST / PYTHON_PORT FastAPI upstream (defaulted below)
# RECEIPT_WEB_UPSTREAM host:port of the receipt printer server on
# stppi, over Tailscale (defaulted below to
# a dead port, so /receipt/ reads "offline")
# RECEIPT_WEB_TOKEN shared secret nginx adds to /receipt/
# requests (defaulted below to empty)
# DEV_MODE "true" only via docker-compose.dev.yml
# CERT_WATCH_INTERVAL optional, seconds between certificate-watch
# polls (default 60). Production only.
@@ -107,11 +112,13 @@ export SILVERBULLET_HOST="${SILVERBULLET_HOST:-silverbullet}"
export SILVERBULLET_PORT="${SILVERBULLET_PORT:-3000}"
export SILVERBULLET_PUBLIC_HOST="${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}"
export SILVERBULLET_PUBLIC_PORT="${SILVERBULLET_PUBLIC_PORT:-3000}"
export RECEIPT_WEB_UPSTREAM="${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}"
export RECEIPT_WEB_TOKEN="${RECEIPT_WEB_TOKEN:-}"
# The envsubst allow-list, defined once and reused by both full-config branches
# and by every partial, so the lists cannot drift apart. It MUST stay
# single-quoted here and be passed as "$ENVSUBST_VARS" (one argument) below.
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT} ${RECEIPT_WEB_UPSTREAM} ${RECEIPT_WEB_TOKEN}'
# Render the shared proxy route table. Done ONCE, here, ahead of the three-way
# decision, rather than inside each branch:
+93 -14
View File
@@ -36,6 +36,15 @@
# (which carry the security headers), the `graphql` rate-limit zone and its
# location, and the limit_req_zone declarations the shared routes refer to.
# =============================================================================
# One worker per CPU. Unset, nginx runs a single worker, and on 2026-10-19 that
# one worker stalled for 4.6 hours: the master kept the container "Up" and the
# tunnel stayed connected, but every request timed out in the TLS handshake.
# With several workers a stuck one only loses the connections it holds; the
# others keep accepting. The healthcheck in docker-compose.yml (and autoheal
# restarting on it) covers the case where they all stall.
worker_processes auto;
events {
worker_connections 1024;
}
@@ -89,18 +98,22 @@ http {
# (Production only; the dev template omits it.
# Its location is at the bottom of this file,
# not in the shared route table.)
# upload 5r/m burst=3 - uploads are 50MB-capable and hit disk; this
# bounds how fast one IP can fill the volume.
# upload 30r/m burst=20 - uploads hit disk; this bounds how fast one IP
# can fill the volume. Generous because only a
# signed-in user can upload and accounts are
# admin-created, and because dropping a batch of
# pictures onto a canvas page uploads them all
# at once — the burst lets ~20 through together.
# hotel_search 3r/m burst=2 - each request holds an upstream call to
# Travelodge/TfL for up to a few minutes and the
# Python side has a single search slot, so this is
# really concurrency protection, not abuse
# protection.
#
# NOTE: the key is the direct client IP. Since nginx is the edge here (no
# CDN or upstream proxy in front), that is correct. If anything is ever put
# in front, these zones must switch to a trusted X-Forwarded-For or every
# visitor will share one bucket.
# NOTE: the key is the client IP, which is only right because of the
# real-IP lines below. Traffic through the Cloudflare tunnel reaches nginx
# from the cloudflared container, so without them every tunnel visitor
# would share that one address and one bucket.
#
# login, api, upload and hotel_search are USED from
# nginx_routes.conf.template, which dev includes too — so
@@ -109,14 +122,34 @@ http {
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=graphql:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=upload:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
# ---- Real client IP behind the Cloudflare tunnel -------------------------
# For connections from the cloudflared container, and only those, replace
# $remote_addr with the visitor's address from Cloudflare's
# CF-Connecting-IP header. Everything downstream then just works: the
# rate-limit keys above, the access log, and the X-Real-IP /
# X-Forwarded-For headers sent upstream.
#
# The trust is pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the whole app-network
# subnet. Direct visitors on the forwarded 80/443 can arrive from the
# bridge gateway, 172.28.0.1, when docker's userland proxy handles the
# connection, so trusting the subnet would let anyone pick their own IP,
# and so their own rate-limit bucket, by sending the header themselves.
# Production only: dev has no tunnel.
set_real_ip_from 172.28.255.250;
real_ip_header CF-Connecting-IP;
log_format compact
'$remote_addr "$request" $status rt=$request_time';
access_log /var/log/nginx/access.log compact;
# JSON request-body log for Dozzle; see payload_log.conf.
include /etc/nginx/payload_log.conf;
# nginx's bundled mime.types has no entry for .mjs, so ES modules would be
# served as application/octet-stream and browsers refuse to execute them.
# This adds the missing mapping without editing the shipped mime.types.
@@ -155,6 +188,15 @@ http {
root /var/www/certbot;
}
# The container healthcheck's target (docker-compose.yml). Answered by
# nginx itself, so it measures whether a worker is serving and nothing
# upstream. Unlogged, or it would put a line in the payload log every
# 30s. Every config's default :80 server has one, setup and dev too.
location = /nginx-health {
access_log off;
return 204;
}
# Redirect everything else to HTTPS
location / {
return 301 https://www.$DOMAIN$request_uri;
@@ -267,14 +309,51 @@ http {
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
# User-uploaded files, served straight off the shared `uploads` volume
# so the Go process never has to stream them. Because these are
# attacker-supplied bytes on our own origin, three headers neutralise
# them: nosniff stops content-type guessing, Content-Disposition inline
# keeps them from being treated as downloads, and the locked-down CSP
# means even an uploaded .html can run no script and load no resource.
# User-uploaded files, served by nginx so the Go process never has to
# stream them. Because these are attacker-supplied bytes on our own
# origin, three headers neutralise them: nosniff stops content-type
# guessing, Content-Disposition inline keeps them from being treated
# as downloads, and the locked-down CSP means even an uploaded .html
# can run no script and load no resource.
#
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the
# Garage bucket's website endpoint, which serves the bucket
# anonymously and picks it by the Host header (garage/garage.toml:
# s3_web); the bucket is reachable only over app-network, so this is
# the only public way in. If Garage has no such file, or is down, the
# request falls through to the shared `uploads` volume
# (@uploads_disk), which holds uploads from before Garage and anything
# the backend wrote there because Garage refused it
# (backend/services/uploads.go). So the bucket is the source of truth
# — deleting a file in garage-webui unpublishes it unless a disk copy
# exists — while a Garage outage only costs files that are nowhere
# else.
# proxy_connect_timeout 2s - Garage is on the same bridge network,
# so a slow connect means it is down; fall back quickly rather
# than after the 60s default.
# proxy_intercept_errors + error_page - Garage's 404 and any 5xx
# (including nginx's own 502 when the garage container doesn't
# exist) become a look at the disk instead.
# Range requests pass through either way, so video seeks.
# @uploads_disk sees the URI after the rewrite (/<name>), hence
# `root /uploads`. The headers are repeated, not inherited: a named
# location is its own location.
location /uploads/ {
alias /uploads/;
rewrite ^/uploads/(.*)$ /$1 break;
proxy_pass $upstream_garage_web;
proxy_set_header Host uploads.web.garage;
proxy_connect_timeout 2s;
proxy_intercept_errors on;
error_page 404 500 502 503 504 = @uploads_disk;
include /etc/nginx/security_headers.conf;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
location @uploads_disk {
root /uploads;
try_files $uri =404;
include /etc/nginx/security_headers.conf;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
+15 -1
View File
@@ -33,6 +33,10 @@
# annotated in nginx_routes.conf.template; the rate-limit reasoning is in
# nginx.conf.template.
# =============================================================================
# As in production; why is in nginx.conf.template.
worker_processes auto;
events {
worker_connections 1024;
}
@@ -54,7 +58,7 @@ http {
# kept equal to production so a limit that would bite there bites here too.
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=upload:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
log_format compact
@@ -62,6 +66,9 @@ http {
access_log /var/log/nginx/access.log compact;
# JSON request-body log for Dozzle; see payload_log.conf.
include /etc/nginx/payload_log.conf;
types {
text/javascript mjs;
}
@@ -86,6 +93,13 @@ http {
listen 80;
server_name $DOMAIN www.$DOMAIN;
# The container healthcheck's target; see nginx.conf.template. Only in
# this block, as in production, where it sits in the :80 server too.
location = /nginx-health {
access_log off;
return 204;
}
include /etc/nginx/nginx_dev_common.conf;
}
+15 -2
View File
@@ -47,14 +47,27 @@
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
# Both /uploads/ blocks are the production ones MINUS
# The /uploads/ blocks (and @uploads_disk) are the production ones MINUS
# `include security_headers.conf`: that file carries HSTS, which must
# never be sent from localhost. That one line is why they are not in
# the shared route table (see WHAT DOES NOT in
# nginx_routes.conf.template). Keep the rest in step with
# nginx.conf.template.
location /uploads/ {
alias /uploads/;
rewrite ^/uploads/(.*)$ /$1 break;
proxy_pass $upstream_garage_web;
proxy_set_header Host uploads.web.garage;
proxy_connect_timeout 2s;
proxy_intercept_errors on;
error_page 404 500 502 503 504 = @uploads_disk;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
location @uploads_disk {
root /uploads;
try_files $uri =404;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
+282 -8
View File
@@ -77,6 +77,22 @@
# The job tracker's container name is fixed in docker-compose.yml, so
# it needs no variable (and no ENVSUBST_VARS entry).
set $upstream_jobs http://jobs:8080;
# Likewise the activity tracker's.
set $upstream_tracker http://activity-tracker:8080;
# And the USACO site's.
set $upstream_usaco http://usaco:8080;
# And the Dozzle log viewer's.
set $upstream_dozzle http://dozzle:8080;
# Garage: its website endpoint (where /uploads/ is served from; see the
# /uploads/ location in nginx.conf.template and
# nginx_dev_common.conf.template) and the garage-webui admin UI.
set $upstream_garage_web http://garage:3902;
set $upstream_garage_webui http://garage-webui:3909;
# The receipt printer's server is the one upstream OFF this host: it
# runs on stppi, which reaches the printer over the home LAN, and is
# reached over Tailscale by IP (MagicDNS names don't resolve in this
# container).
set $upstream_receipt "http://${RECEIPT_WEB_UPSTREAM}";
# ---- Backend API -----------------------------------------------------
# Two patterns repeat through every proxied location below:
@@ -104,7 +120,7 @@
# breaking auth behind TLS termination.
#
# Ordering matters: nginx picks the longest matching prefix location,
# so the specific /ws, /auth/login and /messages/upload blocks (and
# so the specific /ws, /auth/login and /uploads blocks (and
# production's /graphql block in nginx.conf.template) win over the
# catch-all <PREFIX>/ block regardless of file order.
location $BACKEND_ENDPOINT {
@@ -143,8 +159,8 @@
proxy_set_header X-Forwarded-Proto $scheme;
}
location $BACKEND_ENDPOINT/messages/upload {
limit_req zone=upload burst=3 nodelay;
location $BACKEND_ENDPOINT/uploads {
limit_req zone=upload burst=20 nodelay;
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
proxy_pass $upstream_backend;
proxy_set_header Host $host;
@@ -170,6 +186,54 @@
return 301 /radio/;
}
# Dozzle: live view of every container's logs, including the `traffic`
# container's JSON request-body log (see payload_log.conf). It reads
# the Docker socket, so it sits behind the same admin `auth_request`
# as /radio/admin/. No prefix-strip rewrite: DOZZLE_BASE=/dozzle makes
# it serve under the prefix itself. Buffering is off and the read
# timeout long because log tails stream over server-sent events.
location = /dozzle {
return 301 /dozzle/;
}
location /dozzle/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
proxy_pass $upstream_dozzle;
proxy_http_version 1.1;
proxy_buffering off;
proxy_read_timeout 1h;
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;
}
# garage-webui: buckets, keys and a file browser for the Garage object
# store. It holds Garage's admin token, so it sits behind the admin
# `auth_request` like /dozzle/, and its own login is left unset (one
# login, not two). No prefix-strip rewrite: BASE_PATH=/garage makes it
# serve under the prefix itself. The body limit is lifted past the
# server-wide 50M so videos can be uploaded through it, and request
# buffering is off so a large upload streams through instead of
# landing on nginx's disk first.
location = /garage {
return 301 /garage/;
}
location /garage/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
client_max_body_size 2G;
proxy_request_buffering off;
proxy_pass $upstream_garage_webui;
proxy_http_version 1.1;
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;
}
# The icecast ADMIN UI (/radio/admin/*) is a full station-control
# surface — kick sources, change metadata — protected only by the
# icecast admin password, and it was reachable from the public
@@ -211,6 +275,26 @@
proxy_set_header X-Forwarded-Proto $scheme;
}
# Gitea's history views and archives, behind the admin gate. A crawler
# swarm (129k requests from 103k IPs over 2026-10-18/19, so per-IP rate
# limits are useless) walks every file at every commit, and those pages
# are the expensive ones: diffs, blame, tarballs nginx spools to disk.
# 89% of its requests were these shapes; people browsing the code use
# the branch views (src/branch/..., commits/branch/...), which stay
# public, so the CV's repo links still work. Gitea's own
# REQUIRE_SIGNIN_VIEW=expensive would also block src/branch, hence
# doing it here. A regex location, so it wins over /gitea/ above.
location ~ ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/) {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
rewrite ^/gitea/(.*)$ /$1 break;
proxy_pass $upstream_gitea;
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;
}
location /notes {
return 301 /notes/;
}
@@ -343,15 +427,18 @@
# ---- Job tracker (/jobs/) ----
# Its own container (the adamf/job-tracker repo), which serves its SPA
# and its API from the same prefix. The prefix is NOT stripped: the
# app is built to live at /jobs/. There is no auth_request here: the
# SPA's files are public, and every API route that is not checks the
# session itself, by asking the backend's validate-admin with the
# visitor's cookies. ^~ so no regex location can claim a /jobs/ path.
# app is built to live at /jobs/. Gated like /sb/: everything under
# /jobs/ needs the admin session, checked here by auth_request before
# the app sees it (the app still checks the session itself too). Two
# exceptions, below, that a session cookie can never reach. ^~ so no
# regex location can claim a /jobs/ path.
location = /jobs {
return 301 /jobs/;
}
location ^~ /jobs/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
limit_req zone=api burst=20 nodelay;
# "Sync now" on the Settings page runs a whole email sync before
# answering.
@@ -363,6 +450,145 @@
proxy_set_header X-Forwarded-Proto $scheme;
}
# The capture API is called by the userscript from job sites' origins,
# with the capture bearer token rather than cookies, so it cannot pass
# the session gate; the app's CaptureTokenMiddleware guards it.
location ^~ /jobs/api/capture {
limit_req zone=api burst=20 nodelay;
proxy_pass $upstream_jobs;
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;
}
# The userscript itself: userscript managers fetch its @updateURL
# without the session, and it holds no secrets (the token is entered
# after install).
location = /jobs/job-capture.user.js {
proxy_pass $upstream_jobs;
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;
}
# ---- USACO practice log (/usaco/) ----
# Its own container (the usaco repo's site/), shaped like /jobs/: SPA
# and API under one prefix that is NOT stripped, and no
# auth_request, because most of it is public and the app checks the
# session itself for the admin's edits. Gitea's push webhook does not
# come through here: it calls the container directly on the Docker
# network. ^~ so no regex location can claim a /usaco/ path.
location = /usaco {
return 301 /usaco/;
}
location ^~ /usaco/ {
limit_req zone=api burst=20 nodelay;
# An admin edit commits and pushes to Gitea before answering.
proxy_read_timeout 120s;
proxy_pass $upstream_usaco;
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;
}
# ---- Activity tracker (/tracker/) ----
# Its own container (the adamf/ccp repo): an ingest API for device
# collectors, which send batches of events with a per-device bearer
# key, plus a dashboard and setup page. Gated like /sb/: the pages
# and their assets need the admin session, checked here by
# auth_request (the app also checks it itself). Two exceptions,
# below: the API, which collectors call with bearer keys and no
# cookies (the app guards each route, by device key, admin session or
# either), and the public /tracker.user.js. Unlike /jobs/ the prefix
# IS stripped: the server serves /api/v1/... and /readyz from /.
# Collectors must use the www host: the apex 301 would turn their
# POSTs into GETs. Health Auto Export bodies can be several MB; the
# server-wide 50M client_max_body_size covers them.
location = /tracker {
return 301 /tracker/;
}
location ^~ /tracker/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
limit_req zone=api burst=20 nodelay;
rewrite ^/tracker/(.*)$ /$1 break;
proxy_pass $upstream_tracker;
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;
}
location ^~ /tracker/api/v1/ {
limit_req zone=api burst=20 nodelay;
rewrite ^/tracker/(.*)$ /$1 break;
proxy_pass $upstream_tracker;
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;
}
location = /tracker/tracker.user.js {
rewrite ^/tracker/(.*)$ /$1 break;
proxy_pass $upstream_tracker;
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;
}
# ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi
# (not in this stack: that machine reaches the printer on the home LAN). A page
# for printing a note or an uploaded image, plus its API. Behind the
# permission gate on `receipt`, so an account granted it in the admin
# panel can print without being an admin; the prefix IS stripped. The
# server trusts nothing without X-Receipt-Token, which only this proxy
# adds (proxy_set_header replaces any copy the client sent), and is
# told who is printing in X-Remote-User, likewise only set here. The
# token is quoted so an unset one still renders a valid config. When
# stppi is off or unreachable the connect fails fast and
# @receipt_offline answers.
location = /receipt {
return 301 /receipt/;
}
location ^~ /receipt/ {
set $auth_permission receipt;
auth_request /internal/auth/validate;
auth_request_set $auth_user $upstream_http_x_auth_user;
error_page 401 = @auth_denied;
error_page 403 = @auth_forbidden;
error_page 502 504 = @receipt_offline;
limit_req zone=api burst=10 nodelay;
# The server caps uploads at 16 MB; this leaves room for the
# multipart framing around one.
client_max_body_size 17m;
rewrite ^/receipt/(.*)$ /$1 break;
proxy_pass $upstream_receipt;
proxy_connect_timeout 3s;
# An image print (connect, dither, send) takes a few seconds; a
# dead printer socket gives up after escpos's 60 s timeout.
proxy_read_timeout 90s;
proxy_set_header X-Receipt-Token "${RECEIPT_WEB_TOKEN}";
proxy_set_header X-Remote-User $auth_user;
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;
}
location @receipt_offline {
default_type text/plain;
return 503 "The receipt printer machine is offline.\n";
}
# Where the tracker used to be. The SPA routes were client-side, so
# these only catch bookmarks and typed URLs. The userscript's old
# @updateURL lands on the third, which is how installed copies find
@@ -377,7 +603,7 @@
return 301 /jobs/job-capture.user.js;
}
# ---- Admin gate (/sb/, /radio/admin/, /uploads/private/) ----
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/, /uploads/private/) ----
# (/uploads/private/ is declared in the including template, not here;
# it points at the two locations below by name.)
# `auth_request` makes nginx fire a subrequest here before serving the
@@ -393,8 +619,18 @@
# not coming.
# Cookie $http_cookie - the whole point: forward the session
# cookie so the backend can validate it.
# client_max_body_size 0 - the subrequest is checked against THIS
# location's limit using the original
# request's Content-Length, so without it
# a gated location with a higher limit
# (/garage/, 2G) 413s inside the auth
# check and the user sees a 500. Safe:
# the location is internal and never
# reads a body; the real limit is the
# gated location's own.
location = /internal/auth/admin-validate {
internal;
client_max_body_size 0;
rewrite ^ /auth/validate-admin break;
proxy_pass $upstream_backend;
proxy_pass_request_body off;
@@ -405,3 +641,41 @@
location @auth_denied {
return 302 /admin/login?redirect=$request_uri;
}
# ---- Permission gate (/receipt/) ----
# The same auth_request mechanism as the admin gate above, but asking
# GET /auth/validate/<key> whether the session holds one named
# permission (services/permissions.go; admins hold them all). A gated
# location sets $auth_permission and points auth_request here:
#
# set $auth_permission <key>;
# auth_request /internal/auth/validate;
# error_page 401 = @auth_denied;
# error_page 403 = @auth_forbidden;
#
# The variable reaches the subrequest because nginx subrequests share
# the parent request's variables, and `set` runs in the rewrite phase,
# before auth_request's access phase. It must NOT also be given a
# default at server level: a subrequest re-runs the server-level
# rewrite phase, so that `set` would blank the shared value before
# this location reads it. (A location that forgets to set it asks for
# /auth/validate/, which matches no route: denied.) 401 (not signed in) goes to the
# login page as before; 403 (signed in, not granted) goes to a page
# that says so, since sending a signed-in user to log in again only
# shows them "Already signed in". On success the backend returns the
# username in X-Auth-User, which a location can forward with
# auth_request_set (see /receipt/). The body/limit settings are the
# admin-validate location's, for the same reasons.
location = /internal/auth/validate {
internal;
client_max_body_size 0;
rewrite ^ /auth/validate/$auth_permission break;
proxy_pass $upstream_backend;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Cookie $http_cookie;
}
location @auth_forbidden {
return 302 /no-access?path=$request_uri;
}
+6
View File
@@ -45,6 +45,12 @@ http {
root /var/www/certbot;
}
# The container healthcheck's target; see nginx.conf.template.
location = /nginx-health {
access_log off;
return 204;
}
# All other requests should return 404
location / {
return 404;
+55
View File
@@ -0,0 +1,55 @@
# =============================================================================
# Payload log: one JSON line per request, body included, for inspecting what
# actually arrives at the edge. Included at http level by BOTH nginx.conf and
# nginx_dev.conf, so it is plain nginx (no envsubst) like security_headers.conf.
#
# WHERE IT GOES
# /var/log/nginx/payloads/ is bind-mounted from ./logs/nginx on the host.
# The `traffic` container tails the file to its stdout so Dozzle (/dozzle/)
# shows it as its own clean stream of JSON. The `compact` access log is
# untouched and still goes to the container's stdout.
#
# WHAT IS NOT CAPTURED
# - Bodies larger than client_body_buffer_size: nginx spools those to a
# temp file and leaves $request_body empty. Uploads therefore log with an
# empty body (their size is still in `len`).
# - Bodies of requests nginx answers itself (redirects, static files): it
# never reads them, so $request_body is empty there too.
# - Responses. nginx cannot log a proxied response body.
# - auth_request subrequests: log_subrequest is off by default.
# =============================================================================
# 64k keeps ordinary JSON/GraphQL bodies in memory (the default is 16k on
# 64-bit), which is the only case where $request_body is filled. It is a
# per-request buffer only allocated when a body arrives, so the cost is small.
client_body_buffer_size 64k;
# Redaction: any body mentioning a password, token or secret is logged as a
# placeholder rather than having the field stripped, because nginx has no JSON
# parser. That catches /auth/login, the GraphQL login and change-password
# mutations and the refresh-token call in one rule. Over-matching (a query that
# merely selects a field named *token*) costs a hidden body, never a leak.
# map is evaluated lazily at log time, after the body has been read.
map $request_body $logged_body {
"~*(password|token|secret)" "[redacted]";
default $request_body;
}
# escape=json makes each line valid JSON (quotes, newlines and control bytes
# in the body are escaped), so Dozzle renders it as fields and `jq` reads it.
log_format payloads escape=json '{'
'"time":"$time_iso8601",'
'"ip":"$remote_addr",'
'"method":"$request_method",'
'"host":"$host",'
'"uri":"$request_uri",'
'"status":"$status",'
'"rt":"$request_time",'
'"ctype":"$content_type",'
'"len":"$content_length",'
'"referer":"$http_referer",'
'"ua":"$http_user_agent",'
'"body":"$logged_body"'
'}';
access_log /var/log/nginx/payloads/payloads.log payloads;
+3 -4
View File
@@ -15,9 +15,8 @@ add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" alway
# locked-down CSP by declaring Content-Security-Policy again themselves
# (a later add_header of the same name within one response wins).
#
# ponytail: no site-wide CSP from nginx here. The SPA needs
# 'wasm-unsafe-eval' for its Rust module, Gitea (proxied at /gitea/) relies
# on inline <script> blocks its own templates generate, so a shared
# ponytail: no site-wide CSP from nginx here. Gitea (proxied at /gitea/)
# relies on inline <script> blocks its own templates generate, so a shared
# script-src would need 'unsafe-inline' — which voids almost all of CSP's
# value. If a real CSP matters again, give the SPA document its own
# script-src 'self' 'wasm-unsafe-eval' location, separate from Gitea.
# script-src 'self' location, separate from Gitea.
+3 -3
View File
@@ -94,9 +94,9 @@ Their plumbing is in two places, shared by any route added later:
outside is a 404 before its body is validated.
Every route uses one model, `MODEL` in `claude.py`: the `CLAUDE_MODEL` variable,
or `claude-sonnet-5-5` when it is blank. It is chosen on the admin panel's
Environment tab from `claude-haiku-4-5`, `claude-sonnet-5-5` and
`claude-opus-5-5`, and saving it there restarts this service. The request is
or `claude-sonnet-5-5` when it is blank. It is set in `.env` to one of
`claude-haiku-4-5`, `claude-sonnet-5-5` and `claude-opus-5-5`; recreate this
service after changing it. The request is
shaped per model by `_model_options`: a model that thinks gets
`output_config.effort: "low"` and 4,000 tokens of headroom on top of the
caller's `max_tokens`, because thinking is billed against it; Haiku 4.5 gets
+4 -5
View File
@@ -22,12 +22,11 @@ log = logging.getLogger(__name__)
T = TypeVar("T", bound=BaseModel)
# Which model every call uses. CLAUDE_MODEL is set from the admin panel's
# Environment tab (it is in backend/services/env_registry.json, whose `options`
# list is what the panel offers); changing it there recreates this container,
# which is why reading it once at import is enough. Blank means the default.
# Which model every call uses. CLAUDE_MODEL comes from .env; changing it means
# recreating this container, which is why reading it once at import is enough.
# Blank means the default.
#
# The registry's options are the ids this module has been written for. Another
# The ids listed in .env.example are the ones this module has been written for. Another
# id is passed through as it is, treated as a model that thinks (see below);
# if the API does not know it, every call fails with its `failed` message and
# the reason is in this service's log.
-11
View File
@@ -76,17 +76,6 @@ def test_haiku_gets_the_plain_request(monkeypatch):
assert call == {"model": "claude-haiku-4-5", "max_tokens": 64, "messages": MESSAGES}
def test_the_default_model_is_one_the_admin_panel_offers():
"""CLAUDE_MODEL's options in the env registry are what the Environment tab lets an admin pick."""
import json
from pathlib import Path
registry = json.loads((Path(__file__).parents[2] / "backend/services/env_registry.json").read_text())
(entry,) = [v for v in registry if v["name"] == "CLAUDE_MODEL"]
assert claude.DEFAULT_MODEL in entry["options"]
assert "python" in entry["services"]
def test_the_answer_is_found_after_a_thinking_block():
reply = SimpleNamespace(
stop_reason="end_turn",
+115
View File
@@ -0,0 +1,115 @@
// =============================================================================
// renovate.json5 — dependency-update PRs (this repo's Dependabot).
//
// WHY RENOVATE AND NOT DEPENDABOT
// Dependabot only runs on GitHub, and this repo lives on the self-hosted
// Gitea. Renovate does the same job against Gitea's API. It is run by
// .gitea/workflows/renovate.yaml on the stack's own runner, which is where
// the platform, endpoint and token are set; this file is only *what* to
// update.
//
// WHAT IT WATCHES
// gomod backend/go.mod (go.sum and `go mod tidy` come along)
// npm vue/package.json + package-lock.json
// pip_requirements python/requirements.txt, requirements-dev.txt
// dockerfile every */Dockerfile FROM line
// docker-compose every image: in docker-compose*.yml
// custom (below) the images deploy.yaml and renovate.yaml `docker run`
//
// NOTHING IS AUTOMERGED, on purpose: a merge to main IS a deploy. Each
// Renovate branch is pushed to Gitea, so deploy.yaml's `test` job runs on it
// (go vet/test and pytest) — but that job skips the Vue build, so an npm PR is
// only proven by `make check-vue` locally or by the deploy itself (where a
// failed build stops before any container is replaced).
// =============================================================================
{
$schema: "https://docs.renovatebot.com/renovate-schema.json",
extends: ["config:recommended"],
timezone: "Europe/London",
// Replaces config:recommended's list rather than adding to it. .deprecated/
// holds parked services whose manifests are not built any more.
ignorePaths: ["**/node_modules/**", ".deprecated/**"],
// A release has to have been out this long before a PR proposes it, so a
// compromised or quickly-yanked version never reaches a branch.
minimumReleaseAge: "3 days",
postUpdateOptions: ["gomodTidy"],
customManagers: [
{
// deploy.yaml runs the tests in `docker run golang:… / python:…`, which
// no built-in manager reads. They must match backend/Dockerfile and
// python/Dockerfile (see deploy.yaml's header), so they share those
// images' groups below and land in the same PR. Also matches the
// Renovate image in renovate.yaml, and the copies in comments, which
// keeps those accurate.
customType: "regex",
managerFilePatterns: ["/^\\.gitea/workflows/[^/]+\\.ya?ml$/"],
matchStrings: ["(?<depName>golang|python|renovate/renovate):(?<currentValue>[0-9][\\w.-]*)"],
datasourceTemplate: "docker",
},
],
packageRules: [
// The job tracker, usaco and activity-tracker images are built by their
// own repos and roll themselves out on `:latest`; there is nothing here
// to bump.
{
matchDatasources: ["docker"],
matchPackageNames: ["adam-french.co.uk/**"],
enabled: false,
},
// A Postgres major needs a dump and restore of the dbdata volume (the new
// server refuses the old data directory), so it is done by hand, never
// from a PR.
{
matchDatasources: ["docker"],
matchPackageNames: ["postgres"],
matchUpdateTypes: ["major"],
enabled: false,
},
// Non-major updates batched per ecosystem, so the runner tests one branch
// a week per language instead of one per package. Majors stay separate.
// These come before the named groups below because a later matching rule
// wins: gqlgen and the go directive must not be swept in here.
{
matchManagers: ["gomod"],
matchUpdateTypes: ["minor", "patch", "digest"],
groupName: "Go modules (non-major)",
},
{
matchManagers: ["npm"],
matchUpdateTypes: ["minor", "patch"],
groupName: "npm (non-major)",
},
{
matchManagers: ["pip_requirements"],
matchUpdateTypes: ["minor", "patch"],
groupName: "Python packages (non-major)",
},
// One PR per toolchain: the Dockerfile base, the CI test image and (for
// Go) the go.mod `go` directive move together.
{
matchPackageNames: ["golang", "go"],
groupName: "Go toolchain",
},
{
matchDatasources: ["docker"],
matchPackageNames: ["python"],
groupName: "Python image",
},
// gqlgen's runtime and gqlparser are versioned together. If a bump breaks
// the build, regenerate (`go run github.com/99designs/gqlgen generate`)
// on the branch.
{
matchPackageNames: ["github.com/99designs/gqlgen", "github.com/vektah/gqlparser/**"],
groupName: "gqlgen",
},
],
}
+2 -26
View File
@@ -1,5 +1,5 @@
# =============================================================================
# Vue frontend image — compiles Rust to WASM, then builds the SPA.
# Vue frontend image — builds the SPA.
#
# THIS IS A BUILD CONTAINER, NOT A SERVER. In production the container runs
# `vite build` into /output (the shared vue_dist volume) and EXITS. nginx then
@@ -7,16 +7,7 @@
# success case, not a failure. The dev override replaces the CMD with the Vite
# dev server, and then it does stay running.
#
# STAGE 1 — WASM
# Builds crates/stp_wasm with wasm-pack into src/wasm. Only that crate
# directory is copied in, so touching Vue source never invalidates the (slow)
# Rust layer. The two cache mounts persist the cargo registry and the Rust
# target directory between builds on the host — on a Raspberry Pi this turns
# a very long compile into an incremental one. src/wasm is gitignored: it is
# generated, never committed.
#
# STAGE 2 — Vue
# package.json + package-lock.json are copied first so `npm ci` is cached
# package.json + package-lock.json are copied first so `npm ci` is cached
# independently of source changes; the npm cache is also a BuildKit cache
# mount. `npm ci` (not `npm install`) installs exactly the lockfile, so a
# rebuild can never silently pick up a different dependency version.
@@ -26,21 +17,7 @@
# --emptyOutDir is required: /output is a mounted volume, and vite refuses to
# clear a directory outside the project root without it. Without the flag,
# stale assets from a previous build would accumulate and be served.
#
# Note stage 2 is not named and is the final stage; both base images are
# multi-arch so this builds on the Pi unchanged.
# =============================================================================
# Stage 1: Build WASM from Rust
FROM rust:slim AS wasm-builder
RUN rustup target add wasm32-unknown-unknown \
&& cargo install wasm-pack
WORKDIR /wasm
COPY crates/stp_wasm/ crates/stp_wasm/
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/wasm/crates/stp_wasm/target \
wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm
# Stage 2: Build Vue frontend
FROM node:22-slim
RUN apt-get update && apt-get install -y make git && rm -rf /var/lib/apt/lists/*
WORKDIR /app
@@ -48,5 +25,4 @@ COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
COPY --from=wasm-builder /wasm/src/wasm/ src/wasm/
CMD ["sh", "-c", "npx vite build --outDir /output --emptyOutDir"]
+160 -20
View File
@@ -44,7 +44,7 @@ has to be a bare uvicorn.
```
src/
main.js entry point — awaits the wasm init, then mounts <App>
main.js entry point — mounts <App>
App.vue empty shell; all chrome lives in the layouts
router/index.js route table + the single admin route guard
graphql.js the entire GraphQL client (one axios POST)
@@ -55,8 +55,6 @@ src/
views/ page components, one directory per area
assets/styles.css design tokens + base styles (see Styling)
js/ small shared helpers
wasm/ GENERATED by `npm run build:wasm`; gitignored, do not edit
crates/stp_wasm the Rust source for the above
```
## Routing
@@ -65,13 +63,15 @@ Two layout shells, defined in `src/router/index.js`:
| Path | Layout | Notes |
| --- | --- | --- |
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint) |
| `/stp` | DefaultLayout | The personal home page: the widget grid |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
| `/automata`, `/hotels`, `/shrines/*` | DefaultLayout | |
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint): a box canvas, page key `index`; the old fixed page is its starter layout, `views/landing/landingLayout.js` |
| `/stp` | DefaultLayout | The personal home page: an ordinary canvas page (the `Page` with slug `stp`) served by the catch-all, see "The /stp canvas" below |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin`. The login page is everyone's, admin or not |
| `/account`, `/no-access` | DefaultLayout | `views/account/Account.vue`, guarded by `meta.requiresSignIn`: the gated services a non-admin has been granted. `/no-access` is where nginx's permission gate sends a signed-in visitor without the grant |
| `/automata`, `/hotels` | DefaultLayout | |
| `/shrines`, `/shrines/*` | DefaultLayout | All canvas pages via the catch-all: `/shrines` is an index whose links are Link boxes placed by hand |
| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there |
| `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts |
| `:pathMatch(.*)*` | DefaultLayout | 404 |
| `:pathMatch(.*)*` | DefaultLayout | `views/canvas/CanvasPage.vue`: an admin-created canvas page if one exists at the path, else the 404 (with a "create a page here" form for admins) |
Everything except the landing page is a dynamic `import()`, so Vite gives each
view its own chunk.
@@ -124,15 +124,14 @@ the Vite proxy in dev).
The backend's REST routes go through `src/api.js`, the same idea for plain JSON:
```js
const body = await api.get("/admin/logs", { fallback: "Failed to load logs" });
const songs = await api.get("/radio/songs", { fallback: "Failed to load songs" });
await api.post("/radio/upload", formData, { fallback: "Upload failed" });
```
It prefixes `/api`, resolves to the response body, and on failure throws an
`ApiError` whose `message` is the backend's `{"error": "..."}` string when there
is one, otherwise the `fallback` the caller passed. `err.status` carries the
HTTP status for the few callers that branch on it (the Environment tab treats a
401/403 while polling as "the apply rotated my session"). Any other option is
HTTP status for callers that need to branch on it. Any other option is
passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
### Which one to use
@@ -141,10 +140,34 @@ passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
| --- | --- |
| reading or writing the site's data model | `gql()`, from a store |
| doing list/create/update/delete on one GraphQL type | a store built with `createCrudStore()` |
| calling a backend REST route (uploads, admin tooling, OAuth start) | `api` |
| storing a file, or showing one that was stored | `uploadFile()` and friends from `@/uploads` |
| calling a backend REST route (admin tooling, OAuth start) | `api` |
| reading the Python service's NDJSON streams | `views/hotels/hotelsStream.js` — incremental `fetch`, not `api` |
| probing `/radio/stream` | bare `axios.head` — it is Icecast, not the API |
### Uploading files
`src/uploads.js` is the one way to store a file:
```js
import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
// <input type="file" :accept="ACCEPT.images" @change="onPick">
const url = await uploadFile(file); // "/uploads/3f9c….png", public and permanent
```
It posts to `/api/uploads`; the backend (`backend/services/uploads.go`) owns
the allowed types, the 10MB limit and the file name, and stores the file in
Garage. A refused file rejects with an `ApiError` whose message can be shown
as-is. `kindOf(url)` says image/video/audio/file, `tagFor(url)` gives the
markup for a box, `isUploadUrl(url)` checks a URL from someone else before
rendering it, and `mediaSize(file)` reads an image or video's dimensions
(from a `File` or a stored URL). `listUploads()` (admin only) lists every
public upload, newest first; `components/util/UploadPicker.vue` is the modal
that shows them as a grid to choose from.
`{ private: true }` (admin only) is for private chat attachments; never use
it for anything shown in a canvas box, whose sandboxed frame has no cookie.
New views should not call `gql()` or `axios` directly (a few small admin forms
still call `gql()` for a one-off mutation). A view that needs data gets a
store; a view that needs a REST route calls `api`.
@@ -169,6 +192,8 @@ true only once a fetch has succeeded, meaning the data is real. Waiting on
| `auth` | current user (`ensureLoaded()`, see Routing), plus login/logout mutations |
| `posts`, `favorites`, `activity`, `songs`, `steam` | mirror one slice of `homeData` via an `immediate` watch, and keep a placeholder value until real data arrives |
| `places` | CRUD via `createCrudStore`; sign-in only, so it is fetched lazily |
| `boxes` | CRUD via `createCrudStore`, one store per canvas page: `useBoxesStore(page)`. Public read (admin-only boxes excepted), admin write |
| `pages` | CRUD via `createCrudStore`; the admin-created canvas pages. Public read (admin-only pages excepted), admin write |
| `messages` | the chat WebSocket — not GraphQL at all |
| `models` | dormant; not imported anywhere |
@@ -187,12 +212,126 @@ Two factories keep the repeated shapes in one place:
differences between types: `itemsKey` (the name the array is
exposed under), `insert` (`"prepend"` or `"append"`), `deleteReturns`
(`"object"` for `deletePlace`, `"boolean"` for a delete that returns a
scalar — a scalar must not be given a selection set) and `extend` for extra actions.
scalar — a scalar must not be given a selection set), `args` (fixed
arguments for the list query, e.g. the boxes store's `page`) and `extend`
for extra actions.
The error contract is deliberate: `fetch()` never throws and records the
failure on `error`; the mutations throw, so the form that called them can
show the message and keep what was typed.
## The /stp canvas
`/stp` is a set of **boxes** (`Box` in GraphQL, `stores/boxes.js`) that an admin
creates, drags, resizes and edits in the browser. Changes save to the database,
so every visitor sees the saved layout. The canvas is `views/home3/BoxCanvas.vue`,
and it is not only `/stp`: every box has a `page` key, and the same component
renders any page's boxes.
- **Pages.** `"index"` is the landing page
(`Landing.vue`), which is nothing but the canvas. Any other key is the slug of a **`Page`** (GraphQL
type, `stores/pages.js`), an admin-created page served at `/<slug>` by the
router's catch-all (`views/canvas/CanvasPage.vue`). Pages are created from
the admin panel's Pages tab (which also has a "New shrine" form, a blank page
under `shrines/`), or from the 404 of the address you want; each can start
from a layout in `views/canvas/pageStarters.js` (Blank, Notes board, Old /stp grid). Title, address and visibility are under "Page
settings" on the page; renaming moves its boxes, deleting takes them too.
`/stp` is one of these pages too (slug `stp`): it used to have its own route
(`Home3.vue`, now legacy), and the backend creates its `Page` row once at
start-up (`ensureStpPage` in `backend/services/database.go`), so it can be
renamed, hidden or deleted like any other.
The server refuses slugs that an SPA or nginx route would answer first
(`validateSlug` in `backend/graph/page_helpers.go`) — add to that list when
adding a route.
- **Backgrounds.** Each page key can have its own background (`Background` in
GraphQL, `stores/background.js`): a colour, an image, and whether the image
fills the window, fits inside it or tiles. Admins set it with the
"Background" button next to "Edit layout" (`BackgroundEditor.vue`), which
previews live and takes an uploaded, dropped or already-uploaded image
(`UploadPicker`). `DefaultLayout` paints
it behind the whole window, navbar included, while that canvas is mounted,
and falls back to the halftone. Renaming or deleting a page carries its
background along; an admin-only page's background is hidden with it.
- **Saved layouts.** A **`Layout`** (GraphQL type, `stores/layouts.js`) is a
named copy of one page's boxes and background, made with the "Layouts"
button next to "Background" (`LayoutPanel.vue`). "Load here" copies a layout
onto the page on screen; the admin panel's Pages tab copies one onto any page
without opening it. Loading onto a page with boxes asks whether to replace
them or add on top (copies stacked above). A replace first saves the page
as a layout called "<page> before <layout>, <time>", so it can be undone by
loading that back. They are copies, not links: editing a page never changes
a layout or another page. That is also how a layout moves: save it on one
page, load it on another. The copying happens on the server
(`backend/graph/layout_helpers.go`); the browser only sees names and box
counts. All of it is admin-only, since a layout keeps admin-only boxes.
- **Components.** A **`Component`** (GraphQL type, `stores/components.js`) is
a named HTML box. "+ New box" lists them and places a copy, an ordinary box.
The "Components" button (`ComponentPanel.vue`) can also place one
**linked**: the box has a `componentId`, the server answers with the
component's html in its `html` (`fillLinked` in
`backend/graph/component_helpers.go`), and saving the html in `BoxEditor`
saves the component, so every linked box on every page changes. Only the
html is shared; title, geometry, frame, shadow and visibility stay each box's own.
"Save as component" in the editor makes a component from an html box and
links it; "Detach" gives a linked box its own copy. Deleting a component
detaches its boxes first, so no page changes. A layout keeps both the link
and the html, and loading it links again only if the component still
exists. The built-in starters in `templates.js` are not listed directly:
"Import built-ins" in the panel makes them components, after which they can
be edited or deleted like the rest. Admin-only throughout.
- **Admin only.** A box or a page can be marked admin-only. The server never
sends those to anyone else, so they are fit for private notes; admins see
such boxes outlined, with a 🔒 in edit mode. The "Note" template starts
admin-only.
- **Coordinates.** `x`/`y`/`w`/`h` are px on a fixed 1400px-wide design canvas.
`BoxCanvas.vue` draws the canvas at that width and shrinks it with
`transform: scale()` to fit the window, so the arrangement is identical at
every desktop width. `BoxFrame.vue` divides pointer deltas by that scale.
`z` is the CSS z-index.
- **Two kinds of box.** `kind: "widget"` shows a built-in Vue widget by name
from `widgetRegistry.js`. The registry keys are stored data, so don't rename
them. `kind: "html"` shows admin-written HTML (`HtmlBox.vue`) in an
`<iframe sandbox="allow-scripts">` **without `allow-same-origin`**. Its
scripts run, but they have an opaque origin: they can't read cookies, call
`/api` as the visitor, or touch the page. That sandbox is what makes storing
script in the database acceptable, so never add `allow-same-origin`.
`fetch()` from a box only reaches keyless APIs that answer
`Access-Control-Allow-Origin: *` (the Weather template uses Open-Meteo).
- **Site look inside the iframe.** `frameStyles.js` copies the colour tokens in
and inlines the two fonts as `data:` URLs. An opaque origin can't load
`/fonts/` without CORS headers.
- **Editing.** Admins get an "Edit layout" toggle at desktop width. Geometry
saves on pointer release, and the box is moved locally first and put back if
the save fails. Dragging snaps a box's edges and centre to other boxes'
edges and centres and to the canvas's sides, centre and top, within 6 screen
px, and draws a pink guide along each line it then shares; a resize snaps
the dragged edge the same way. Elsewhere the 5px grid applies. The pure
geometry is `alignment.js`; the admin bar's "Align" button turns it off (kept
per browser by `editorPrefs.js`), and holding Ctrl/⌘ mid-drag skips it.
`BoxEditor.vue` is the side panel. Settings save on change;
HTML is a draft that previews live and saves with Save or Ctrl/Cmd+S, or
automatically on leaving the box (selecting another, clicking empty canvas,
Done, ✕).
CodeMirror is loaded only when that panel opens; the panel is teleported to
`<body>`. Its width (drag the left edge, double-click to reset) and the
code's text size (A−/A+, or Ctrl/Cmd +/−/0 in the editor) are kept per
browser in localStorage by `editorPrefs.js`; the canvas pads itself by the
same width so it rescales beside the panel.
Image and video files dropped onto the canvas in edit mode are uploaded and
each becomes an unframed box at the drop point. "Insert upload" stores a
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
tag for it at the cursor; "Choose upload" does the same with a file already
stored, and "+ From uploads…" in the admin bar makes a box from one, as a
drop would (`UploadPicker`). Built-in starter HTML is in `templates.js` (imported as components, above); links in a box
need `target="_top"` or `_blank` (the Link templates set it), or they open
inside the frame. A canvas given a `starter` has an import button in edit
mode (it confirms first if the page isn't empty): only `/` has one, "Import
old landing page", which recreates the old bio and links. The old `Home.vue`
grid (`defaultLayout.js`) is the "Old /stp grid" starter for a new page.
- **Phones (≤700px)** get no canvas: boxes stack full-width in `(y, x)` order at
their saved height, skipping any with `hideOnMobile`. There is no separate
mobile layout. To change the order, move boxes on the desktop canvas.
## Component conventions
- Layout and one-off tweaks go in Tailwind utilities; reach for a scoped
@@ -223,10 +362,8 @@ Two factories keep the repeated shapes in one place:
- **Production** (`npm run build`): `dist/` is built into the nginx container
and served as static files, with nginx doing the same reverse-proxying.
Note `npm run build` runs `build:wasm` first, which needs **wasm-pack** on the
PATH. If you only want the Vue bundle and `src/wasm/` is already populated,
`npm run build:js` (plain `vite build`) skips that step. It is also the local
check that the app still compiles — there is no test runner or linter.
`npm run build` is a plain `vite build`. It is also the local check that the
app still compiles — there is no test runner or linter.
## Live vs legacy views
@@ -235,16 +372,17 @@ in its header comment; the summary:
| File | Status |
| --- | --- |
| `views/home/Home.vue` | live (`/stp`) — imports **Intro2** and **Gym2** |
| `views/home3/Home3.vue` | legacy: `/stp`'s old route, before it became a canvas `Page`; no route. The rest of `views/home3/` (`BoxCanvas.vue` and friends) is live |
| `views/home/shrines/{Shrines,Demoman,GTO,Evangelion,Skipskipbenben}.vue` | the old `/shrines` index and hand-written shrines (Demoman a video wall, the rest `<Wip />`), unrouted; shrines are canvas pages now |
| `views/home/Home.vue` | legacy fixed grid that `/stp` used to be; no route. Its widgets are still live through `home3/widgetRegistry.js` |
| `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported |
| `views/home/Gym.vue` | superseded by `Gym2.vue`; not imported |
| `views/home2/Home2.vue` | reachable at `/stp2`, but a static mock and unlinked |
| `views/home/BadApple.vue` | unfinished ASCII video player; not imported |
| `views/CV/CVProgramming.vue` | live — the only CV template listed in `CV.vue` |
| `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable |
| `views/unused/CoverLetters.vue` | **live** despite the directory — it is the "Cover Letter" tab on `/cv` |
| `views/CV/CoverLetters.vue` (+ `CoverSnippetBank.vue`, `coverLetter.js`) | live — the "Cover Letter" tab on `/cv`. Sections of draggable paragraphs; an admin also gets saved letters (`CoverLetter`) and a paragraph bank (`CoverSnippet`), both `@admin` |
| `views/unused/Notes.vue` | no route points at it; not imported |
| `components/util/wasm/AutoScroll.vue` | Rust port of the JS AutoScroll; not imported |
| `components/util/{MusicPlayer,ObjectTable}.vue` | not imported |
| `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported |
| `stores/models.js`, `js/mobile-automata.mjs` | not imported |
@@ -291,6 +429,8 @@ Note that Tailwind's spacing unit is set to **3px** (not the default 4px), so `p
- Never hard-code a colour in a component; use a token. The one exception is `<canvas>` drawing (MobileAutomata), which can't read CSS variables.
- Home widgets: wrap the title in `<Header>`; admin-only create forms use `<CreateToggle v-model="showCreate">` in the header's `#action` slot and render the form inside a `<Modal v-model="showCreate">` so it pops up over the page instead of replacing the widget.
- Crossfading content in place: `<Transition name="fade">` inside a `position: relative` parent. Route changes use `<Transition name="slide">`.
- Keyboard focus and reduced motion are handled globally in `styles.css`: every focusable element gets a pink `:focus-visible` ring (text fields a pink border instead), and `prefers-reduced-motion` collapses transitions and CSS animations. Both are low-specificity, so a component's own focus or outline style wins. A JS animation loop has to check `matchMedia("(prefers-reduced-motion: reduce)")` itself, as `Headline.vue` does.
- Forms are real `<form @submit.prevent>` elements with `type="submit"` / `type="button"` on their buttons, not `@keyup.enter` on each input: Enter then submits from any field and password managers recognise the login. A form that saves shows its error inline and disables its button while the request is out (`useCreateForm` returns `error` and `submitting` for this).
## Production Build
-136
View File
@@ -1,136 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bumpalo"
version = "3.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "js-sys"
version = "0.3.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"
dependencies = [
"once_cell",
"wasm-bindgen",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "stp_wasm"
version = "0.1.0"
dependencies = [
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "syn"
version = "2.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "wasm-bindgen"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"
dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"
dependencies = [
"js-sys",
"wasm-bindgen",
]
-25
View File
@@ -1,25 +0,0 @@
[package]
name = "stp_wasm"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib"]
[dependencies]
js-sys = "0.3.85"
wasm-bindgen = "0.2.108"
web-sys = { version = "0.3.85", features = [
"console",
"Document",
"Element",
"HtmlElement",
"Window",
"Animation",
"CssStyleDeclaration",
"ResizeObserver",
"ResizeObserverEntry",
"ResizeObserverSize",
"EventTarget",
"MouseEvent",
] }
-259
View File
@@ -1,259 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;
const SPEED: f64 = 0.0005; // % per frame
const PAUSE: i32 = 2000; // ms at top/bottom
struct Inner {
el: HtmlElement,
pos: f64,
direction: f64, // 1.0 = down, -1.0 = up
hovered: bool,
cached_scroll_height: f64,
raf_id: Option<i32>,
pause_timeout_id: Option<i32>,
resize_observer: Option<web_sys::ResizeObserver>,
// closures kept alive
tick_closure: Option<Closure<dyn FnMut()>>,
resize_closure: Option<Closure<dyn FnMut(js_sys::Array)>>,
mouseenter_closure: Option<Closure<dyn FnMut()>>,
mouseleave_closure: Option<Closure<dyn FnMut()>>,
start_after_pause_closure: Option<Closure<dyn FnMut()>>,
}
#[wasm_bindgen]
pub struct AutoScroller {
inner: Rc<RefCell<Inner>>,
}
impl Inner {
fn measure_scroll_height(&mut self) {
self.cached_scroll_height = self.el.scroll_height() as f64;
}
fn stop_loop(&mut self) {
let window = web_sys::window().unwrap();
if let Some(id) = self.raf_id.take() {
window.cancel_animation_frame(id).ok();
}
if let Some(id) = self.pause_timeout_id.take() {
window.clear_timeout_with_handle(id);
}
}
}
fn start_loop(inner: &Rc<RefCell<Inner>>) {
{
let mut s = inner.borrow_mut();
s.stop_loop();
}
schedule_tick(inner);
}
fn schedule_tick(inner: &Rc<RefCell<Inner>>) {
let inner_clone = Rc::clone(inner);
// Create a fresh tick closure each frame
let closure = Closure::once(move || {
tick(&inner_clone);
});
let mut s = inner.borrow_mut();
let window = web_sys::window().unwrap();
let id = window
.request_animation_frame(closure.as_ref().unchecked_ref())
.unwrap();
s.raf_id = Some(id);
// Store the closure to keep it alive until the frame fires
s.tick_closure = Some(closure);
}
fn tick(inner: &Rc<RefCell<Inner>>) {
let should_continue;
{
let mut s = inner.borrow_mut();
s.raf_id = None;
if s.hovered {
return;
}
if s.cached_scroll_height == 0.0 {
drop(s);
schedule_tick(inner);
return;
}
let reached_bottom = s.pos >= 1.0;
let reached_top = s.pos <= 0.0;
if reached_bottom {
s.pos = 0.999;
s.direction = -1.0;
drop(s);
schedule_pause(inner);
return;
} else if reached_top && s.direction == -1.0 {
s.pos = 0.001;
s.direction = 1.0;
drop(s);
schedule_pause(inner);
return;
}
s.pos += s.direction * SPEED;
s.el.set_scroll_top((s.pos * s.cached_scroll_height) as i32);
should_continue = true;
}
if should_continue {
schedule_tick(inner);
}
}
fn schedule_pause(inner: &Rc<RefCell<Inner>>) {
{
let mut s = inner.borrow_mut();
s.stop_loop();
}
let inner_clone = Rc::clone(inner);
let closure = Closure::once(move || {
start_loop(&inner_clone);
});
let mut s = inner.borrow_mut();
let window = web_sys::window().unwrap();
let id = window
.set_timeout_with_callback_and_timeout_and_arguments_0(
closure.as_ref().unchecked_ref(),
PAUSE,
)
.unwrap();
s.pause_timeout_id = Some(id);
s.start_after_pause_closure = Some(closure);
}
#[wasm_bindgen]
impl AutoScroller {
#[wasm_bindgen(constructor)]
pub fn new(el: HtmlElement) -> AutoScroller {
let inner = Rc::new(RefCell::new(Inner {
el,
pos: 0.0,
direction: 1.0,
hovered: false,
cached_scroll_height: 0.0,
raf_id: None,
pause_timeout_id: None,
resize_observer: None,
tick_closure: None,
resize_closure: None,
mouseenter_closure: None,
mouseleave_closure: None,
start_after_pause_closure: None,
}));
// Set up mouseenter listener
{
let inner_clone = Rc::clone(&inner);
let closure = Closure::wrap(Box::new(move || {
let mut s = inner_clone.borrow_mut();
s.hovered = true;
s.stop_loop();
}) as Box<dyn FnMut()>);
let s = inner.borrow();
s.el
.add_event_listener_with_callback("mouseenter", closure.as_ref().unchecked_ref())
.unwrap();
drop(s);
inner.borrow_mut().mouseenter_closure = Some(closure);
}
// Set up mouseleave listener
{
let inner_clone = Rc::clone(&inner);
let closure = Closure::wrap(Box::new(move || {
{
let mut s = inner_clone.borrow_mut();
s.hovered = false;
if s.cached_scroll_height > 0.0 {
s.pos = s.el.scroll_top() as f64 / s.cached_scroll_height;
}
}
start_loop(&inner_clone);
}) as Box<dyn FnMut()>);
let s = inner.borrow();
s.el
.add_event_listener_with_callback("mouseleave", closure.as_ref().unchecked_ref())
.unwrap();
drop(s);
inner.borrow_mut().mouseleave_closure = Some(closure);
}
AutoScroller { inner }
}
pub fn start(&self) {
// Measure initial scroll height
self.inner.borrow_mut().measure_scroll_height();
// Set up resize observer
let inner_clone = Rc::clone(&self.inner);
let resize_closure = Closure::wrap(Box::new(move |_entries: js_sys::Array| {
inner_clone.borrow_mut().measure_scroll_height();
}) as Box<dyn FnMut(js_sys::Array)>);
let observer =
web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref()).unwrap();
// Clone the element ref and drop the borrow before calling observe(),
// because observe() can fire the resize callback synchronously,
// which would conflict with an active borrow.
let el_clone = self.inner.borrow().el.clone();
observer.observe(&el_clone);
{
let mut s = self.inner.borrow_mut();
s.resize_observer = Some(observer);
s.resize_closure = Some(resize_closure);
}
// Start with a pause then begin scrolling
schedule_pause(&self.inner);
}
pub fn destroy(&self) {
let mut s = self.inner.borrow_mut();
s.stop_loop();
if let Some(observer) = s.resize_observer.take() {
observer.disconnect();
}
if let Some(ref closure) = s.mouseenter_closure {
s.el
.remove_event_listener_with_callback(
"mouseenter",
closure.as_ref().unchecked_ref(),
)
.ok();
}
if let Some(ref closure) = s.mouseleave_closure {
s.el
.remove_event_listener_with_callback(
"mouseleave",
closure.as_ref().unchecked_ref(),
)
.ok();
}
s.mouseenter_closure = None;
s.mouseleave_closure = None;
s.resize_closure = None;
s.tick_closure = None;
s.start_after_pause_closure = None;
}
}
-135
View File
@@ -1,135 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;
const SPEED: f64 = 0.5; // pixels per frame
struct Inner {
container: HtmlElement,
item1: HtmlElement,
offset: f64,
cached_width: f64,
raf_id: Option<i32>,
resize_observer: Option<web_sys::ResizeObserver>,
// closures kept alive
animate_closure: Option<Closure<dyn FnMut()>>,
resize_closure: Option<Closure<dyn FnMut(js_sys::Array)>>,
}
#[wasm_bindgen]
pub struct HeadlineScroller {
inner: Rc<RefCell<Inner>>,
}
impl Inner {
fn measure_width(&mut self) {
let container_width = self.container.offset_width() as f64;
let item_width = self.item1.scroll_width() as f64;
self.cached_width = container_width.max(item_width);
}
}
fn schedule_frame(inner: &Rc<RefCell<Inner>>) {
let inner_clone = Rc::clone(inner);
let closure = Closure::once(move || {
animate(&inner_clone);
});
let mut s = inner.borrow_mut();
let window = web_sys::window().unwrap();
let id = window
.request_animation_frame(closure.as_ref().unchecked_ref())
.unwrap();
s.raf_id = Some(id);
s.animate_closure = Some(closure);
}
fn animate(inner: &Rc<RefCell<Inner>>) {
{
let mut s = inner.borrow_mut();
s.raf_id = None;
if s.cached_width == 0.0 {
drop(s);
schedule_frame(inner);
return;
}
s.offset -= SPEED;
if s.offset <= -s.cached_width {
s.offset += s.cached_width;
}
let transform = format!("translateX({}px)", s.offset);
s.container.style().set_property("transform", &transform).ok();
}
schedule_frame(inner);
}
#[wasm_bindgen]
impl HeadlineScroller {
#[wasm_bindgen(constructor)]
pub fn new(container: HtmlElement, item1: HtmlElement) -> HeadlineScroller {
let inner = Rc::new(RefCell::new(Inner {
container,
item1,
offset: 0.0,
cached_width: 0.0,
raf_id: None,
resize_observer: None,
animate_closure: None,
resize_closure: None,
}));
HeadlineScroller { inner }
}
pub fn start(&self) {
// Measure initial width
self.inner.borrow_mut().measure_width();
// Set up resize observer
let inner_clone = Rc::clone(&self.inner);
let resize_closure = Closure::wrap(Box::new(move |_entries: js_sys::Array| {
inner_clone.borrow_mut().measure_width();
}) as Box<dyn FnMut(js_sys::Array)>);
let observer =
web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref()).unwrap();
// Clone the element ref and drop the borrow before calling observe(),
// because observe() can fire the resize callback synchronously,
// which would conflict with an active borrow.
let container_clone = self.inner.borrow().container.clone();
observer.observe(&container_clone);
{
let mut s = self.inner.borrow_mut();
s.resize_observer = Some(observer);
s.resize_closure = Some(resize_closure);
}
// Start animation loop
schedule_frame(&self.inner);
}
pub fn destroy(&self) {
let mut s = self.inner.borrow_mut();
let window = web_sys::window().unwrap();
if let Some(id) = s.raf_id.take() {
window.cancel_animation_frame(id).ok();
}
if let Some(observer) = s.resize_observer.take() {
observer.disconnect();
}
s.animate_closure = None;
s.resize_closure = None;
}
}
-5
View File
@@ -1,5 +0,0 @@
mod auto_scroll;
mod headline;
pub use auto_scroll::AutoScroller;
pub use headline::HeadlineScroller;
+233 -348
View File
@@ -8,10 +8,13 @@
"name": "nginx-html",
"version": "0.0.0",
"dependencies": {
"@codemirror/lang-html": "^6.4.11",
"@codemirror/view": "^6.43.14",
"@mdit/plugin-katex": "^0.24.1",
"@tailwindcss/vite": "^4.1.18",
"@vueuse/core": "^14.2.1",
"axios": "^1.13.2",
"codemirror": "^6.0.2",
"dompurify": "^3.3.3",
"katex": "^0.16.27",
"markdown-it": "^14.1.0",
@@ -25,9 +28,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.1",
"vite": "^7.3.2",
"vite-plugin-top-level-await": "^1.6.0",
"vite-plugin-vue-devtools": "^8.0.3",
"vite-plugin-wasm": "^3.6.0"
"vite-plugin-vue-devtools": "^8.0.3"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
@@ -488,6 +489,139 @@
"node": ">=6.9.0"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.11.1",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz",
"integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.11",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.13.1",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz",
"integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/streamparser": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search": {
"version": "6.7.2",
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.2.tgz",
"integrity": "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.37.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.6",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/streamparser": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz",
"integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==",
"license": "MIT"
},
"node_modules/@codemirror/view": {
"version": "6.43.14",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.14.tgz",
"integrity": "sha512-hC45YnmJNR1rz42OF57BLoQNFMV12/13drnvibDsR2quNDmldcb4WvYVV81hFQg56i9lcqQMEDqilhX2QDcGQQ==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
@@ -949,6 +1083,69 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lezer/common": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.3.tgz",
"integrity": "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",
"integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.6",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz",
"integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.11",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.11.tgz",
"integrity": "sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
"license": "MIT"
},
"node_modules/@mdit/helper": {
"version": "0.22.1",
"resolved": "https://registry.npmjs.org/@mdit/helper/-/helper-0.22.1.tgz",
@@ -1026,24 +1223,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/@rollup/plugin-virtual": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@rollup/plugin-virtual/-/plugin-virtual-3.0.2.tgz",
"integrity": "sha512-10monEYsBp3scM4/ND4LNH5Rxvh3e/cVeL3jWTgZ2SrQ+BmUoQcopVQvnaMcOnykb1VkxUFuDAN+0FnpTFRy2A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
@@ -1369,293 +1548,6 @@
"win32"
]
},
"node_modules/@swc/core": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.15.24.tgz",
"integrity": "sha512-5Hj8aNasue7yusUt8LGCUe/AjM7RMAce8ZoyDyiFwx7Al+GbYKL+yE7g4sJk8vEr1dKIkTRARkNIJENc4CjkBQ==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@swc/counter": "^0.1.3",
"@swc/types": "^0.1.26"
},
"engines": {
"node": ">=10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/swc"
},
"optionalDependencies": {
"@swc/core-darwin-arm64": "1.15.24",
"@swc/core-darwin-x64": "1.15.24",
"@swc/core-linux-arm-gnueabihf": "1.15.24",
"@swc/core-linux-arm64-gnu": "1.15.24",
"@swc/core-linux-arm64-musl": "1.15.24",
"@swc/core-linux-ppc64-gnu": "1.15.24",
"@swc/core-linux-s390x-gnu": "1.15.24",
"@swc/core-linux-x64-gnu": "1.15.24",
"@swc/core-linux-x64-musl": "1.15.24",
"@swc/core-win32-arm64-msvc": "1.15.24",
"@swc/core-win32-ia32-msvc": "1.15.24",
"@swc/core-win32-x64-msvc": "1.15.24"
},
"peerDependencies": {
"@swc/helpers": ">=0.5.17"
},
"peerDependenciesMeta": {
"@swc/helpers": {
"optional": true
}
}
},
"node_modules/@swc/core-darwin-arm64": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.15.24.tgz",
"integrity": "sha512-uM5ZGfFXjtvtJ+fe448PVBEbn/CSxS3UAyLj3O9xOqKIWy3S6hPTXSPbszxkSsGDYKi+YFhzAsR4r/eXLxEQ0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-darwin-x64": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.15.24.tgz",
"integrity": "sha512-fMIb/Zfn929pw25VMBhV7Ji2Dl+lCWtUPNdYJQYOke+00E5fcQ9ynxtP8+qhUo/HZc+mYQb1gJxwHM9vty+lXg==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-arm-gnueabihf": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.15.24.tgz",
"integrity": "sha512-vOkjsyjjxnoYx3hMEWcGxQrMgnNrRm6WAegBXrN8foHtDAR+zpdhpGF5a4lj1bNPgXAvmysjui8cM1ov/Clkaw==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-arm64-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.15.24.tgz",
"integrity": "sha512-h/oNu+upkXJ6Cicnq7YGVj9PkdfarLCdQa8l/FlHYvfv8CEiMaeeTnpLU7gSBH/rGxosM6Qkfa/J9mThGF9CLA==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-arm64-musl": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.15.24.tgz",
"integrity": "sha512-ZpF/pRe1guk6sKzQI9D1jAORtjTdNlyeXn9GDz8ophof/w2WhojRblvSDJaGe7rJjcPN8AaOkhwdRUh7q8oYIg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-ppc64-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-ppc64-gnu/-/core-linux-ppc64-gnu-1.15.24.tgz",
"integrity": "sha512-QZEsZfisHTSJlmyChgDFNmKPb3W6Lhbfo/O76HhIngfEdnQNmukS38/VSe1feho+xkV5A5hETyCbx3sALBZKAQ==",
"cpu": [
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-s390x-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-s390x-gnu/-/core-linux-s390x-gnu-1.15.24.tgz",
"integrity": "sha512-DLdJKVsJgglqQrJBuoUYNmzm3leI7kUZhLbZGHv42onfKsGf6JDS3+bzCUQfte/XOqDjh/tmmn1DR/CF/tCJFw==",
"cpu": [
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-x64-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.15.24.tgz",
"integrity": "sha512-IpLYfposPA/XLxYOKpRfeccl1p5dDa3+okZDHHTchBkXEaVCnq5MADPmIWwIYj1tudt7hORsEHccG5no6IUQRw==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-x64-musl": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.15.24.tgz",
"integrity": "sha512-JHy3fMSc0t/EPWgo74+OK5TGr51aElnzqfUPaiRf2qJ/BfX5CUCfMiWVBuhI7qmVMBnk1jTRnL/xZnOSHDPLYg==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-win32-arm64-msvc": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.15.24.tgz",
"integrity": "sha512-Txj+qUH1z2bUd1P3JvwByfjKFti3cptlAxhWgmunBUUxy/IW3CXLZ6l6Gk4liANadKkU71nIU1X30Z5vpMT3BA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-win32-ia32-msvc": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.15.24.tgz",
"integrity": "sha512-15D/nl3XwrhFpMv+MADFOiVwv3FvH9j8c6Rf8EXBT3Q5LoMh8YnDnSgPYqw1JzPnksvsBX6QPXLiPqmcR/Z4qQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-win32-x64-msvc": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.15.24.tgz",
"integrity": "sha512-PR0PlTlPra2JbaDphrOAzm6s0v9rA0F17YzB+XbWD95B4g2cWcZY9LAeTa4xll70VLw9Jr7xBrlohqlQmelMFQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/counter": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@swc/types": {
"version": "0.1.26",
"resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.26.tgz",
"integrity": "sha512-lyMwd7WGgG79RS7EERZV3T8wMdmPq3xwyg+1nmAM64kIhx5yl+juO2PYIHb7vTiPgPCj8LYjsNV2T5wiQHUEaw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@swc/counter": "^0.1.3"
}
},
"node_modules/@swc/wasm": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/wasm/-/wasm-1.15.24.tgz",
"integrity": "sha512-vFjzOE8dhJcfeTbM4+HO9Qy58IINV0ysqStAgw81uds+KqCeUDM9huN+SZ5lWZ6U+5nf8VcZoEw5N81xMtAidg==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@tailwindcss/node": {
"version": "4.1.18",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
@@ -2413,6 +2305,21 @@
],
"license": "CC-BY-4.0"
},
"node_modules/codemirror": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
"integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/commands": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/search": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -2456,6 +2363,12 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -3686,6 +3599,12 @@
"punycode": "^2.1.1"
}
},
"node_modules/style-mod": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz",
"integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==",
"license": "MIT"
},
"node_modules/superjson": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",
@@ -3825,20 +3744,6 @@
"integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
"license": "(WTFPL OR MIT)"
},
"node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"dev": true,
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/vite": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
@@ -3982,22 +3887,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/vite-plugin-top-level-await": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/vite-plugin-top-level-await/-/vite-plugin-top-level-await-1.6.0.tgz",
"integrity": "sha512-bNhUreLamTIkoulCR9aDXbTbhLk6n1YE8NJUTTxl5RYskNRtzOR0ASzSjBVRtNdjIfngDXo11qOsybGLNsrdww==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rollup/plugin-virtual": "^3.0.2",
"@swc/core": "^1.12.14",
"@swc/wasm": "^1.12.14",
"uuid": "10.0.0"
},
"peerDependencies": {
"vite": ">=2.8"
}
},
"node_modules/vite-plugin-vue-devtools": {
"version": "8.0.5",
"resolved": "https://registry.npmjs.org/vite-plugin-vue-devtools/-/vite-plugin-vue-devtools-8.0.5.tgz",
@@ -4073,16 +3962,6 @@
"vite": "^3.0.0-0 || ^4.0.0-0 || ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0"
}
},
"node_modules/vite-plugin-wasm": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.6.0.tgz",
"integrity": "sha512-mL/QPziiIA4RAA6DkaZZzOstdwbW5jO4Vz7Zenj0wieKWBlNvIvX5L5ljum9lcUX0ShNfBgCNLKTjNkRVVqcsw==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"vite": "^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8"
}
},
"node_modules/vue": {
"version": "3.5.26",
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.26.tgz",
@@ -4125,6 +4004,12 @@
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
"license": "MIT"
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
},
"node_modules/wsl-utils": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.1.0.tgz",
+7 -8
View File
@@ -7,19 +7,20 @@
"node": "^20.19.0 || >=22.12.0"
},
"scripts": {
"build:wasm": "wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm",
"dev": "vite",
"build": "npm run build:wasm && vite build",
"build:js": "vite build",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@mdit/plugin-katex": "^0.24.1",
"@codemirror/lang-html": "^6.4.11",
"@codemirror/view": "^6.43.14",
"@mdit/plugin-katex": "^0.25.0",
"@tailwindcss/vite": "^4.1.18",
"@vueuse/core": "^14.2.1",
"axios": "^1.13.2",
"codemirror": "^6.0.2",
"dompurify": "^3.3.3",
"katex": "^0.16.27",
"katex": "^0.19.0",
"markdown-it": "^14.1.0",
"markdown-it-wikilinks": "^1.4.0",
"pinia": "^3.0.4",
@@ -31,8 +32,6 @@
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.1",
"vite": "^7.3.2",
"vite-plugin-top-level-await": "^1.6.0",
"vite-plugin-vue-devtools": "^8.0.3",
"vite-plugin-wasm": "^3.6.0"
"vite-plugin-vue-devtools": "^8.0.3"
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
* OAuth starts — everything backend/README.md lists as "not GraphQL").
*
* It does two things a bare axios call does not:
* - prefixes `/api`, so callers name the route (`api.get("/admin/logs")`);
* - prefixes `/api`, so callers name the route (`api.get("/radio/songs")`);
* - turns a failure into an ApiError whose `message` is the backend's
* `{"error": "..."}` body when there is one. Every handler reports errors
* in that shape, and each view used to dig it out of `err.response` itself.
+38 -2
View File
@@ -6,9 +6,11 @@
* every token is BOTH a utility class in templates
* (text-primary, bg-surface, font-heading) AND a CSS variable
* in component <style> blocks (var(--color-primary)).
* 3. Base default look of plain HTML elements (the dark theme)
* 3. Base default look of plain HTML elements (the dark theme),
* including the keyboard focus ring
* 4. Components reusable classes: gif borders, A4 sheet, halftone background
* 5. Transitions <Transition name="slide"> and <Transition name="fade">
* 5. Transitions <Transition name="slide"> and <Transition name="fade">,
* and the reduced-motion override
* 6. Print
*
* The CV pages are a light theme: src/layouts/CVLayout.vue re-points the colour
@@ -150,6 +152,26 @@ textarea::placeholder {
opacity: 0.5;
}
/* Keyboard focus. Nothing on the site had a visible focus ring, so tabbing
through it was blind. Text fields get the border treatment the login form
had; everything else an outline. The selectors are wrapped in :where() to
keep their specificity just above the bare `input` rule above, so any
component with its own focus or outline style (BoxFrame, the hotels and
automata forms) still wins. Not in an @layer: unlayered rules such as
`input` above would then beat it whatever its specificity. */
:where(*):focus-visible {
outline: 2px solid var(--color-tertiary);
outline-offset: 2px;
}
:where(
input:not([type="checkbox"], [type="radio"], [type="range"], [type="file"]),
textarea
):focus-visible {
outline: none;
border-color: var(--color-tertiary);
box-shadow: 0 0 0 2px var(--color-quaternary);
}
table {
color: var(--color-primary);
border: 1px solid var(--color-primary);
@@ -255,6 +277,20 @@ th {
opacity: 0;
}
/* Visitors who ask the OS for less motion get instant route changes and
crossfades. The JS animation loops check the same query themselves
(Headline.vue for the navbar marquee). */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* ------------------------------------------------------------------ */
/* 6. Print */
/* ------------------------------------------------------------------ */

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