Author SHA1 Message Date
adamfandClaude Opus 5.5 b6baf9c1a2 Serve the Partner Radar demo at radar.DOMAIN
Test and deploy / test (push) Successful in 2m36s
Test and deploy / deploy (push) Successful in 44s
Weekly Maintenance / maintenance (push) Successful in 7m17s
Renovate / renovate (push) Successful in 8m7s
A new Caddy site proxies radar.DOMAIN to radar-web:80, the web container of
the adamf/cto stack, which joins app-network from its own compose project.
It has its own rate-limit zones (radar, radar_login) and answers 503
"offline" when that stack is down. The name is added to Caddy's network
aliases and cloudflared's extra_hosts like www.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 15:50:22 +00:00
adamfandClaude Opus 5.5 30d6056bc0 Move the retired nginx and certbot into .deprecated
Test and deploy / test (push) Successful in 1m35s
Test and deploy / deploy (push) Successful in 1m10s
Nothing references nginx/ or certbot/ since the cutover to Caddy (daa2a46),
so they join quartz, hasura and autoheal in .deprecated/, with a README
entry on how to bring them back. The rollback steps in DEPLOYMENT.md §7 now
revert this commit and then the cutover. The host keeps ./certbot/conf (the
last certbot certificate, valid until 2027-01-20) and ./logs/nginx until the
rollback is no longer wanted; .gitignore still covers certbot/conf and
certbot/www for that reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 23:35:33 +00:00
adamfandClaude Opus 5.5 daa2a465fb Cut the edge over from nginx and certbot to Caddy
Test and deploy / test (push) Successful in 3m30s
Test and deploy / deploy (push) Has been cancelled
Caddy takes nginx's place in compose: ports 80/443, the fixed address
172.28.255.251 that cloudflared pins the public names to, the network
aliases, the healthcheck and the autoheal label. nginx and certbot are
removed from compose; Caddy already holds its own certificates in
./caddy/data, obtained while it ran beside nginx. `traffic` now tails
logs/caddy/payloads.log, and the dev override switches Caddy to its dev
sites instead of putting nginx in DEV_MODE.

Docs and comments that described nginx's behaviour now describe Caddy's:
CLAUDE.md, DEPLOYMENT.md (topology, boot paths, TLS, rate limits, runbook
with a rollback, rough edges), the READMEs, .env.example and the comments
in the backend, Python service, Vue source and infra files. nginx/ and
certbot/ stay in the repo as the rollback until this has settled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 23:28:28 +00:00
adamfandClaude Opus 5.5 e09b90afaa Add Caddy beside nginx as the replacement edge
Test and deploy / test (push) Successful in 1m32s
Test and deploy / deploy (push) Successful in 29m5s
caddy/ reproduces nginx's routes, gates, /notes/ privacy denials, uploads
(bucket first, then disk), rate limits, real-IP and headers in one shared
route table, with certificates obtained over DNS-01 in-process instead of by
certbot. Until the cutover it serves nothing public: loopback-only ports
8880/8443, no network aliases, its own address. The image build validates
the prod and dev configs, so a broken Caddyfile stops the deploy before any
container is replaced (`make check-caddy` is the same build).

caddy/edge_test.sh checks the privacy boundary and the gates and prints
everything else for diffing nginx against Caddy before switching over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 22:45:35 +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
226 changed files with 23914 additions and 5465 deletions
+18 -1
View File
@@ -1,6 +1,6 @@
# .deprecated
STATUS: nothing in here is live. No compose file, nginx template or script
STATUS: nothing in here is live. No compose file, Caddyfile or script
references this directory. It is kept, not deleted, in line with the repo's
"legacy is kept" convention; the full history is also in git.
@@ -32,3 +32,20 @@ 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` (caddy; nginx until 2026-11-17). This copy is the old
`all` variant, kept for reference.
## nginx/ and certbot/
The public edge until 2026-11-17, when Caddy (`caddy/`) replaced both:
`nginx/` is the image (three templates chosen at start by `entrypoint.sh`,
the shared route table, the payload log and security-header includes), and
`certbot/entrypoint.sh` obtained and renewed the certificate that nginx
reloaded through a sentinel file. Their compose services were removed in
`daa2a46`. The last certbot certificate is still in `./certbot/conf` on the
host, valid until 2027-01-20.
To bring them back: revert the commit that moved them here and then `daa2a46`;
DEPLOYMENT.md §7 ("Roll back to nginx") has the commands.
@@ -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
@@ -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"]
@@ -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:
@@ -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;
@@ -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;
}
@@ -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;
@@ -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;
}
@@ -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;
@@ -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.
+172
View File
@@ -0,0 +1,172 @@
# =============================================================================
# .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. Nothing reads EMAIL any more (it was certbot's).
DOMAIN=localhost
EMAIL=[email protected]
# --- Cloudflare Tunnel -------------------------------------------------------
# cloudflared is disabled in dev, and dev's Caddy sites use `tls internal`,
# so neither token is ever used.
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
+146 -34
View File
@@ -7,26 +7,22 @@
# it parses the file, before any container exists. This is how container
# names and published ports are built.
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
# variables inside that container. nginx, backend, db, icecast2,
# certbot and gitea all do this.
# variables inside that container. backend, db and icecast2 do this.
# The `python` and `jobs` services deliberately do neither wholesale — each
# uses an explicit `environment:` allow-list, so neither sees the site's
# database password, the JWT secret, or any key it does not use.
#
# HOW TO USE
# cp .env.example .env then fill in every value.
# 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 +33,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,9 +48,12 @@ 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.
# GITEA_HOST is the container name AND the Caddy upstream host.
# The three secrets below are passed as GITEA__section__KEY overrides so the
# committed app.ini.template can keep those fields blank. Generate each as a
# long random hex string.
@@ -63,6 +63,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.
@@ -120,14 +124,10 @@ ADZUNA_APP_ID=
ADZUNA_APP_KEY=
REED_API_KEY=
# --- Services that nginx substitutes but no longer runs -----------------------
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
# compose service uses them today. Harmless if blank.
# --- SilverBullet (notes) ---------------------------------------------------
# Two instances over the same vault: the admin-only editor at /sb/, and the
# public read-only notes site at /notes/ (which replaced Quartz). All four
# default in nginx/entrypoint.sh and docker-compose.yml, so they can be left
# default in docker-compose.yml (the caddy service's list), so they can be left
# blank.
SILVERBULLET_HOST=silverbullet
SILVERBULLET_PORT=3000
@@ -137,8 +137,8 @@ SILVERBULLET_PUBLIC_PORT=3000
SILVERBULLET_GIT_INTERVAL=
# --- Go backend --------------------------------------------------------------
# BACKEND_HOST is the container name and the nginx upstream.
# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then
# BACKEND_HOST is the container name and the Caddy upstream.
# BACKEND_ENDPOINT is the public URL prefix Caddy mounts the API at and then
# strips; the Vue app's GraphQL client assumes /api.
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
# everyone out.
@@ -168,7 +168,7 @@ SPOTIFY_AUTH_STATE=
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
# with it, and a live-broadcasting client authenticates to the liquidsoap
# harbor port with it. Anyone holding it can take over the stream.
# LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host.
# LIQUIDSOAP_HARBOR_PORT is the only non-Caddy port published to the host.
ICECAST_SOURCE_PASSWORD=
ICECAST_RELAY_PASSWORD=
ICECAST_ADMIN_USER=
@@ -180,20 +180,38 @@ LIQUIDSOAP_HARBOR_MOUNT=/live
LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ----------------------------------------------------------
# DOMAIN is the APEX domain with no scheme and no www; certbot requests both
# it and www.DOMAIN on one certificate, and nginx canonicalises to www.
# EMAIL is the Let's Encrypt account address for expiry notices.
# DOMAIN is the APEX domain with no scheme and no www; Caddy gets a
# certificate for it and for www.DOMAIN, and canonicalises to www.
# EMAIL was certbot's Let's Encrypt account address. Nothing reads it since
# the move to Caddy, which registers its ACME account without one; it stays
# for the nginx/certbot rollback (.deprecated/, DEPLOYMENT.md §7).
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 Caddy's DNS-01 challenge (caddy/sites/prod.caddy):
# My Profile -> API Tokens -> Create Token -> "Edit zone DNS", limited to this
# zone, then add Zone -> Zone -> Read on the same zone (the template only has
# DNS -> Edit). Certificates are issued and renewed with no inbound port, so
# the router forwards nothing. Required in production: Caddy has no HTTP
# challenge to fall back to. Changing it needs `docker compose up -d caddy`.
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 +231,99 @@ 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 Caddy 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 Caddy 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 caddy`.
RECEIPT_WEB_TOKEN=
# --- Partner Radar (radar.DOMAIN) ----------------------------------------------
# A separate compose project on this host (adamf/cto, `make stpvm`), whose web
# container joins app-network as `radar-web`. Only set this to point
# radar.DOMAIN somewhere else.
# RADAR_UPSTREAM=radar-web:80
# 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 Caddy 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 Caddy 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
+12 -10
View File
@@ -1,15 +1,20 @@
icecast2/fallback_music/*
.claude/
!icecast2/fallback_music/.gitkeep
# The retired certbot's data (code in .deprecated/certbot/), still on the
# host as the rollback certificate
certbot/conf
certbot/www
# Caddy's certificates, keys and ACME account (docker-compose.yml)
caddy/data/
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 +24,6 @@ gitea-runner/.runner
gitea-runner/act_runner
gitea-runner/nohup.out
# Rust build artifacts
**/target/
# Python bytecode
__pycache__/
*.pyc
@@ -30,9 +32,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 +73,6 @@ __screenshots__/
.deploy
*.xcf
sync-secrets.sh
# Local-only outstanding-work notes, deliberately not published
TODO-NEXT.md
@@ -82,3 +80,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/
+20 -15
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, `docker compose config` for both compose files, and the Caddy image build, which validates `caddy/` for both modes. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`, `check-caddy`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it.
### Full stack (dev mode, HTTP only)
```
cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
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 serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. 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).
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served by Caddy (production) or proxied to Vite dev server (dev mode).
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. 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. Caddy proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and Caddy 404s `/py/internal/`. The model is one setting, 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/`; Caddy 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). Caddy 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.
**Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit <zone> <events> <window>`) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated at the edge because a crawler swarm hammers them; the branch views stay public. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7.
## Backend Structure
@@ -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. Caddy's *permission gate* (`import permission_gate <key>` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its route from `import admin_gate` to `import permission_gate <key>`. `/auth/validate-admin` and the admin gate are unchanged.
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
- **Environment 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.
@@ -109,7 +114,7 @@ Each area has its own README with the detail that doesn't belong here:
## Conventions
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, the edge's route order). 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.
+479 -242
View File
@@ -2,17 +2,21 @@
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.
— compose, the Caddy edge, TLS, the runner, and the runbook.
Everything runs on a single Raspberry Pi, as Docker containers on one bridge
network, behind one nginx.
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 Caddy (nginx and certbot until 2026-11-17).
---
## 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: Caddy 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
@@ -20,7 +24,7 @@ Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
:80 :443| :3000 / :2222 :8001
v v v
+--------------+ +--------+ +-------------+
| nginx | | gitea | | liquidsoap |
| caddy | | gitea | | liquidsoap |
| (TLS, SPA, | | (git + | | harbor |
| reverse | | CI) | | (live DJ) |
| proxy) | +--------+ +------+------+
@@ -41,56 +45,91 @@ backend icecast2 gitea sb sb-pub python | |
| db | postgres:16
+------+ (app database + gitea database)
vue one-shot build container -> writes vue_dist volume -> nginx serves it
certbot no ports; shares ./certbot/conf and ./certbot/www with nginx
vue one-shot build container -> writes vue_dist volume -> caddy serves it
```
### 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 |
| --------------------------------------------- | ----------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------- |
| caddy (the edge) | `caddy` | 80, 443 (fixed IP `172.28.255.251`) | everything below | **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 Caddy `forward_auth`; capture API and userscript public, bearer-token) | no |
| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by Caddy `forward_auth`; `/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 |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of Caddy, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by Caddy `forward_auth`; 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 Caddy `forward_auth`; Caddy adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no |
| Partner Radar (adamf/cto, its own compose project) | `radar-web` (alias of that project's `web`, on app-network) | 80 | `radar.<DOMAIN>`, the whole host (its own login, no gate; zones `radar` and `radar_login`). Started from the cto checkout with `make stpvm`; 503 "offline" when that stack is down | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy caddy) | `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 Caddy `forward_auth`) | no |
Container names come from `.env`, and nginx builds its upstreams from the same
variables. **Renaming a `*_HOST` value renames the container and repoints nginx
in one step — never change one without the other.**
Container names come from `.env`, and Caddy builds its upstreams from the same
variables (passed through the caddy service's `environment:` list). **Renaming
a `*_HOST` value renames the container and repoints Caddy in one step — never
change one without the other.**
### Things nginx does that are easy to miss
### Things Caddy does that are easy to miss
- **Canonical host.** `http://` → `https://`, and apex → `www`. The SPA, the
cookies and the CORS rules all assume `www.<DOMAIN>`.
- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/py` are stripped
— but `/sb/` and `/notes/` deliberately are NOT: SilverBullet is told its own base path via
`SB_URL_PREFIX` and builds its service-worker scope from it, so stripping the
prefix serves a blank page with nothing in the log.
by a `rewrite ... break` before proxying; each upstream serves from `/`.
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
backend down (502s until it appears) instead of refusing to start.
- **Admin gate.** `/sb/`, `/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.
The config is `caddy/Caddyfile` (global options and snippets), `caddy/routes.caddy`
(every proxied route, shared by dev and production) and `caddy/sites/`
(`prod.caddy`, `dev.caddy`). Each file's header explains it.
- **Canonical host.** `http://` → `https://www.<DOMAIN>`, and apex → `www`. The
SPA, the cookies and the CORS rules all assume `www.<DOMAIN>`.
- **Route order is literal.** `routes.caddy` is one ordered list inside a
`route` block, and the first matching `handle` wins: denials first, then each
carve-out ahead of the gated prefix it is carved out of. A new route goes in
the right place in that list, not just anywhere.
- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/py`, `/tracker` and
`/receipt` are stripped with `uri strip_prefix` before proxying; each of
those upstreams serves from `/`. `/sb/`, `/notes/`, `/jobs/`, `/usaco/`,
`/dozzle/` and `/garage/` deliberately are NOT: those apps are told their own
base path (SilverBullet's `SB_URL_PREFIX` builds its service-worker scope from
it, so stripping the prefix serves a blank page with nothing in the log).
- **Upstreams resolve when dialled.** Caddy starts with any upstream container
missing and answers 502 until it appears; it never refuses to start over one.
- **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 `forward_auth` to the backend's `/auth/validate-admin` (the
`admin_gate` snippet); a 401/403 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 the edge 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`.
Paths are matched cleaned and case-insensitively, so `/SB/` or `/uploads/x/../private/y`
land on the gate too. With the backend down every gated path answers 502: it fails closed.
- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead (the
`permission_gate` snippet), 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
`path_regexp` deny rules at the top of `caddy/routes.caddy`. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
file _list_; direct `/.fs/` fetches and server-rendered page URLs still serve
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the
comment above `location /notes/` in `nginx_routes.conf.template`.
- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads`
volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so
user-supplied files cannot execute anything on our origin.
adding it to the deny regex publishes it. `caddy/edge_test.sh` checks these
denials against a running edge.
- **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 (the `uploads_disk` snippet, which hands the
request to a loopback-only site inside the container so that 206 and 304
answers keep their status). 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.
---
@@ -104,32 +143,31 @@ docker compose up --build
```
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
- renders `nginx.conf.template` if the cert is there, else
`nginx_setup.conf.template`;
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
nginx either way.
3. `certbot` obtains or confirms the certificate, then loops renewing.
4. Everything else comes up in parallel; `depends_on` here is the plain list
form, which waits only for *start*, not readiness.
2. `caddy` starts with the image's own command (`caddy run` on
`/etc/caddy/Caddyfile`). `CADDY_SITE` is unset, so it loads
`sites/prod.caddy`. It serves at once: the SPA is whatever is in `vue_dist`,
and upstreams that are not up yet are 502s. If `./caddy/data` holds no
certificate it obtains one first (§3), and TLS fails for those seconds.
3. Everything else comes up in parallel; `depends_on` here is the plain list
form, which waits only for _start_, not readiness.
On the Pi this is triggered automatically 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
(never the deploy checkout) and runs the backend's `go vet` + `go test` in
`golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build is
not repeated here: the image build in the deploy step does it, and a failed
build leaves the old containers running.
`golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build and
the Caddy config check are not repeated here: the image builds in the deploy
step do them (`caddy/Dockerfile` runs `caddy validate`), and a failed build
leaves the old containers running.
- **`deploy`** runs only on `main`, only after `test` passes, and only if the
tested commit is still the tip of `main` (so an older run cannot deploy a
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
hard-resets the deploy checkout, and runs
`docker compose up -d --build --remove-orphans` under the
`env-apply/run/lock` flock.
`.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,75 +180,190 @@ 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
```
The override layer changes five services and disables one:
`.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 these services and disables `cloudflared`:
- **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.
- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a
`CN=localhost` certificate (once, kept in `certbot/conf`) and render
`nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and
`:443` serve the whole site, no HSTS, no HTTP→HTTPS redirect.
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.
- **caddy** — `CADDY_SITE=dev`, which loads `caddy/sites/dev.caddy`: `/`
proxies to the Vite dev server, both `:80` and `:443` serve the whole site,
no HSTS or other security headers, no HTTP→HTTPS redirect. HTTPS uses a
certificate from Caddy's own local CA (kept in `./caddy/data`), which the
browser warns about. Every proxied route, gate and limit is the same
`routes.caddy` as production.
- **backend** — `DEV_MODE`, GraphQL playground and introspection on, a localhost
Spotify redirect URI, and **`SEED_DB=true`**.
- **python** — `uvicorn --reload` with `python/app` bind-mounted.
- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt
cannot validate localhost anyway.
- **jobs** — seeded, with the GraphQL playground on.
- **cloudflared** — put in the `disabled` profile, so it never starts: a dev
stack must never join the production tunnel.
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.
---
## 3. TLS: first issuance and renewal
## 3. TLS: certificates
### The chicken-and-egg
Caddy obtains and renews its own certificates (`prod_tls` in
`caddy/sites/prod.caddy`): one per name, `<DOMAIN>` and `www.<DOMAIN>`, from
Let's Encrypt over **DNS-01**. It creates the `_acme-challenge` TXT record
through the Cloudflare API with `CLOUDFLARE_DNS_API_TOKEN`, so nothing has to
reach the host: the router forwards no ports. The certificates, their keys and
the ACME account live in `./caddy/data` (gitignored, private key material).
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.
**First run on a new host or domain.** Set `CLOUDFLARE_DNS_API_TOKEN` (the
token needs **Zone → Zone → Read** and **Zone → DNS → Edit** on this zone; see
`.env.example`), then `docker compose up -d`. Caddy serves straight away and
obtains both certificates in the background, usually within seconds; until
they land the TLS handshake fails, so the tunnel answers 502. There is no
bootstrap config and nothing to restart.
`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no
upstreams, nothing that can fail to load. It serves
`/.well-known/acme-challenge/` from `/var/www/certbot` and 404s everything else,
so a half-configured site is never partially exposed.
```
docker compose logs caddy | grep -E 'obtaining certificate|certificate obtained|error'
```
**First run on a new domain:**
**Renewal** happens in-process when a third of a certificate's lifetime is
left, and the new one is served immediately, with no reload. A failed attempt
is retried with backoff and logged. To see what is being served:
1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx
config.`
2. certbot runs `certbot certonly --webroot` and writes the certificate into
`./certbot/conf` (bind-mounted into both containers — that sharing is what
makes the whole thing work).
3. **`docker compose restart nginx`.** This step is manual. Nothing watches the
cert directory. On restart the entrypoint re-checks, finds the cert, and
renders the production config.
```
for n in www.$DOMAIN $DOMAIN; do echo | openssl s_client -connect 127.0.0.1:443 -servername $n 2>/dev/null | openssl x509 -noout -subject -enddate; done
```
### Renewal
**`resolvers 1.1.1.1 1.0.0.1`** in `prod_tls` matters: on `app-network`
`<DOMAIN>` is an alias for the caddy container itself, so Docker's DNS would
answer the plugin's zone lookup and the order would fail with "expected 1
zone, got 0".
`certbot/entrypoint.sh` loops `certbot renew` every 12 hours. Renewal is a no-op
until the cert is inside its 30-day window, so this is well within Let's Encrypt
rate limits — it just means the window is checked twice a day. Certs are valid 90
days, so renewal lands around day 60.
**Losing `./caddy/data`** costs only a re-issue on the next start. Let's
Encrypt allows five certificates for the same name a week, so do not make a
habit of it.
**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container
cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the
certificate at startup and holds it in memory, so **a renewed certificate is not
served until nginx is reloaded or restarted.** In practice pushes to `main`
recreate nginx often enough to hide this. If the site ever serves an expired
cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
Until 2026-11-17 this was certbot plus a bootstrap nginx config, a reload
sentinel and a watcher loop, now in `.deprecated/`. The last certbot
certificate is still in `./certbot/conf` on the host as the rollback (§7); it
expires on 2027-01-20.
### Cloudflare Tunnel
The `cloudflared` container holds an outbound connection to Cloudflare and
forwards requests for the site's hostnames down it to Caddy. 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 Caddy. That is deliberate. Pointed at `http://caddy: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 change to the edge.
The origin is the public name, not `caddy`, because Caddy carries `<DOMAIN>`
and `www.<DOMAIN>` as network aliases on `app-network` (`docker-compose.yml`).
Inside the network those names resolve to the caddy container, so the hop
never leaves the host, and cloudflared verifies the Let's Encrypt certificate
against a name it covers. `https://caddy` would fail that check and need No
TLS Verify. The flip side: **an expired certificate takes the tunnel down
with a 502**, which is why renewal over DNS-01 (step 5) matters.
An alias only exists while Caddy is running, so cloudflared also pins both
names to Caddy's fixed address (`172.28.255.251`) with `extra_hosts`. Without
that, while Caddy 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 Caddy 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>`: Caddy redirects it to www, and it serves Gitea's registry
at `/v2/`.
- `radar.<DOMAIN>` → `https://radar.<DOMAIN>`: the Partner Radar demo
(Caddy's `radar.{$DOMAIN}` site, `sites/prod.caddy`).
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), add **Zone → Zone → Read** to it, and set it as
`CLOUDFLARE_DNS_API_TOKEN`. Caddy then obtains and renews over DNS-01
(§3) and needs no inbound port.
6. On the host, point the apex at Caddy 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 only: Caddy is given no HTTP
challenge to fall back to, so without a working `CLOUDFLARE_DNS_API_TOKEN`
nothing is issued or renewed. 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 serves nothing over 443 until
the first issuance (§3), so the tunnel carries nothing for those seconds.
- **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 Caddy 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.
---
@@ -219,30 +372,32 @@ 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 |
| `caddy_config` | Caddy's autosaved JSON config | Nothing — rewritten on every start |
**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 |
| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `./caddy/data` | Caddy's TLS certificates, **private keys** and ACME account | Gitignored. Never commit. Losing it means a re-issue on the next start (§3). |
| `./certbot/conf` | The old certbot certificate and keys | Unused since 2026-11-17; kept as the rollback until it is cleaned up (§7). |
| `./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`); Caddy's JSON request-body log in `logs/caddy/payloads.log` | Caddy rotates the payload log itself (50 MiB, five kept). `logs/nginx/` is nginx's, finished. |
| `./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
rendered icecast config, and the Gitea runner's downloaded binary
are all regenerated.
---
@@ -257,11 +412,11 @@ Two distinct mechanisms read it, and services use both:
- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse
time. Builds container names and published ports.
- **`env_file: ./.env`** — injects the whole file into the container. Used by
nginx, backend, db, icecast2, certbot.
backend, db and icecast2.
`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own
convention for overriding `app.ini` keys), and `python` receives an explicit
allow-list, so it never sees the database password or any API key other than
allow-list (as do `jobs`, `caddy` and the rest), so it never sees the database password or any API key other than
the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`,
which picks the model). The Python service
makes the site's one Claude call (the rowing photo reader); the `jobs` container
@@ -269,84 +424,70 @@ 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
An unset variable is not an error: compose substitutes an empty string,
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 backend, db and icecast2 load the whole file.
---
## 6. Rate limits
Defined once per config in the `http` block, applied per location. Keyed on
`$binary_remote_addr` — the client IP in packed form, so each entry is ~64 bytes
and a `10m` zone holds roughly 160k IPs. `10m` is a safe round number, not a
tuned value.
The `rate_limit` directive comes from the `mholt/caddy-ratelimit` plugin
(compiled in by `caddy/Dockerfile`) and is applied per route through the
`limit` snippet: `import limit <zone> <events> <window>`. Each zone is a
**sliding window** keyed on `{client_ip}`: at most `<events>` requests per
`<window>` per IP, then the request is refused. There is no separate burst, so
the numbers are nginx's old rates, which keeps the sustained rates the same;
the instant allowance comes out close to nginx's burst + 1.
`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**.
A refused request gets **503**, not the plugin's 429: `handle_errors 429` in
the Caddyfile rewrites it, because `vue/src/views/hotels/hotelsStream.js`
tells a rate-limit 503 ("too many searches from your address") apart from the
Python service's own 429 ("someone else is searching").
| 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. |
A zone's state is shared by every route that names it (`/api/`, `/py/`,
`/jobs/`, `/usaco/` and `/tracker/` share one `api` bucket per IP), so a zone
name must always be given the same numbers. A route that wants different ones
gets its own zone, as `/receipt/` does.
| Zone | Limit | Applied to | Why |
| -------------- | --------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `login` | 5 / 1m | `/api/auth/login` | Brute-force defence, on top of the backend's own 5/min. A human mistyping gets five tries a minute; a credential-stuffing script gets nothing useful. |
| `api` | 30 / 1s | `/api/`, `/py/`, `/jobs/`, `/usaco/`, `/tracker/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
| `graphql` | 10 / 1s | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. Dev has it too now. |
| `upload` | 30 / 1m | `/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 / 1m | `/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. |
| `receipt` | 10 / 1s | `/receipt/` | Prints are slow and physical; ten a second is far above any real use. |
| `radar` | 30 / 1s | all of `radar.<DOMAIN>` | The Partner Radar demo: an abuse ceiling like `api`, in its own zone because it is a different app. |
| `radar_login` | 5 / 1m | `radar.<DOMAIN>/api/auth/login` | Brute-force defence on the demo's login, on top of `radar` and the app's own login throttling. |
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.**
`{client_ip}` is the visitor's address only because of `trusted_proxies` and
`client_ip_headers CF-Connecting-IP` in the Caddyfile's global options, which
trust that header from cloudflared's fixed address alone. **If that address
changes in `docker-compose.yml` without the Caddyfile, 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,60 +497,85 @@ 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):
```
docker compose up -d --build backend
```
Note: editing `certbot/entrypoint.sh` needs no rebuild (it is bind-mounted over
the stock image's entrypoint) — just `docker compose restart certbot`. Editing
an nginx **template** does need a rebuild, since templates are `COPY`'d into the
image.
**Apply a new nginx config / pick up a renewed certificate:**
**Apply a Caddy config change.** Everything in `caddy/` is copied into the
image, so a change needs a rebuild, which also validates it (the Dockerfile's
last step runs `caddy validate` for the production and dev sites, and a
config that would not load fails the build before any container is
replaced). Only the first build on a host, or a Caddy or plugin version bump,
compiles Caddy itself (about 25 minutes on stpvm's two CPUs); a config-only
change rebuilds in seconds. The recreate drops connections for a second or
two. Certificates need nothing.
```
docker compose up -d --build nginx # template changed
docker compose restart nginx # certificate changed
make check-caddy # on a laptop, before pushing
docker compose up -d --build caddy # on the host
```
**Renew certificates manually** (then restart nginx so it is actually served):
**Check the edge.** `caddy/edge_test.sh` sends a fixed set of requests and
checks the privacy denials and every gate (non-zero exit on a FAIL), then
prints redirects, headers and uploads for comparison. Pass an admin session's
`Cookie` header value as `EDGE_COOKIE` to cover the signed-in cases. On the
host, pin the name to the machine or curl goes out over the internet:
```
docker compose exec certbot certbot renew --webroot -w /var/www/certbot
docker compose restart nginx
export "$(grep '^DOMAIN=' .env)"
caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
```
Add `--dry-run` to test without burning rate limit.
**Roll back to nginx** (possible while the certbot certificate in
`./certbot/conf` is valid, until 2027-01-20). The old edge is in
`.deprecated/nginx/` and `.deprecated/certbot/`. Revert the commit that moved
it there and then the cutover (`daa2a46`), which restores both directories
and nginx's compose services. Push, or apply it by hand on the host under the
lock so a deploy cannot interleave:
```
git revert --no-edit <the .deprecated move> daa2a46
flock .compose.lock sh -c 'docker compose stop caddy && docker compose rm -f caddy && docker compose up -d --build nginx certbot cloudflared traffic'
```
**Check logs:**
```
docker compose logs -f nginx # follow one service
docker compose logs -f caddy # follow one service (one line per request)
docker compose logs --tail=200 backend
docker compose ps # note: `vue` Exited(0) is correct
docker compose logs certbot # issuance / renewal outcomes
docker compose logs caddy | grep -E 'tls|certificate' # issuance / renewal
```
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
login required).
**Incoming request bodies.** Caddy writes one JSON line per request, body
included, to `logs/caddy/payloads.log` (the `payloads_file` logger and the
`logging` snippet in `caddy/Caddyfile`). 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/caddy/payloads.log | jq 'select(.request.method=="POST")'
jq -r 'select(.request.uri=="/api/graphql") | .req_body | fromjson? | .operationName' logs/caddy/payloads.log
jq -r '[.ts, .request.client_ip, .request.method, .request.uri, .status] | @tsv' logs/caddy/payloads.log
```
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
(that covers every login and the refresh call), and `Cookie`/`Authorization`
headers as `REDACTED`. A body is only logged when the client declared a
length under 100 KB on a route that is not an upload (`/api/uploads`,
`/garage/`, `/receipt/`, `/v2/`); everything else has no `req_body`, and
responses are never logged.
Caddy rotates the file itself (50 MiB, five old files kept), and `tail -F`
in `traffic` follows the rotation, so it needs no logrotate entry. The
`logs/nginx/*.log` stanza in `/etc/logrotate.d/web_server` is nginx's and
can go when `logs/nginx/` does.
**Reset the database** — destructive; wipes the app database **and Gitea's**:
```
@@ -427,37 +593,121 @@ 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;
- Caddy serves `/uploads/` from Garage and falls back to the volume when
Garage has no such file or is unreachable, and it starts 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 2 GB by Caddy.
**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 caddy 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 caddy (its healthcheck fetches
`http://127.0.0.1/caddy-health` 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 edge looks
like (2026-10-19, under nginx: 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 catch it. If it happens, capture what Caddy is
doing before restarting, since a restart destroys the only evidence of why.
Its admin API (inside the container only) serves Go's profiler:
```
docker inspect caddy --format '{{.State.Health.Status}}'
docker compose exec caddy wget -q -O - 'http://localhost:2019/debug/pprof/goroutine?debug=2' > caddy-goroutines.txt
docker compose restart caddy
```
---
@@ -465,25 +715,12 @@ define healthchecks, but the `autoheal` watchdog that acted on them was retired
Documented, not fixed — each would change deploy behaviour.
1. **Renewed certificates are not served until nginx restarts.** No
`--deploy-hook` in `certbot/entrypoint.sh`. Fix: add
`--deploy-hook "touch /var/www/certbot/.reloadme"` plus a watcher, or give
certbot the docker socket to send nginx a `HUP`.
2. **First TLS issuance needs a manual `docker compose restart nginx`.** The
entrypoint only re-evaluates cert presence at container start.
3. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be
1. **The old edge's host directories are still on stpvm** as the rollback
from the 2026-11-17 cutover: `./certbot/` (the last certbot certificate)
and `./logs/nginx/`, plus the `logs/nginx` stanza in
`/etc/logrotate.d/web_server`. The code is in `.deprecated/`. Once the
rollback is no longer wanted, delete the two directories and the stanza.
2. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be
mounted to the same in-container path as the real wrapper. It is currently
shadowed by an explicit file mount — fragile. Deleting it would be safe but
is a file removal.
4. **The two `/uploads/` location blocks are still written twice** — once in
`nginx.conf.template` and once in `nginx_dev_common.conf.template` —
because production adds security headers inside an auth-gated block. Every
other proxied route lives once in `nginx_routes.conf.template`, which both
configs include; the `auth_request` lines on `/uploads/private/` are the
one thing that must be kept in step by hand.
5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing
only our own origin**, which defeats the point of having the header at all.
6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert
today (neither contains whitespace) but a latent quoting bug.
7. **`UPTIMEKUMA_*` and `WALLABAG_*` are substituted by nginx but no compose
service provides them** — leftovers from removed services.
+18 -21
View File
@@ -11,9 +11,9 @@
# 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
# check-caddy Docker
# Nothing here installs a toolchain; a missing one fails that target only.
#
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
@@ -36,7 +36,7 @@ VENV := .venv
# changes and skip the install otherwise.
VENV_STAMP := $(VENV)/.installed
.PHONY: help check check-backend check-python check-vue check-compose generate dev
.PHONY: help check check-backend check-python check-vue check-compose check-caddy generate dev
help:
@echo "Targets:"
@@ -45,11 +45,12 @@ help:
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
@echo " make check-vue vite build of vue/ into a throwaway directory"
@echo " make check-compose validate docker-compose.yml, alone and with the dev override"
@echo " make check-caddy build the Caddy image, which validates caddy/ for prod and dev"
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
@echo " make dev build and run the dev stack (http://localhost)"
# Run with `make -k check` to keep going past the first failing area.
check: check-backend check-python check-vue check-compose
check: check-backend check-python check-vue check-compose check-caddy
check-backend:
cd backend && go vet ./... && go test ./...
@@ -69,26 +70,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; }
@@ -126,11 +113,21 @@ check-compose:
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
# The edge config is validated by the image build itself (the last RUN in
# caddy/Dockerfile runs `caddy validate` for the production and dev sites), so
# this is that build and nothing more. The deploy's `docker compose up
# --build` runs the same build, and a failure there stops before any
# container is replaced. The first build compiles Caddy with its plugins and
# takes a few minutes; later ones reuse that layer unless the Dockerfile
# changes.
check-caddy:
docker build -q -t web_server-caddy:check caddy/
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
generate:
cd backend && go run github.com/99designs/gqlgen generate
# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx.
# Dev stack: http and https, seeded database, Vite hot reload behind Caddy.
dev:
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
+23 -25
View File
@@ -1,3 +1,4 @@
Gay bal;;s
# My Web
![screenshot](vue/public/img/screenshot.png)
@@ -14,11 +15,11 @@ After hearing all the hype on LinkedIn and feeling the pressure to keep up a hig
## Architecture
All services run in Docker containers orchestrated by Docker Compose behind Nginx as a reverse proxy on a single bridge network.
All services run in Docker containers orchestrated by Docker Compose behind Caddy as a reverse proxy on a single bridge network. (nginx and certbot did that job until 2026-11-17.)
```
vue ── Frontend build (outputs dist to shared volume)
nginx (80, 443) ── Frontend SPA + Reverse Proxy
caddy (80, 443) ── Frontend SPA + Reverse Proxy + TLS certificates
backend (8080) ── Go API (GraphQL + REST)
db (5432) ── PostgreSQL 16
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
@@ -27,18 +28,17 @@ silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0)
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
silverbullet-git ── Commits/pushes notes edits to the notes repo
python (8000) ── Python API (FastAPI)
certbot ── SSL Certificate Management (disabled in dev)
```
## Tech Stack
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), 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
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
**Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner
**Infrastructure** - Docker Compose, Caddy, Let's Encrypt (DNS-01 via Cloudflare), Cloudflare Tunnel, Gitea + Act Runner
## Features
@@ -55,7 +55,7 @@ certbot ── SSL Certificate Management (disabled in dev)
- Printable CV with role-specific sections
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
- Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request`
- Admin-gated routes: `/sb`, `/jobs`, `/tracker`, `/dozzle`, `/garage` and more require the admin session, checked by Caddy's `forward_auth` against the backend
- Landing page with animated stamps section
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
@@ -122,7 +122,7 @@ certbot ── SSL Certificate Management (disabled in dev)
| POST | `/api/auth/refresh` | Refresh token |
| GET | `/api/auth/check` | Check token validity |
| POST | `/api/auth/logout` | Logout |
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Nginx auth_request) |
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Caddy's `forward_auth` admin gate) |
Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry.
@@ -147,7 +147,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 |
@@ -173,7 +173,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
| --- | --- | --- |
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
### Nginx Proxy Routes
### Proxy Routes (Caddy)
| Route | Target | Notes |
| ---------- | ------------ | ------------------------------------------ |
@@ -185,7 +185,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
| `/uploads` | local alias | User-uploaded files |
`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
`/sb` is protected by `forward_auth` to the backend's `/auth/validate-admin`. Requests without a valid admin session are redirected to `/admin/login`. The full table is `caddy/routes.caddy`; `DEPLOYMENT.md` §1 explains it.
### Deprecated Endpoints
@@ -271,21 +271,19 @@ Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the
editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at
`/notes/` with `SB_READ_ONLY`
3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off
`/notes/` by `SB_SPACE_IGNORE` **and** nginx deny blocks — the nginx blocks are the ones that
`/notes/` by `SB_SPACE_IGNORE` **and** Caddy deny rules — the Caddy rules are the ones that
actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary")
4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above)
### SSL Certificates (Certbot)
### TLS certificates
**Initial setup (production):**
Caddy obtains and renews them itself, over DNS-01 through the Cloudflare API, so no port has to be reachable from the internet:
1. Set `DOMAIN` and `EMAIL` in `.env`
2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/`
3. Certbot requests a certificate via `certbot certonly --webroot`
4. Once the certificate is issued to `certbot/conf/live/<DOMAIN>/`, restart Nginx — it will detect the certs and switch to the full `nginx.conf.template`
5. Certbot checks for renewal every 12 hours automatically
1. Set `DOMAIN` and `CLOUDFLARE_DNS_API_TOKEN` in `.env` (the token needs Zone → Zone → Read and Zone → DNS → Edit on the zone)
2. `docker compose up -d`. Caddy serves immediately and fetches both certificates (apex and www) into `./caddy/data` within seconds
3. Renewal is automatic and needs no restart
**Dev mode:** Nginx generates a self-signed certificate for localhost automatically.
**Dev mode:** Caddy issues a certificate for localhost from its own local CA.
### Icecast Radio
@@ -302,14 +300,15 @@ 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
```
This:
- Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.)
- Generates a self-signed certificate for localhost
- Disables certbot
- Loads Caddy's dev sites (`caddy/sites/dev.caddy`): all the same routing (SPA via Vite, backend proxy, radio, gitea, etc.) on both http and https, with no redirects or security headers
- Uses a localhost certificate from Caddy's local CA
- Disables the Cloudflare tunnel
- Seeds the database with test data (`SEED_DB=true`)
- Enables GraphQL playground and introspection
@@ -329,7 +328,7 @@ Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets defaul
make check
```
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build, `docker compose config` validation and the Caddy image build, which validates the edge config. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass.
@@ -341,7 +340,7 @@ These files are git-ignored and must be created manually:
| ------------------------------- | --------------------------------------------------------------- |
| `.env` | See setup section above |
| `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
| `certbot/conf/`, `certbot/www/` | Created automatically by certbot; use dev mode to skip |
| `caddy/data/` | Created automatically by Caddy (certificates and their keys) |
| `backend/token/` | Created automatically by Docker volume mount |
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file |
| `gitea-runner/act_runner` | Download from Gitea releases |
@@ -349,7 +348,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
+1 -1
View File
@@ -22,7 +22,7 @@
# would fail certificate verification without a trust store.
#
# EXPOSE 8080 is documentation only; the port is never published to the host.
# nginx reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
# Caddy reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
#
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
# amd64 (a dev laptop) with no platform pin.
+32 -50
View File
@@ -1,11 +1,11 @@
# Backend
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
The Go API for adam-french.co.uk. It is one process behind Caddy, serving a
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
that needs Claude is asked of the Python service, not called from here.
Nginx strips the `/api` prefix before proxying, so a browser request to
Caddy strips the `/api` prefix before proxying, so a browser request to
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
sees it.
@@ -33,7 +33,7 @@ graph/ GraphQL layer
## Request lifecycle
1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
1. Caddy terminates TLS, applies its own rate limits, strips `/api`, and
proxies to this service.
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
that `ClientIP()` — which the login rate limiter keys on — cannot be
@@ -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 Caddy'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
Caddy 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
@@ -226,7 +195,7 @@ no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at
`/jobs/` is a separate app with its own Claude calls.) It reaches the
internal routes directly over the Docker network
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
nginx, which answers 404 for `/py/internal/`:
Caddy, which answers 404 for `/py/internal/`:
| route | caller | sends | gets back |
| --- | --- | --- | --- |
@@ -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
(the edge cannot gate a bucket). Caddy 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
// Caddy or one of the SPA's own routes answers them first (see
// caddy/routes.caddy 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 a Caddy 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 Caddy 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")
}
}
+75 -38
View File
@@ -93,51 +93,87 @@ 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, Caddy'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, Caddy'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 a Caddy route 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 Caddy's forward_auth
// copies onto the proxied request (as X-Remote-User for /receipt/), so the
// service behind the gate 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 +186,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 +198,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
}
@@ -251,10 +288,10 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
// Login backs POST /auth/login. The user object it returns omits the password
// because models.User tags that field `json:"-"`.
func (store *Store) Login(ctx *gin.Context) {
// Per-IP limit (5/min) on top of nginx's own login rate limit.
// Per-IP limit (5/min) on top of Caddy's own login rate limit.
// ctx.ClientIP is only trustworthy because main.go pins the trusted
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
// client talking through nginx.
// client talking through Caddy.
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
return
-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
}
+2 -2
View File
@@ -34,8 +34,8 @@ type ExtractedRowingData struct {
Distance uint64 `json:"distance"`
}
// rowingReadPath is the Python route. It is internal: nginx refuses
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
// rowingReadPath is the Python route. It is internal: Caddy refuses
// /py/internal/ and the route itself refuses anything Caddy forwarded, so the
// only way in is the direct container-to-container call services.CallPython
// makes.
const rowingReadPath = "/internal/rowing/read"
+1 -1
View File
@@ -32,7 +32,7 @@ func TestReadRowingDisplayRequestAndReply(t *testing.T) {
var forwarded bool
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
// The Python route treats either header as "came through nginx" and
// The Python route treats either header as "came through Caddy" and
// answers 404, so this call must never carry them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+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 a Caddy
// 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)
}
})
}
}
+4 -4
View File
@@ -34,13 +34,13 @@ type Store struct {
LoginLimiter *services.RateLimiter
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx, all through
// slash. Used for the calls that bypass Caddy, all through
// 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
+24 -22
View File
@@ -50,7 +50,7 @@ func main() {
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
r.Use(gin.Recovery())
// Only the Docker network nginx sits on may set X-Forwarded-For. Without
// Only the Docker network Caddy sits on may set X-Forwarded-For. Without
// this pin any client could spoof its IP and defeat the per-IP login rate
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
@@ -115,7 +115,7 @@ func main() {
steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE
// Called directly over the Docker network, not through nginx, for its
// Called directly over the Docker network, not through Caddy, for its
// /internal/ Claude route (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
pythonHost := os.Getenv("PYTHON_HOST")
@@ -128,24 +128,32 @@ 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.
// and the GraphQL login mutation. Caddy 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.
//
// Paths below have no /api prefix: nginx strips it before proxying.
// Paths below have no /api prefix: Caddy strips it before proxying.
protected := r.Group("/", store.AuthMiddlewear)
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
@@ -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.
// Caddy 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 its route in
// caddy/routes.caddy from `import admin_gate` to `import permission_gate
// <key>` (the snippet is in caddy/Caddyfile).
// PermissionType describes one grantable service. Key is what is stored and
// what Caddy 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: Caddy 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)
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ import (
// (handlers/handle_rowing.go); the job posting reader, email classifier and
// lead scorer went with the job tracker to its own repo.
//
// The routes are internal in a specific sense: nginx answers 404 for
// The routes are internal in a specific sense: Caddy answers 404 for
// /py/internal/, and each route itself refuses a request carrying a proxy
// header, so the only way in is this direct container-to-container call. That
// is why the request below sets nothing but Content-Type.
+1 -1
View File
@@ -36,7 +36,7 @@ func TestCallPythonRequestAndReply(t *testing.T) {
)
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
// The Python routes treat either header as "came through nginx" and
// The Python routes treat either header as "came through Caddy" and
// answer 404, so the helper must never send them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+1 -1
View File
@@ -12,7 +12,7 @@ import (
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
// string (in practice the client IP). It is process-local: restarting the
// backend clears every window, and a multi-replica deployment would limit
// per replica rather than globally. Nginx applies its own rate limits in
// per replica rather than globally. Caddy applies its own rate limits in
// front of this, so this layer is a second line of defence, not the only one.
type RateLimiter struct {
mu sync.Mutex
+11 -6
View File
@@ -11,7 +11,7 @@ import (
// site owner scanning the log for "who is using my site". Two goals:
//
// 1. Quietness. The log is flooded by traffic that is not a human visit:
// nginx auth_request subrequests (/auth/validate-admin, re-run for every
// Caddy forward_auth subrequests (/auth/validate-admin, re-run for every
// admin page hit), the front end's own polling (`/auth/refresh_token`,
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
// a single terse line, or dropped entirely when repeated in a short
@@ -24,11 +24,16 @@ import (
// logQuietDrop lists paths whose 2xx responses are dropped outright. These
// are all heartbeat-style endpoints: identical every few seconds, no signal.
var logQuietDrop = map[string]bool{
"/auth/validate-admin": true, // nginx auth_request subrequest
"/auth/validate-admin": true, // Caddy forward_auth subrequest
"/auth/refresh": true, // front-end token refresh
"/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 ""
}
@@ -71,7 +76,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
fmt.Sprintf("%.0f%s", float64(latency), unit), marker)
// Visitor traffic gets the IP appended — the "who". Infrastructure
// traffic (nginx's own feet on the internal subnet) already has its IP
// traffic (the edge's own feet on the internal subnet) already has its IP
// implied and is left lean.
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
line += " " + params.ClientIP
@@ -81,10 +86,10 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
}
// logIsInterestingClient reports whether a client IP is likely an actual
// visitor rather than infrastructure. nginx proxies everything, so the IPs
// visitor rather than infrastructure. Caddy proxies everything, so the IPs
// that appear are either forwarded-from-humans or the ingress itself.
func logIsInterestingClient(ip string) bool {
// Docker's bridge network: nginx's own feet. Not a visitor.
// Docker's bridge network: the edge's own feet. Not a visitor.
return !startsWith(ip, "172.28.")
}
+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. Caddy
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (caddy/routes.caddy), 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 Caddy gates behind an admin check. Caddy 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; Caddy 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: Caddy 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; Caddy 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 the edge, in another container, 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 Caddy'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 (Caddy
// 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 Caddy 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)
}
}
+6
View File
@@ -0,0 +1,6 @@
**/.git
**/.DS_Store
# The certificate store (private keys) is bind-mounted at runtime, never sent
# to the build.
data
edge_test.sh
+404
View File
@@ -0,0 +1,404 @@
# =============================================================================
# Caddyfile — the public edge: TLS, the SPA, and the reverse proxy in front of
# every other service. Replaced nginx and certbot (now .deprecated/) on
# 2026-11-17.
#
# FILES (all baked into the image by caddy/Dockerfile)
# Caddyfile this file: global options, the snippets every site
# uses, the healthcheck site, and the import that picks
# the dev or production sites.
# routes.caddy the proxy route table, shared by dev and production.
# ADD A NEW PROXIED ROUTE THERE.
# sites/prod.caddy production: http -> https://www, the apex (registry
# and redirect), the www site.
# sites/dev.caddy dev: localhost on http and https, `/` -> Vite.
#
# WHICH SITES ARE LOADED
# CADDY_SITE picks the file (`prod` unless set; docker-compose.dev.yml sets
# `dev`). It is a parse-time {$VAR}, substituted before the Caddyfile is
# read, so it can name the import itself.
#
# TWO KINDS OF VARIABLE
# {$NAME} / {$NAME:default} read from the environment ONCE, when the config
# is parsed. Used for upstream names and the
# domain. They end up in the JSON config Caddy
# autosaves to /config, so never a secret.
# {env.NAME} read per use at runtime, never written into the
# config. Used for the two secrets: the
# Cloudflare DNS token and the receipt token.
# Every variable must be in the caddy service's explicit `environment:`
# list in docker-compose.yml, or it reaches Caddy empty. Note an EMPTY
# variable is not "unset": {$X:default} keeps the empty value. So defaults
# live in that compose list (${X:-default}), which treats both alike, as
# nginx's entrypoint's ${X:-default} did.
#
# WHAT NO LONGER NEEDS DOING (vs nginx)
# - Upstreams are resolved when Caddy dials them, not at startup, so it
# boots with any container missing and 502s until it appears. No
# `resolver` / `set $upstream_*` trick.
# - Certificates are obtained and renewed in-process (sites/prod.caddy), and
# Caddy serves while it does, so there is no bootstrap config, no certbot,
# no reload sentinel.
# - `header` is additive: a route that sets its own headers keeps the site's
# too. No security_headers.conf re-included everywhere.
# - Websocket upgrades, streaming responses and request-body streaming are
# the reverse proxy's defaults.
# =============================================================================
{
# No `email`: the ACME account works without one, Let's Encrypt stopped
# sending expiry notices in 2025, and an `email {$EMAIL}` line with EMAIL
# unset is a parse error that keeps the whole edge from starting.
# rate_limit is a plugin, so it has no place in Caddy's built-in directive
# order. Before basic_auth means before forward_auth too: a gated route
# counts the request before asking the backend about the session, as
# nginx's limit_req (preaccess phase) ran before auth_request (access).
order rate_limit before basic_auth
# Dev's `tls internal` would otherwise try to add Caddy's local CA to the
# container's trust store, which is pointless and logs an error.
skip_install_trust
servers {
# Real client IP behind the Cloudflare tunnel. For connections from
# the cloudflared container, and only those, the client IP is taken
# from Cloudflare's CF-Connecting-IP header. {client_ip} is then the
# visitor everywhere it is used: the rate-limit keys, the access log,
# and the X-Real-IP / X-Forwarded-For sent upstream (see `proxy`).
#
# Pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the subnet. Direct
# visitors on the published 80/443 can arrive from the bridge gateway,
# 172.28.0.1, so trusting the subnet would let anyone choose their own
# IP, and so their own rate-limit bucket, by sending the header.
trusted_proxies static 172.28.255.250
client_ip_headers CF-Connecting-IP
# No HTTP/3: 443/udp is not published and cloudflared does not use it,
# so advertising it (Alt-Svc) would only send browsers on a detour.
protocols h1 h2
}
# ---- Access logs ---------------------------------------------------------
# Every site imports `logging`, which names its access logger `payloads`.
# The two loggers below take that stream; the default logger is told to
# leave it alone, or each request would also be printed unfiltered,
# request body included.
log default {
exclude http.log.access.payloads
}
# The payload log: one JSON line per request, body included (log_append
# in `logging`), for seeing what actually arrives at the edge.
# logs/caddy/ on the host; the `traffic` container tails it so Dozzle
# shows it as its own stream. Caddy rotates it itself, and
# `tail -F` follows the rotation. 0644 so `jq` on the host can read it
# unprivileged (Caddy's default is 0600).
#
# Redaction: any body mentioning a password, token or secret is replaced
# whole, not field by field, because there is no JSON parser here. 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.
# Cookie and Authorization headers are logged as REDACTED by Caddy itself
# (the `log_credentials` server option is off).
log payloads_file {
include http.log.access.payloads
output file /var/log/caddy/payloads.log {
roll_size 50MiB
roll_keep 5
mode 0644
}
format filter {
wrap json
fields {
req_body regexp "(?is)^.*(password|token|secret).*$" "[redacted]"
}
}
}
# The container's stdout, which `docker compose logs caddy` and Dozzle
# show: the same requests cut down to one short line each, without the
# body or headers, like nginx's `compact` format.
log payloads_stdout {
include http.log.access.payloads
output stdout
format filter {
wrap console
fields {
req_body delete
request>headers delete
request>tls delete
resp_headers delete
}
}
}
}
# ---- Snippets ----------------------------------------------------------------
# Defined here, before the site files are imported, so every file can use
# them. `import <snippet> <args...>` fills {args[N]}.
# Inside every reverse_proxy. Caddy already passes Host through and sets
# X-Forwarded-Proto/Host. X-Forwarded-For is overwritten rather than left to
# Caddy's default, which APPENDS the trusted peer: behind the tunnel that is
# "<visitor>, 172.28.255.250", and Gitea (REVERSE_PROXY_LIMIT = 1, so the
# rightmost entry) would log cloudflared for every visitor. With exactly one
# entry, the visitor, every upstream sees what nginx gave it: gin's ClientIP()
# (backend/main.go, trusts 172.28/16), Gitea, and python/app/main.py's
# _internal_only guard, which refuses any request carrying either header.
(proxy) {
header_up X-Real-IP {client_ip}
header_up X-Forwarded-For {client_ip}
}
# import limit <zone> <events> <window>
#
# A sliding window: at most <events> per <window> per client IP, then 429
# (turned into 503 by `errors`). Unlike nginx's leaky bucket there is no
# separate burst, so each zone's <events> is nginx's rate and <window> its
# unit, which keeps the sustained rates exact; the instant allowance comes out
# close to nginx's burst + 1. DEPLOYMENT.md §6 has the table and the reasoning
# behind each zone.
#
# State is shared per ZONE NAME across every route that names it (the plugin
# keeps one pool keyed by name), which is how /api, /py, /jobs, /usaco and
# /tracker share one `api` bucket, as in nginx. So a zone name must always be
# given the same <events> and <window>; a route that wants different numbers
# needs its own zone name (see `receipt`).
(limit) {
rate_limit {
zone {args[0]} {
key {client_ip}
events {args[1]}
window {args[2]}
}
}
}
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/,
# Gitea's history views, /uploads/private/) ----
# forward_auth sends a GET carrying the original request's headers, cookie
# included, to the backend's /auth/validate-admin before the request goes
# anywhere. 2xx lets it through; 401/403 become a redirect to the SPA login.
# This puts the Go backend's session in front of services that have no idea
# it exists. The body is never sent (the method is rewritten to GET), so a
# 2 GB garage-webui upload does not go to the backend twice.
#
# {http.request.orig_uri}, not {uri}: a route's `uri strip_prefix` runs
# BEFORE forward_auth in Caddy's directive order, so {uri} would have lost its
# prefix by the time this redirect is built. The `*` matters too: given only a
# target and a status, `redir` takes a target starting with / as a path
# MATCHER, and the redirect would never fire.
(admin_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate-admin
@denied status 401 403
handle_response @denied {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
}
}
# ---- Permission gate (/receipt/) ----
# import permission_gate <key>
#
# The same mechanism, but asking GET /auth/validate/<key> whether the session
# holds one named permission (backend/services/permissions.go; admins hold
# them all), so a non-admin account granted it in the admin panel gets in.
# 401 (not signed in) goes to the login page; 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, copied onto the
# proxied request as X-Remote-User. copy_headers deletes any X-Remote-User the
# client sent before it sets the real one, so the upstream can trust it.
(permission_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate/{args[0]}
copy_headers X-Auth-User>X-Remote-User
@unauthenticated status 401
handle_response @unauthenticated {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
@forbidden status 403
handle_response @forbidden {
redir * /no-access?path={http.request.orig_uri} 302
}
}
}
# Production only (sites/prod.caddy); HSTS on localhost would poison the
# browser for every other localhost project on the machine.
#
# No site-wide CSP 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, separate from Gitea.
(security_headers) {
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Strict-Transport-Security "max-age=63072000; includeSubDomains"
}
}
# User-uploaded files are attacker-supplied bytes on our own origin. nosniff
# stops content-type guessing (so backend/services/uploads.go's stored type is
# what the browser goes by), 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. `>` defers each one until the
# response is written, so it also wins over anything Garage sends. (-Server
# and -Via repeat `common`'s, for the error route, which does not run it.)
(upload_headers) {
header {
>X-Content-Type-Options "nosniff"
>Content-Disposition "inline"
>Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'"
-Server
-Via
}
}
# The disk half of /uploads/ (see routes.caddy): hand the request to the
# uploads disk site at the bottom of this file. Used both when Garage answers
# 404/5xx (handle_response) and when it cannot be reached at all (`errors`),
# so it works from the ORIGINAL path, whatever the route had stripped by then.
#
# Why proxy to a second site rather than call file_server here: in an error
# route file_server answers with the ERROR's status, so a file served while
# Garage is down would arrive as a 502 (with the file as its body), and
# forcing 200 instead would also turn its 206 and 304 answers into 200s. A
# proxied response keeps whatever status the disk site gave it.
#
# The headers are imported again because error routes do not inherit the
# deferred ones of the route that failed.
(uploads_disk) {
import upload_headers
rewrite * {http.request.orig_uri.path}
reverse_proxy 127.0.0.1:2080
}
# Error routes, for errors Caddy raises itself (never for an upstream's own
# error response, which is passed through untouched). Any error none of these
# handles is answered with its own status and an empty body.
(errors) {
# rate_limit's 429. Answered as 503, the status nginx's limit_req used,
# because vue/src/views/hotels/hotelsStream.js tells the two apart: 503 is
# "too many searches from your address", while a 429 is the Python
# service's own "someone else is searching right now".
handle_errors 429 {
respond "Too many requests from your address. Wait a moment and retry." 503
}
# An upstream that could not be reached or timed out. Three routes turn that
# into something better than a bare 502, each keyed on a variable its
# route sets (error routes keep the request's vars, and a variable cannot
# be spoofed the way a path can be dressed up):
# uploads_fallback Garage is down: serve the file from disk instead.
# receipt_upstream set only once the permission gate has passed, so a
# backend outage is not reported as the printer's.
# radar_upstream the Partner Radar stack (radar.DOMAIN) is down.
handle_errors 502 504 {
@uploads_fallback vars uploads_fallback yes
handle @uploads_fallback {
import uploads_disk
}
@receipt_offline vars receipt_upstream yes
handle @receipt_offline {
respond "The receipt printer machine is offline." 503
}
@radar_offline vars radar_upstream yes
handle @radar_offline {
respond "Partner Radar is offline." 503
}
}
}
# The access log, and the request body on it. {http.request.body} buffers the
# body in memory to log it, so it is only taken when the client declared a
# length under 100 KB and the route is not an upload path: big and chunked
# bodies are logged without one. nginx did the equivalent: bodies over its
# 64k buffer went to a temp file and logged empty.
(logging) {
log payloads
@small_body {
# Up to five digits, spelt out because a {1,5} would read as a
# placeholder.
header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
}
# `<` (early: taken before the request is proxied) must be explicit.
# Without it 2.11 takes the body early as documented, but then takes it a
# second time after the proxy has read it, logging an empty string.
log_append @small_body <req_body {http.request.body}
}
# Compression, for the types nginx's gzip_types listed. An explicit list so
# that streamed responses (application/x-ndjson from /py/hotels/*, Dozzle's
# text/event-stream, icecast's audio) are never held back to fill a
# compression buffer.
(encode) {
encode zstd gzip {
minimum_length 256
match {
header Content-Type text/html*
header Content-Type text/plain*
header Content-Type text/css*
header Content-Type text/javascript*
header Content-Type application/javascript*
header Content-Type application/json*
header Content-Type application/xml*
header Content-Type image/svg+xml*
}
}
}
(common) {
import logging
import errors
import encode
# Caddy's own `Server: Caddy` and an upstream's (icecast sends one), and
# the `Via: 1.1 Caddy` its reverse proxy adds: nginx sent neither.
header {
-Server
-Via
}
}
# ---- Container healthcheck ---------------------------------------------------
# The target of the healthcheck in docker-compose.yml, which the `autoheal`
# container acts on. Answered by Caddy itself, so it measures whether the
# server is serving and nothing upstream. Plain HTTP on :80, addressed by IP
# so it matches no real site; not logged, or it would put a line in the
# payload log every 30 s.
http://127.0.0.1 {
respond /caddy-health 204
respond 404
}
# ---- Uploads disk site -------------------------------------------------------
# The shared `uploads` volume (mounted at /srv/uploads), served to this
# container only (bound to the loopback; nothing publishes 2080). Reached by
# `uploads_disk` when Garage has no copy of a file; see that snippet for why
# it is a site of its own. Unlogged: the request was logged as it arrived.
#
# private/ is refused here as well as gated upstream. A request is routed by
# its cleaned, lower-cased path, so anything that could reach private/ goes to
# the gated /uploads/private/ route long before this; the refusal is the
# second lock, should that route ever be reordered.
http://:2080 {
bind 127.0.0.1
@private path /uploads/private /uploads/private/*
handle @private {
respond 404
}
handle /uploads/* {
root * /srv
file_server
}
respond 404
}
import sites/{$CADDY_SITE:prod}.caddy
+66
View File
@@ -0,0 +1,66 @@
# =============================================================================
# caddy image — the public edge. Caddy with two plugins, plus this
# directory's config, checked while the image is built.
#
# WHY A CUSTOM BUILD
# Stock Caddy has neither of these, and the config needs both:
# caddy-dns/cloudflare DNS-01 certificates through the Cloudflare API
# (sites/prod.caddy), since the router forwards
# nothing to obtain them over HTTP.
# mholt/caddy-ratelimit the `rate_limit` directive (the `limit` snippet
# in the Caddyfile).
# xcaddy compiles them in. The cloudflare plugin is pinned to a release;
# caddy-ratelimit has had one tagged release (v0.1.0, 2024) and is pinned
# to a commit, so Renovate leaves it alone and it is bumped by hand.
#
# BASE: caddy:2.11.9, the builder and the runtime from the same release
# (the builder's xcaddy builds the CADDY_VERSION its image sets). Both
# tags are bumped together. Official images are multi-arch.
#
# THE CONFIG IS VALIDATED AT BUILD TIME
# The last RUN parses and provisions the config with `caddy validate`, for
# the production sites and the dev ones, against placeholder values for
# every variable the config reads. A config that would not load therefore
# fails the image build, and a failed build aborts `docker compose up
# --build` BEFORE any container is replaced, so the running edge keeps
# serving. `make check-caddy` is the same build. The placeholders exist
# only for that RUN; the real values come from the container's
# environment (docker-compose.yml).
#
# NO ENTRYPOINT. The base image's CMD runs
# `caddy run --config /etc/caddy/Caddyfile --adapter caddyfile`, which is all
# that is needed: Caddy reads the environment itself, and obtains and renews
# its own certificates.
# =============================================================================
FROM caddy:2.11.9-builder AS builder
RUN xcaddy build \
--with github.com/caddy-dns/[email protected] \
--with github.com/mholt/caddy-ratelimit@5625512f24f6f59d6f64fb3aafe5eecff0b286db
FROM caddy:2.11.9
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile routes.caddy /etc/caddy/
COPY sites/ /etc/caddy/sites/
# Mount points (docker-compose.yml). Created so Caddy still starts without
# them: the log directory especially, since a log file that cannot be opened
# stops the config loading.
RUN mkdir -p /var/log/caddy /srv/www /srv/uploads
# Validation writes Caddy's data and the payload log, so it is pointed at a
# throwaway directory and the log is removed afterwards, leaving the image as
# it was.
RUN set -e; \
for site in prod dev; do \
echo "caddy validate (CADDY_SITE=$site)"; \
env XDG_DATA_HOME=/tmp/validate XDG_CONFIG_HOME=/tmp/validate \
CADDY_SITE=$site DOMAIN=example.com EMAIL=[email protected] \
BACKEND_HOST=backend BACKEND_PORT=8080 BACKEND_ENDPOINT=/api \
ICECAST_HOST=icecast2 ICECAST_PORT=8000 \
GITEA_HOST=gitea GITEA_PORT=3000 \
SILVERBULLET_HOST=silverbullet SILVERBULLET_PORT=3000 \
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_PORT=3000 \
PYTHON_HOST=python PYTHON_PORT=8000 \
RECEIPT_WEB_UPSTREAM=127.0.0.1:9 RECEIPT_WEB_TOKEN=validate \
CLOUDFLARE_DNS_API_TOKEN=validate-placeholder-token-0000000000000 \
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile; \
done; \
rm -rf /tmp/validate /var/log/caddy/*
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env bash
# =============================================================================
# edge_test.sh — what the public edge does with a fixed set of requests.
#
# WHAT IT DOES
# Sends each request below to the edge and prints one line per request
# (status and Location, or one response header). Two kinds of line:
# ok / FAIL the privacy boundary and the gates, which have a fixed right
# answer: the /notes/ denials, /py/internal/, every gated
# prefix. Any FAIL makes the exit status 1.
# show / hdr everything else (redirects, headers, carve-outs, uploads),
# whose answer depends on the upstream's data. Compare two runs
# instead (below).
#
# USAGE
# caddy/edge_test.sh <base-url> [curl options...]
# base-url the www origin, e.g. https://www.example.com
# curl options added to every request: --resolve to reach a given
# container, -k for dev's internal CA.
# Environment, all optional:
# EDGE_APEX the apex origin (production only): adds the apex cases.
# EDGE_HTTP the plain-http apex origin (production only), e.g.
# http://example.com: adds the http -> https case.
# EDGE_COOKIE an admin session's Cookie header value: adds the
# signed-in cases (each gated prefix must then NOT redirect
# to the login).
# EDGE_UPLOAD the name of a file under /uploads/ that exists.
#
# On stpvm, pin the hostname to this machine, or curl goes out over the
# internet and back (and hangs):
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
# Dev stack:
# caddy/edge_test.sh https://localhost -k
#
# COMPARING TWO EDGES
# Run it against each and diff the output. This is how Caddy was checked
# against nginx before the 2026-11-17 cutover (Caddy on 8443 beside nginx),
# and how a big change to caddy/ can be checked against the running edge:
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >before.txt
# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >after.txt
# diff before.txt after.txt
# Every remaining difference should be one that was intended.
#
# NOTHING HERE WRITES. Every request is a GET, apart from one POST to
# /py/internal/, which never gets past the edge.
# =============================================================================
set -u
if [ $# -lt 1 ]; then
echo "usage: $0 <base-url> [curl options...]" >&2
exit 2
fi
BASE=${1%/}
shift
CURL_OPTS=("$@")
FAILED=0
# The www host, without scheme or port.
BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')
# "<status> <location>" for one request. Arguments after the URL are extra
# curl options (method, headers, --path-as-is). A redirect to the www host is
# shown as its path alone: nginx sends an absolute Location built from its
# own port, Caddy a relative one, and either way the browser lands on the
# same page.
probe() {
local url=$1 out
shift
out=$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{redirect_url}' \
"${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null) || out=ERR
printf '%s' "$out" | sed -E "s#^([0-9]+) [a-z]+://$BASE_HOST(:[0-9]+)?/#\\1 /#"
}
# The first value of one response header, or "-".
header_of() {
local name=$1 url=$2 value
shift 2
value=$(curl -sS -o /dev/null -D - --max-time 15 "${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null |
tr -d '\r' | grep -i "^$name:" | head -n 1 | cut -d: -f2- | sed 's/^ //')
printf '%s' "${value:--}"
}
# must <status> <location prefix, or -> <label> <path> [curl options]
must() {
local want_status=$1 want_loc=$2 label=$3 path=$4 got status loc ok=yes
shift 4
got=$(probe "$BASE$path" "$@")
status=${got%% *}
loc=${got#* }
[ "$status" = "$want_status" ] || ok=no
if [ "$want_loc" != "-" ] && [ "${loc#"$want_loc"}" = "$loc" ]; then
ok=no
fi
if [ $ok = yes ]; then
printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got"
else
printf 'FAIL %-12s %-58s %s (want %s %s)\n' "$label" "$path" "$got" "$want_status" "$want_loc"
FAILED=1
fi
}
# not_login <label> <path> [curl options]: anything but a redirect to the login.
not_login() {
local label=$1 path=$2 got
shift 2
got=$(probe "$BASE$path" "$@")
case $got in
ERR | "302 /admin/login"*)
printf 'FAIL %-12s %-58s %s (want: let through)\n' "$label" "$path" "$got"
FAILED=1 ;;
*) printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got" ;;
esac
}
# show <label> <url> [curl options]
show() {
local label=$1 url=$2
shift 2
printf 'show %-12s %-58s %s\n' "$label" "${url#"$BASE"}" "$(probe "$url" "$@")"
}
# hdr <url> <header...>
hdr() {
local url=$1 h
shift
for h in "$@"; do
printf 'hdr %-12s %-58s %s\n' "$h" "${url#"$BASE"}" "$(header_of "$h" "$url")"
done
}
LOGIN="/admin/login?redirect="
echo "# privacy boundary: must be 404"
for p in \
/notes/private/x /notes/Private/x /notes/a/private/x /notes/private \
/notes/templates/t /notes/.fs/private/x.md /notes/.fs/a/private/x.md \
/notes/.fs/.git/HEAD /notes/a/.obsidian/workspace.json /notes/a/.git/config \
/notes/.revisions/x.md /notes/private%2Fx /notes/%70rivate/x; do
must 404 - notes "$p"
done
must 404 - notes /notes/a/../private/x --path-as-is
must 404 - notes /notes/a//private/x --path-as-is
must 404 - py-internal /py/internal/rowing/read -X POST
must 404 - py-internal /py/internal/rowing/read
must 404 - py-internal /py/x/../internal/rowing/read --path-as-is -X POST
must 404 - py-internal /py//internal/rowing/read --path-as-is -X POST
echo "# admin gate, signed out: must redirect to the login, with the original URI"
for p in \
/sb/ /sb/index.html /jobs/ /jobs/api/graphql /tracker/ /tracker/dashboard \
/dozzle/ /garage/ /radio/admin/stats.xsl /uploads/private/x.png \
/gitea/adamf/web_server/commit/0000000 /gitea/adamf/web_server/src/commit/0000000/README.md \
/gitea/adamf/web_server/archive/main.tar.gz /gitea/adamf/web_server/compare/main...x \
/gitea/adamf/web_server/blame/commit/0000000/README.md \
"/jobs/leads?x=1"; do
must 302 "$LOGIN$p" gate "$p"
done
must 302 "${LOGIN}/uploads/x/../private/x.png" gate /uploads/x/../private/x.png --path-as-is
show gate "$BASE/SB/"
must 302 "${LOGIN}/receipt/" permission /receipt/
if [ -n "${EDGE_COOKIE:-}" ]; then
echo "# admin gate, signed in: must be let through"
for p in /sb/ /jobs/ /tracker/ /dozzle/ /garage/ /radio/admin/stats.xsl \
/gitea/adamf/web_server/commit/0000000 /receipt/; do
not_login gate "$p" -H "Cookie: $EDGE_COOKIE"
done
fi
echo "# carve-outs and public routes (status depends on the upstream)"
for p in /jobs/api/capture /jobs/job-capture.user.js /tracker/api/v1/events \
/tracker/tracker.user.js /tracker/readyz /usaco/ /notes/ /gitea/ \
/gitea/adamf/web_server/src/branch/main/README.md /radio/status.xsl \
/py/ /py/docs /api/ /api/me /; do
show public "$BASE$p"
done
echo "# bare prefixes and moved URLs"
for p in /api /radio /dozzle /garage /gitea /notes /sb /py /jobs /usaco \
/tracker /receipt /cv/jobs /cv/leads /job-capture.user.js "/gitea?x=1"; do
show redirect "$BASE$p"
done
echo "# SPA"
for p in /admin /architecture /some-canvas-page /assets/does-not-exist.js; do
show spa "$BASE$p"
done
hdr "$BASE/" Content-Type Strict-Transport-Security X-Frame-Options \
X-Content-Type-Options Referrer-Policy Content-Security-Policy Server
hdr "$BASE/api/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/gitea/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/assets/does-not-exist.js" Cache-Control
hdr "$BASE/img/stamps/mine.gif" Access-Control-Allow-Origin Cache-Control
echo "# uploads"
show uploads "$BASE/uploads/does-not-exist.png"
hdr "$BASE/uploads/does-not-exist.png" X-Content-Type-Options Content-Security-Policy
if [ -n "${EDGE_UPLOAD:-}" ]; then
show uploads "$BASE/uploads/$EDGE_UPLOAD"
show uploads "$BASE/uploads/$EDGE_UPLOAD" -H "Range: bytes=0-9"
hdr "$BASE/uploads/$EDGE_UPLOAD" Content-Type X-Content-Type-Options \
Content-Disposition Content-Security-Policy Strict-Transport-Security
fi
if [ -n "${EDGE_APEX:-}" ]; then
APEX=${EDGE_APEX%/}
echo "# apex (production)"
show apex "$APEX/x?y=1"
show apex "$APEX/v2/"
hdr "$APEX/x" Strict-Transport-Security
fi
if [ -n "${EDGE_HTTP:-}" ]; then
echo "# plain http (production)"
show http "${EDGE_HTTP%/}/x?y=1"
fi
echo "# result: $([ $FAILED = 0 ] && echo all MUST cases passed || echo SOME MUST CASES FAILED)"
exit $FAILED
+452
View File
@@ -0,0 +1,452 @@
# =============================================================================
# routes.caddy — the PROXY ROUTE TABLE shared by production and dev. Add a new
# proxied route HERE, once.
#
# WHO IMPORTS IT
# sites/prod.caddy (the www site) and sites/dev.caddy, each inside a
# `route { ... }` block, followed by that site's own `/` handler (the built
# SPA in production, the Vite dev server in dev). Everything else that
# differs between the two (TLS, security headers, static-asset caching, the
# apex) is in the site files.
#
# ORDER IS LITERAL: THE FIRST MATCHING handle WINS
# Inside `route`, Caddy keeps directives in the order written, and `handle`
# blocks are mutually exclusive. So this file is read top to bottom like a
# firewall list: denials first, then the specific routes, each carve-out
# ahead of the gated prefix it is carved out of, then the catch-alls.
# (nginx's longest-prefix / regex-in-file-order / ^~ rules are gone.)
#
# HOW PATHS ARE MATCHED
# `path` matchers are case-insensitive and see the decoded, cleaned path
# (`..` resolved, `//` merged), so /SB/, /notes/a/../private/x or
# /uploads/%70rivate/x cannot slip past a rule. `path_regexp` sees the
# decoded, cleaned path too but is case-sensitive, hence `(?i)` where case
# matters. caddy/edge_test.sh checks these against the live edge.
#
# PATTERNS THAT REPEAT BELOW
# - `uri strip_prefix /x`: the public URL carries a prefix (/api, /radio,
# /gitea, /py, /tracker, /receipt) but the upstream serves from /. Apps
# told their own base path (SilverBullet, the job tracker, usaco, Dozzle,
# garage-webui) keep it.
# - `import proxy` in every reverse_proxy: the forwarding headers (see the
# snippet in Caddyfile).
# - `import limit <zone> ...`: see the snippet; DEPLOYMENT.md §6 for the
# numbers.
# - `import admin_gate` / `import permission_gate <key>`: the session check
# against the backend. Some of these services have no auth of their own,
# so a gated route that loses its import is open to the internet.
# - Upstream read timeouts are not set anywhere: Caddy has none by default,
# so a long hotel search, an email sync or a log tail is never cut off by
# the proxy. (Cloudflare still gives up on an origin that sends nothing
# for 100 s; see DEPLOYMENT.md.)
#
# Upstream names come from the environment ({$BACKEND_HOST} etc.; see the
# caddy service in docker-compose.yml). The job tracker, activity tracker,
# usaco, Dozzle and Garage containers have fixed names there, so they are
# written literally.
# =============================================================================
# Request bodies: 50 MB everywhere except garage-webui, which takes video
# uploads and sets its own 2 GB below. (An outer limit cannot be raised by an
# inner one, so the exception has to be carved out here.) The backend caps
# uploads at 10 MB itself; this is the ceiling for everything else.
@body_default not path /garage/*
request_body @body_default {
max_size 50MB
}
# ---- Denials -----------------------------------------------------------------
# /py/internal/: routes the Go backend calls directly over app-network (the
# rowing photo reader, which spends a paid Claude call and has no auth of its
# own). Never proxied. The Python side also refuses anything carrying the
# X-Real-IP / X-Forwarded-For headers `proxy` sets, as a second layer.
handle /py/internal/* {
respond 404
}
# PUBLIC notes viewer privacy boundary. /notes/ is a second, read-only
# SilverBullet over the vault /sb/ edits, and SB_SPACE_IGNORE only hides
# paths from its file LIST. Everything else serves them (all verified against
# 2.11.0 with curl):
# /notes/.fs/private/x.md raw file, straight off disk
# /notes/private/x the page URL: the server pre-renders the
# note's content into the HTML shell
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
# version of every private note ever
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a private/
# folder at ANY depth, so the block must too.
#
# 1. private/ or templates/ as any path segment, page URL or /.fs/. (?i) so
# Private/ is caught; (/|$) so the folder itself matches.
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The first
# segment is exempt because that is where SilverBullet's own endpoints
# live (/.fs, /.config, /.client, /.events ...). Nothing the client
# legitimately loads has a dot-segment deeper than that.
# 3. Revisions are read from the vault's own .git, i.e. the full history of
# every file INCLUDING private/ and anything ever deleted.
# SB_REVISIONS=disabled already turns this off upstream; this is the
# second lock in case that env var is ever dropped.
# Keep the folder list in step with SB_SPACE_IGNORE on silverbullet-public.
# 404 rather than 403 so the response does not confirm a private path exists.
@notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$)
handle @notes_private {
respond 404
}
@notes_dot path_regexp ^/notes/.+/\.
handle @notes_dot {
respond 404
}
handle /notes/.revisions* {
respond 404
}
# ---- Bare prefixes and moved URLs ----------------------------------------------
# So a user typing /gitea without the slash lands correctly. Exact paths: unlike
# nginx's prefix locations, /gitea-something is not caught and is left to the
# SPA (where an admin-created canvas page with that slug now works).
redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301
redir /radio /radio/ 301
redir /dozzle /dozzle/ 301
redir /garage /garage/ 301
redir /gitea /gitea/ 301
redir /notes /notes/ 301
redir /sb /sb/ 301
redir /py /py/ 301
redir /jobs /jobs/ 301
redir /usaco /usaco/ 301
redir /tracker /tracker/ 301
redir /receipt /receipt/ 301
# Where the job 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 version 2.0.0 and its new
# API base.
redir /cv/jobs /jobs/ 301
redir /cv/leads /jobs/leads 301
redir /job-capture.user.js /jobs/job-capture.user.js 301
# ---- Backend API ---------------------------------------------------------------
# Live chat / activity feed websocket. Deliberately NOT rate limited: a
# websocket is one long-lived request, and a limit here would drop reconnect
# storms, not abuse.
handle {$BACKEND_ENDPOINT}/ws* {
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# Brute-force defence on password auth, on top of the backend's own 5/min.
handle {$BACKEND_ENDPOINT}/auth/login* {
import limit login 5 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/uploads* {
import limit upload 30 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# Tighter than the REST catch-all, because one GraphQL query can be
# arbitrarily expensive to resolve.
handle {$BACKEND_ENDPOINT}/graphql* {
import limit graphql 10 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/* {
import limit api 30 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# ---- Admin-gated services ------------------------------------------------------
# Dozzle: live view of every container's logs, including the `traffic`
# container's request-body log. It reads the Docker socket, so it is
# effectively root on the host: admin only. DOZZLE_BASE=/dozzle makes it serve
# under the prefix itself. Its log tails are server-sent events, which Caddy
# streams without buffering.
handle /dozzle/* {
import admin_gate
reverse_proxy dozzle:8080 {
import proxy
}
}
# garage-webui: buckets, keys and a file browser for the Garage object store.
# It holds Garage's admin token, so admin only, and its own login is left
# unset (one login, not two). BASE_PATH=/garage makes it serve under the
# prefix. 2 GB so videos can be uploaded through it; the body streams through
# rather than landing on disk first.
handle /garage/* {
import admin_gate
request_body {
max_size 2GB
}
reverse_proxy garage-webui:3909 {
import proxy
}
}
# The icecast ADMIN UI is a full station-control surface (kick sources, change
# metadata) protected only by the icecast admin password. Ahead of /radio/*,
# so listener traffic (the mount, status.xsl) is untouched.
handle /radio/admin/* {
import admin_gate
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
# Gitea's history views and archives. 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. 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. Ahead of /gitea/*.
@gitea_history path_regexp ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/)
handle @gitea_history {
import admin_gate
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes. NO
# prefix strip: it is a PWA told its own base path via SB_URL_PREFIX=/sb, and
# builds its service-worker scope and asset URLs from it. Strip the prefix and
# the app loads a blank page with no error in the log.
handle /sb/* {
import admin_gate
reverse_proxy {$SILVERBULLET_HOST}:{$SILVERBULLET_PORT} {
import proxy
}
}
# ---- Public services -----------------------------------------------------------
handle /radio/* {
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
handle /gitea/* {
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# The public notes viewer, behind the denials at the top of this file. No
# prefix strip, for the same reason as /sb/ (SB_URL_PREFIX=/notes).
handle /notes/* {
reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} {
import proxy
}
}
# /py/hotels/search[/stream] and /py/hotels/scan/stream: public, minutes-long
# upstream calls to Travelodge/TfL with a single search slot on the Python
# side, so this zone is really concurrency protection. flush_interval -1
# passes each NDJSON progress line on as it arrives (chunked responses are
# flushed anyway; this makes it explicit). `encode` never touches
# application/x-ndjson.
@hotels path_regexp ^/py/hotels/(search|scan)
handle @hotels {
import limit hotel_search 3 1m
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
flush_interval -1
}
}
handle /py/* {
import limit api 30 1s
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
}
}
# ---- Job tracker (/jobs/) ----
# Its own container (the adamf/job-tracker repo), which serves its SPA and its
# API from the same prefix, NOT stripped: the app is built to live at /jobs/.
# Gated like /sb/ (the app checks the session itself too), with two
# exceptions ahead of it that a session cookie can never reach:
# - the capture API, called by the userscript from job sites' origins with
# the capture bearer token rather than cookies; the app's
# CaptureTokenMiddleware guards it;
# - the userscript itself: userscript managers fetch its @updateURL without
# the session, and it holds no secrets (the token is entered after
# install).
handle /jobs/api/capture* {
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/job-capture.user.js {
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/* {
import admin_gate
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
# ---- 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 gate, 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.
handle /usaco/* {
import limit api 30 1s
reverse_proxy usaco:8080 {
import proxy
}
}
# ---- 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 app also checks the session itself),
# with two exceptions ahead of it: 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 userscript. 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 50 MB default above covers them.
handle /tracker/api/v1/* {
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/tracker.user.js {
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/* {
import admin_gate
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
# ---- 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), reached over
# Tailscale by IP. 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 (header_up replaces any copy the client sent), and is told who is
# printing in X-Remote-User, which the gate sets.
#
# A `route`, so the steps run in the order written: receipt_upstream is set
# only after the gate has passed, so `errors` reports "printer offline" for a
# failed dial to stppi and not for a backend outage during the auth check.
# Its own zone, not `api`: a zone name must always carry the same numbers.
# 17 MB: the server caps uploads at 16 MB, plus room for the multipart
# framing around one.
handle /receipt/* {
route {
import limit receipt 10 1s
request_body {
max_size 17MB
}
import permission_gate receipt
vars receipt_upstream yes
uri strip_prefix /receipt
reverse_proxy {$RECEIPT_WEB_UPSTREAM} {
import proxy
header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN}
# Caddy's default, spelt out: when stppi is off, fail fast and
# let `errors` answer.
transport http {
dial_timeout 3s
}
}
}
}
# ---- Uploads (/uploads/) ----
# PRIVATE attachments (admin-only): files on *private* chat messages, which
# the backend always writes to disk, at uploads/private/. Ahead of the public
# route below, and matched on the cleaned, lower-cased path, so no spelling of
# a path into private/ reaches the ungated one.
handle /uploads/private/* {
import admin_gate
import upload_headers
root * /srv
file_server
}
# 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 (404), errors (5xx), or cannot be reached at all (a dial error,
# caught by `errors` through the uploads_fallback variable), the file is
# served from the shared `uploads` volume instead (`uploads_disk`). That
# volume 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. dial_timeout 2s: Garage is on the same bridge, so a slow
# connect means it is down; fall back quickly. Range requests pass through
# either way, so video seeks.
handle /uploads/* {
import upload_headers
vars uploads_fallback yes
uri strip_prefix /uploads
reverse_proxy garage:3902 {
import proxy
header_up Host uploads.web.garage
transport http {
dial_timeout 2s
}
@not_in_bucket status 404 5xx
handle_response @not_in_bucket {
import uploads_disk
}
}
}
+32
View File
@@ -0,0 +1,32 @@
# =============================================================================
# sites/dev.caddy — LOCAL DEVELOPMENT sites. Imported by the Caddyfile when
# CADDY_SITE=dev, which only docker-compose.dev.yml sets.
#
# HOW IT DIFFERS FROM sites/prod.caddy
# - `/` is proxied to the Vite dev server at vue:5173 instead of serving the
# built SPA. Its HMR websocket needs nothing extra.
# - http AND https both serve the full site, with no redirects, so
# http://localhost just works. Listing the http:// addresses is what
# stops Caddy adding its automatic http -> https redirect.
# - TLS is `tls internal`: a certificate from Caddy's own local CA, kept in
# ./caddy/data. Browsers warn until that CA is trusted, which is expected.
# - No security headers: HSTS on localhost would poison the browser for
# every other localhost project on the machine.
# - No static-asset caching: Vite serves those, and long cache lifetimes
# would defeat hot reload.
# Everything else, every proxied route, gate, denial and rate limit, is the
# same routes.caddy as production.
# =============================================================================
http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} {
tls internal
import common
route {
import ../routes.caddy
handle {
reverse_proxy vue:5173
}
}
}
+179
View File
@@ -0,0 +1,179 @@
# =============================================================================
# sites/prod.caddy — PRODUCTION sites. Imported by the Caddyfile unless
# CADDY_SITE says otherwise.
#
# FOUR SITES
# 1. http:// apex + www -> 301 to https://www.DOMAIN.
# 2. https:// apex -> Gitea's registry at /v2/, else 301 to www, so
# there is exactly one canonical origin (cookies,
# CORS and the SPA all assume www).
# 3. https:// www -> the real site.
# (4. the healthcheck site, http://127.0.0.1, is in the Caddyfile.)
#
# CERTIFICATES
# Caddy obtains one for each name over DNS-01 through the Cloudflare API
# (`prod_tls`), keeps them in /data (./caddy/data on the host), and renews
# each when a third of its lifetime is left, in-process, with no reload.
# DNS-01 because the router forwards nothing: behind the tunnel no ACME
# server can reach :80 or :443. The token needs Zone -> Zone -> Read and
# Zone -> DNS -> Edit on this zone; see .env.example. Until the first
# certificate arrives (about a minute on a fresh ./caddy/data) the TLS
# handshake fails, so the tunnel, which verifies it, serves 502s.
#
# resolvers: on app-network, DOMAIN is a network alias for this very
# container, so Docker's DNS would answer the plugin's zone lookup itself
# and the order fails with "expected 1 zone, got 0". Asking Cloudflare's
# public resolvers sees the real zone.
# =============================================================================
(prod_tls) {
tls {
dns cloudflare {env.CLOUDFLARE_DNS_API_TOKEN}
resolvers 1.1.1.1 1.0.0.1
}
}
# Spelt out rather than left to Caddy's automatic redirect, which goes to the
# same host: http://apex would then take two hops (https://apex, then www).
http://{$DOMAIN}, http://www.{$DOMAIN} {
import logging
header -Server
redir https://www.{$DOMAIN}{uri} 301
}
{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
# Gitea's container registry, which publishes images such as
# DOMAIN/adamf/job-tracker. Docker always talks to /v2/ at the root of
# the host, whatever Gitea's ROOT_URL says, and Gitea advertises its
# token endpoint at https://DOMAIN/v2/token: on the apex, not under
# /gitea/ and not on www. So the apex serves /v2/ itself rather than
# redirecting it; a redirect on a blob upload is not something every
# Docker client follows. No request_body limit (routes.caddy's 50 MB
# is not imported here): image layers are far larger, and Caddy
# streams them to Gitea as they arrive.
handle /v2/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
redir https://www.{$DOMAIN}{uri} 301
}
}
www.{$DOMAIN} {
import prod_tls
import common
import security_headers
# ---- Static asset caching ----
# Each matcher also requires the file to exist (`file`), so only a real
# file is marked cacheable: a 404 for a hash the browser asks for before
# the new build lands must never be cached for a year as `immutable`.
# (nginx's add_header without `always` skipped error responses the same
# way.)
# Vite hashed assets: a new build has new names, so these never change.
@hashed {
path /assets/*
file {
root /srv/www
}
}
header @hashed Cache-Control "public, max-age=31536000, immutable"
@fonts {
path /fonts/*
file {
root /srv/www
}
}
header @fonts Cache-Control "public, max-age=2592000"
@week {
path /img/* /sound/*
file {
root /srv/www
}
}
header @week Cache-Control "public, max-age=604800"
# This GIF is a "web stamp" other people's sites hot-link, so it needs a
# CORS header. It is a public, deliberately hot-linkable image and nothing
# here is credentialed, so `*` is safe.
header /img/stamps/mine.gif Access-Control-Allow-Origin "*"
route {
import ../routes.caddy
# Static directories: a missing file is a 404, never the SPA's
# index.html. A stale page asking for an old asset hash then gets an
# honest error rather than HTML served as JavaScript.
@static path /assets/* /fonts/* /img/* /sound/*
handle @static {
root * /srv/www
file_server
}
# The built SPA (the vue_dist volume). Serve the file if it exists,
# otherwise hand index.html to the browser so Vue Router can resolve
# the path client-side: that is what makes deep links like /admin or
# a canvas page's /<slug> work on refresh.
handle {
root * /srv/www
try_files {path} {path}/ /index.html
file_server
}
}
}
# ---- Partner Radar (radar.DOMAIN) ----
# The adamf/cto "Partner Radar" demo: its own docker compose project on this
# host (`make stpvm` there), whose `web` container (its own Caddy, serving the
# React app and proxying its API) joins app-network as `radar-web`. A
# subdomain, not a /radar/ path, because the app assumes it owns `/` and its
# session cookie then stays apart from www's.
#
# No admin gate: the app has its own login and accounts. No security_headers
# either: the app's Caddy sends its own, and www's CSP would block the React
# app. Two zones of its own (see DEPLOYMENT.md §6): `radar` on every request,
# and `radar_login` on top of it for the login endpoint. radar_upstream lets
# `errors` answer "offline" when the stack is down instead of a bare 502.
(radar_proxy) {
reverse_proxy {$RADAR_UPSTREAM} {
import proxy
# Caddy's default, spelt out: when the stack is down, fail fast and
# let `errors` answer.
transport http {
dial_timeout 3s
}
}
}
radar.{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
import limit radar 30 1s
request_body {
max_size 10MB
}
vars radar_upstream yes
handle /api/auth/login {
route {
import limit radar_login 5 1m
import radar_proxy
}
}
handle {
import radar_proxy
}
}
}
+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.
+22 -27
View File
@@ -12,14 +12,15 @@
# - vue : one-shot `vite build` becomes the long-running Vite dev server
# with the source bind-mounted for hot reload.
# - backend : dev flags on, including database seeding.
# - nginx : DEV_MODE=true, which makes its entrypoint render
# nginx_dev.conf.template and self-sign a localhost certificate.
# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy instead of
# the production sites: no redirects, no security headers, a
# certificate from Caddy's own local CA, `/` proxied to Vite.
# - 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
# the browser will warn about — that is expected).
# http://localhost (HTTPS also works on :443 with the local-CA certificate,
# which the browser will warn about — that is expected).
#
# NOT USED ON THE PI. The deploy workflow runs plain `docker compose up`.
# =============================================================================
@@ -27,18 +28,16 @@
services:
vue:
# Replaces the one-shot `vite build`: the container now stays up serving
# the Vite dev server on :5173, which nginx_dev.conf proxies `/` to.
# the Vite dev server on :5173, which caddy/sites/dev.caddy proxies `/` to.
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:
@@ -56,17 +55,12 @@ services:
# because dev uses a throwaway local dbdata volume; it is NEVER set
# in production — seeding a live database would inject fake content.
- SEED_DB=true
nginx:
caddy:
environment:
# The single switch that selects nginx_dev.conf.template and the
# self-signed localhost certificate. See nginx/entrypoint.sh.
- DEV_MODE=true
# Same mapping as the base file; restated because compose replaces the
# `ports` list rather than merging it, so omitting it here would be fine
# but restating it makes the dev surface explicit.
ports:
- 80:80
- 443:443
# The single switch that loads caddy/sites/dev.caddy instead of
# the production sites: localhost on http and https, `tls
# internal`, `/` -> Vite.
- CADDY_SITE=dev
python:
# Same command as the Dockerfile's CMD plus --reload, paired with the
# source bind mount below so editing python/app/ restarts uvicorn.
@@ -85,11 +79,12 @@ services:
- GQL_PLAYGROUND=true
- GQL_INTROSPECTION=true
- MSGRAPH_REDIRECT_URI=https://localhost/jobs/api/email/callback
certbot:
cloudflared:
# Profiles are opt-in: a service with a profile is only started when
# that profile is explicitly requested. Nothing ever requests
# "disabled", so this is the idiomatic way to switch a service off in an
# override file. Dev gets TLS from nginx's self-signed cert instead, and
# Let's Encrypt could not validate localhost anyway.
# "disabled", so this is the idiomatic way to switch a service off in
# an override file. A dev stack must never join the production tunnel:
# Cloudflare would load-balance real visitors onto this machine's
# seeded database.
profiles:
- disabled
+458 -87
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
@@ -27,35 +27,44 @@
# inline defaults.
#
# NAMING CONVENTION / WHY container_name IS SET FROM env
# Service discovery is by container name on app-network. nginx builds its
# upstreams from the same ${*_HOST} variables (nginx/entrypoint.sh), so
# naming the containers from .env keeps the proxy and the containers in sync
# from one source of truth. Renaming a *_HOST value renames the container AND
# repoints nginx at it — do not change one without the other.
# Service discovery is by container name on app-network. Caddy builds its
# upstreams from the same ${*_HOST} variables (the caddy service's
# environment list), so naming the containers from .env keeps the proxy and
# the containers in sync from one source of truth. Renaming a *_HOST value
# renames the container AND repoints Caddy at it — do not change one without
# the other.
#
# WHAT IS PUBLISHED TO THE HOST
# Only nginx (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor
# Only caddy (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 Caddy. Web traffic can
# also arrive through the `cloudflared` tunnel, which publishes nothing.
# =============================================================================
networks:
# One flat bridge network; every service resolves every other by container
# name via docker's embedded DNS at 172.28.0.11 (nginx configs point their
# `resolver` there). The subnet is pinned explicitly so it cannot collide
# name via docker's embedded DNS at 127.0.0.11 (Caddy resolves an upstream
# through it each time it dials one). The subnet is pinned explicitly so it cannot collide
# with the Pi's LAN range or wander between compose versions.
app-network:
driver: bridge
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;
# they are only destroyed by `docker compose down -v` or an explicit
# `docker volume rm`. Bind mounts (./gitea/data, ./backend/token, ./logs,
# ./certbot/conf) live in the repo checkout on the Pi and survive everything
# ./caddy/data) live in the repo checkout on the Pi and survive everything
# short of deleting the directory. Anything inside a container's own
# filesystem is ephemeral and gone on rebuild.
volumes:
@@ -63,13 +72,27 @@ volumes:
# Deleting this wipes posts, users, messages and every git repo's metadata.
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.
# served read-only by Caddy at /uploads/. Shared so Caddy can serve user
# 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. Caddy 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.
# one-shot `vue` container writes the built SPA here and exits; Caddy mounts
# it at /srv/www and serves it. Repopulated on every rebuild.
vue_dist:
# Caddy's /config: the JSON it autosaves on each config load. Nothing in it
# is needed across restarts (the Caddyfile is the source); named only so
# the image's VOLUME does not leave an anonymous volume behind on every
# recreate. The certificates are in ./caddy/data, not here.
caddy_config:
services:
# One-shot build container, NOT a long-running service. `vite build` writes
@@ -87,67 +110,144 @@ services:
networks:
- app-network
# The only public entrypoint. Terminates TLS, serves the SPA, reverse-proxies
# everything else. Its config is chosen at container start — see
# nginx/entrypoint.sh for the DEV_MODE / cert-present / bootstrap decision.
# The only public entrypoint: Caddy (caddy/Caddyfile). Terminates TLS,
# serves the SPA, reverse-proxies everything else, and obtains and renews
# its own certificates over DNS-01 into ./caddy/data, with no reload and no
# inbound port. It replaced nginx and the certbot container on 2026-11-17;
# both are in .deprecated/ (DEPLOYMENT.md §7 has the rollback).
#
# START ORDERING: these `depends_on` entries are the plain list form, which
# only waits for each container to be *created and started*, NOT for it to be
# ready or healthy. That is deliberate — nginx's `resolver 127.0.0.11` means
# upstreams are resolved per-request, so a late-starting backend produces a
# temporary 502 rather than a failed nginx boot. The one ordering nginx
# genuinely cares about (the Vue build finishing) is handled by the polling
# loop in its entrypoint, because depends_on cannot express "wait for a
# one-shot container to exit successfully" here.
nginx:
# ENVIRONMENT: an explicit list, not the whole .env, so the edge never sees
# the database password or the JWT secret. A variable the Caddyfile reads
# must be added here, or it reaches Caddy empty. The ${X:-default} forms
# are the defaults nginx's entrypoint gave the optional services; they live
# here because Caddy's own {$X:default} keeps a variable that is set but
# empty, which is how a blank line in .env arrives.
#
# NO depends_on: Caddy resolves an upstream when it dials it, so it starts
# with any of them missing (502 until it appears), and there is no Vue
# build to wait for: the SPA is files in vue_dist, served as they appear.
caddy:
build:
context: ./nginx
context: ./caddy
dockerfile: Dockerfile
container_name: nginx
env_file: ./.env
container_name: caddy
restart: always
depends_on:
- vue
- backend
- icecast2
- gitea
- silverbullet
- silverbullet-public
- python
- jobs
environment:
- DOMAIN=${DOMAIN}
- BACKEND_HOST=${BACKEND_HOST}
- BACKEND_PORT=${BACKEND_PORT}
- BACKEND_ENDPOINT=${BACKEND_ENDPOINT}
- ICECAST_HOST=${ICECAST_HOST}
- ICECAST_PORT=${ICECAST_PORT}
- GITEA_HOST=${GITEA_HOST}
- GITEA_PORT=${GITEA_PORT}
- SILVERBULLET_HOST=${SILVERBULLET_HOST:-silverbullet}
- SILVERBULLET_PORT=${SILVERBULLET_PORT:-3000}
- SILVERBULLET_PUBLIC_HOST=${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}
- SILVERBULLET_PUBLIC_PORT=${SILVERBULLET_PUBLIC_PORT:-3000}
- PYTHON_HOST=${PYTHON_HOST:-python}
- PYTHON_PORT=${PYTHON_PORT:-8000}
# A dead port by default, so /receipt/ reads "offline".
- RECEIPT_WEB_UPSTREAM=${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}
- RECEIPT_WEB_TOKEN=${RECEIPT_WEB_TOKEN:-}
# Partner Radar (radar.DOMAIN): the adamf/cto stack's `web` container,
# which joins app-network under this alias (its docker-compose.stpvm.yml).
# While that stack is down the name does not resolve and radar.DOMAIN
# answers "offline".
- RADAR_UPSTREAM=${RADAR_UPSTREAM:-radar-web:80}
# Zone -> Zone -> Read and Zone -> DNS -> Edit; see .env.example.
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
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://caddy` would fail the
# name check). Any other container that calls the public site now
# reaches Caddy directly instead of hairpinning through the internet.
aliases:
- ${DOMAIN}
- www.${DOMAIN}
- radar.${DOMAIN}
# Fixed for cloudflared's extra_hosts (see there): an alias only
# exists while Caddy 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
volumes:
# Shared with certbot: the cert store nginx reads and certbot writes.
# PERSISTENT, and private key material — gitignored, never commit.
- ./certbot/conf:/etc/letsencrypt
# Shared with certbot: the ACME HTTP-01 challenge webroot. certbot drops
# tokens in, nginx serves them on port 80.
- ./certbot/www:/var/www/certbot
- uploads:/uploads
# The certificates, their keys and the ACME account. PERSISTENT and
# private key material: gitignored, never commit. Losing it only costs
# a re-issue on the next start (seconds over DNS-01), during which the
# tunnel, which verifies the certificate, serves 502s.
- ./caddy/data:/data
- caddy_config:/config
- uploads:/srv/uploads:ro
# The SPA written by the one-shot `vue` container.
- vue_dist:/etc/nginx/html
- vue_dist:/srv/www:ro
# The JSON request-body log, kept on the host so it survives rebuilds
# and the `traffic` container can tail it. Caddy rotates it itself
# (50 MiB, five files kept).
- ./logs/caddy:/var/log/caddy
# restart: always only acts when the process exits. On 2026-10-19 nginx's
# worker stalled while its master lived, and the site was down 4.6 hours
# with the container "Up". /caddy-health (http://127.0.0.1 in the
# Caddyfile) is answered by Caddy's own server, so a hung server shows
# here; Docker only marks it unhealthy, and the `autoheal` label is what
# gets it restarted (see the autoheal service). The image has busybox
# wget, not curl.
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/caddy-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.
certbot:
image: certbot/certbot:v3.1.0
container_name: certbot
volumes:
- ./certbot/entrypoint.sh:/entrypoint.sh
- ./certbot/conf:/etc/letsencrypt
- ./certbot/www:/var/www/certbot
entrypoint: ["/entrypoint.sh"]
env_file:
- .env
# Cloudflare Tunnel: an OUTBOUND connection from here to Cloudflare's edge,
# which then forwards visitors' requests back down it to Caddy. 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 Caddy's network aliases
# resolve to Caddy itself, so the certificate verifies; Caddy'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 Caddy can trust the CF-Connecting-IP header from this
# container and no other (trusted_proxies in caddy/Caddyfile). 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:
- caddy
# Pins the tunnel origin's names to Caddy's fixed address. Its 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 Caddy 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"
- "radar.${DOMAIN}:172.28.255.251"
networks:
- app-network
app-network:
ipv4_address: 172.28.255.250
backend:
build:
@@ -177,16 +277,12 @@ 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).
- ${OBSIDIAN_DIR}:/backend/notes
- ./logs:/backend/logs
# Same named volume nginx serves at /uploads/ — backend writes, nginx reads.
# Same named volume Caddy serves at /uploads/ — backend writes, Caddy reads.
- uploads:/backend/uploads
# Shared with icecast2, which plays these as the radio fallback playlist;
# the backend reads them to report what is queued.
@@ -244,11 +340,12 @@ services:
# listeners connect to, proxied at /radio/) and liquidsoap (the source that
# feeds it). See icecast2/entrypoint.sh.
#
# This is the only non-nginx service that publishes a host port, and it has
# This is the only non-Caddy 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.
# through Caddy 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
# the published port always matches what liquidsoap actually binds.
icecast2:
@@ -267,7 +364,7 @@ services:
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
# Browser-based editor for the vault, so notes are editable from a phone.
# Proxied at /sb/ behind the nginx admin gate. The public site at /notes/ is
# Proxied at /sb/ behind Caddy's admin gate. The public site at /notes/ is
# a SECOND, read-only SilverBullet over the same folder (silverbullet-public,
# below).
#
@@ -285,7 +382,7 @@ services:
environment:
SB_PORT: "${SILVERBULLET_PORT:-3000}"
# The app builds its service-worker scope and asset URLs from this, which
# is why nginx must NOT strip the /sb/ prefix. See nginx.conf.template.
# is why Caddy must NOT strip the /sb/ prefix. See caddy/routes.caddy.
SB_URL_PREFIX: /sb
# Only .obsidian: it is editor config and plugin JS, not notes.
#
@@ -320,14 +417,14 @@ services:
# URL /notes/private/x (server-rendered with the
# note's content), nor /.fs/.git/ — SilverBullet
# only applies it to listing (checked in 2.11.0).
# 2. nginx deny blocks 404 any private/ or templates/ segment and any
# 2. Caddy deny rules 404 any private/ or templates/ segment and any
# nested dot-folder under /notes/; this is what
# actually closes those holes. Keep its folder list
# in step with the one below.
# 3. SB_REVISIONS the default ("unmanaged") serves history from the
# vault's own .git, i.e. every version of every file
# including private/ and deleted ones. Disabled here,
# and nginx blocks /notes/.revisions as well.
# and Caddy blocks /notes/.revisions as well.
#
# SB_READ_ONLY rejects writes server-side and also disables the shell and the
# /.proxy endpoint (otherwise an open fetch proxy). The :ro mount is a second
@@ -344,13 +441,13 @@ services:
- app-network
environment:
SB_PORT: "${SILVERBULLET_PUBLIC_PORT:-3000}"
# Same reason as the editor's SB_URL_PREFIX: nginx must not strip /notes/.
# Same reason as the editor's SB_URL_PREFIX: Caddy must not strip /notes/.
SB_URL_PREFIX: /notes
SB_READ_ONLY: "true"
SB_REVISIONS: disabled
# Newline separated (commas are silently ignored). Gitignore semantics,
# so these match at any depth. Must match the folder list in the
# /notes/ deny regex in nginx/nginx_routes.conf.template, or a new entry here is
# /notes/ deny regex in caddy/routes.caddy, or a new entry here is
# hidden from the list but still publicly fetchable.
SB_SPACE_IGNORE: |
private/
@@ -365,7 +462,7 @@ services:
# writes, and pulls what Obsidian pushes from elsewhere.
#
# WHY A SEPARATE CONTAINER and not SilverBullet's own shell backend: enabling
# that would give anyone who gets past the nginx admin gate command execution
# that would give anyone who gets past Caddy's admin gate command execution
# inside the container. Since SilverBullet itself runs with no SB_USER, that
# gate is the only thing protecting it, so the blast radius stays here.
silverbullet-git:
@@ -374,6 +471,13 @@ services:
restart: always
networks:
- app-network
# The vault's remotes are ssh://git@DOMAIN:2222/..., but Caddy's network
# aliases make DOMAIN resolve to Caddy 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"
@@ -394,7 +498,7 @@ services:
# ssh will not run for a uid with no passwd entry; see the file's comment.
- ./silverbullet/passwd:/etc/passwd:ro
# FastAPI side-service, proxied at /py/ with the prefix stripped by nginx.
# FastAPI side-service, proxied at /py/ with the prefix stripped by Caddy.
# ROOT_PATH=/py tells FastAPI it is mounted under a prefix so the generated
# OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own
# routes are written relative to /.
@@ -402,7 +506,7 @@ services:
# than `env_file: ./.env` — it only gets the variables it needs and never
# sees the database password, Spotify secrets, or the other API keys.
# CLAUDE_API_KEY is the one secret on the list: the rowing photo reader
# (POST /internal/rowing/read, called by the backend, blocked at nginx)
# (POST /internal/rowing/read, called by the backend, blocked at Caddy)
# makes its Claude call here.
python:
build:
@@ -431,12 +535,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. Caddy's admin gate 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 Caddy's admin gate 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 +579,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: Caddy's admin gate 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 Caddy'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 Caddy'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/caddy:/logs:ro
# Dozzle: a live, searchable web view of every container's logs, served at
# /dozzle/ behind the admin login (caddy/routes.caddy). 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 caddy 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; Caddy
# 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. Caddy is deliberately NOT
# given it in depends_on: it resolves garage when it dials it, so a missing
# or crash-looping garage only makes bucket-only files 404 (everything on
# the volume is still served), never Caddy's start; 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 Caddy's admin gate.
# Manages buckets and keys, and browses/uploads/deletes objects. Its own
# login (AUTH_USER_PASS) is left unset because Caddy's admin gate 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 +865,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 Caddy 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 Caddy's /uploads/ route
# 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"
+2 -2
View File
@@ -20,8 +20,8 @@
# rather than retrying, so the loop polls (forever, by design — there is no
# sensible timeout when the answer is "wait longer") until Gitea responds.
# It targets localhost:3000, the port docker-compose.yml publishes directly,
# NOT the public /gitea/ path through nginx — so the runner keeps working
# even while TLS or nginx is broken.
# NOT the public /gitea/ path through Caddy — so the runner keeps working
# even while TLS or Caddy is broken.
#
# THE REGISTRATION TOKEN (one-shot, and easy to get wrong)
# GITEA_RUNNER_REGISTRATION_TOKEN comes from ./.env and is generated in the
+8 -7
View File
@@ -14,19 +14,22 @@
; Gitea generates one itself on first run and writes it into the live app.ini.
;
; SETTINGS WORTH KNOWING
; ROOT_URL must match the public path nginx serves Gitea at (/gitea/), or
; ROOT_URL must match the public path Caddy serves Gitea at (/gitea/), or
; every link, clone URL and OAuth redirect Gitea emits will be wrong.
; START_SSH_SERVER = true with SSH_PORT 2222: the rootless image cannot bind
; 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.
; Caddy at ROOT_URL and stay public.
; REVERSE_PROXY_LIMIT = 1 / TRUSTED_PROXIES = * : trust exactly one hop of
; X-Forwarded-For, i.e. our nginx, so Gitea logs real client IPs. This is
; only safe because nginx is the sole edge.
; X-Forwarded-For, i.e. our Caddy, so Gitea logs real client IPs. Caddy
; sends a single entry, the visitor (its `proxy` snippet). This is only
; safe because Caddy is the sole edge.
; INSTALL_LOCK = true skips the first-run web installer.
; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up.
; OFFLINE_MODE = true — no calls out to gravatar/CDNs.
@@ -50,7 +53,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 +62,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

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