Author SHA1 Message Date
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
120 changed files with 9295 additions and 4229 deletions
+4
View File
@@ -32,3 +32,7 @@ Watchdog that restarted any container docker marked `unhealthy` (only `backend`
and `python` define healthchecks). It mounts the docker socket, which is
effectively root on the host. To bring it back, layer
`docker-compose.autoheal.yml` the same way as above.
Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers
labelled `autoheal=true` (nginx). This copy is the old `all` variant, kept for
reference.
+83 -17
View File
@@ -15,18 +15,14 @@
#
# 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.
# 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,6 +48,9 @@ POSTGRES_HOST=db
POSTGRES_JOBS_DB=jobs
POSTGRES_JOBS_USER=jobs
POSTGRES_JOBS_PASSWORD=
POSTGRES_TRACKER_DB=tracker
POSTGRES_TRACKER_USER=tracker
POSTGRES_TRACKER_PASSWORD=
# --- Gitea -------------------------------------------------------------------
# GITEA_HOST is the container name AND the nginx upstream host.
@@ -63,6 +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.
@@ -186,14 +190,27 @@ LIQUIDSOAP_HARBOR_PORT=8001
DOMAIN=
EMAIL=
# --- Cloudflare Tunnel -------------------------------------------------------
# Token of the remotely managed tunnel the `cloudflared` container runs
# (Zero Trust -> Networks -> Tunnels -> your tunnel -> the `--token` value in
# the install command). Hostnames and origin settings are configured in the
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
# the container restarting with an error and the site reachable directly.
CLOUDFLARE_TUNNEL_TOKEN=
# Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API
# Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the
# certificate renews without any inbound port, so the router's 80/443
# forwards can close. Blank falls back to HTTP-01 on port 80.
CLOUDFLARE_DNS_API_TOKEN=
# --- Third-party API keys (backend) ------------------------------------------
# CLAUDE_API_KEY is used by the python service, which makes every Claude call
# in the stack: the rowing photo reader, the job posting reader and the email
# pipeline's classifier. The backend no longer calls Claude itself.
CLAUDE_API_KEY=
# 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 +230,54 @@ 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=
# 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=
# --- 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
# TfL Unified API key (500 req/min); used by the Python hotel finder
TFL_APP_KEY=
# --- Garage object store (public /uploads/) -----------------------------------
# See garage/garage.toml and DEPLOYMENT.md ("Garage"). Everything here is
# optional for the site to run: with S3_ENDPOINT blank the backend keeps
# writing uploads to the `uploads` volume exactly as before.
#
# Garage's own secrets, passed to the garage and garage-webui containers.
# Generate each with `openssl rand -hex 32`. The RPC secret must never change
# once the node has data; the admin token unlocks garage-webui's whole API.
GARAGE_RPC_SECRET=
GARAGE_ADMIN_TOKEN=
# The backend's S3 access, imported into Garage by garage/bootstrap.sh.
# Garage only accepts this shape:
# S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12))
# S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32)
S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY=
# Blank keeps uploads on disk. Set to http://garage:3900 (after running
# garage/bootstrap.sh) to store new public uploads in the bucket; recreate the
# backend after changing it. If a write to Garage fails the backend logs it and
# writes to disk instead, and nginx serves the file from there.
S3_ENDPOINT=
# Optional; these defaults match garage.toml and bootstrap.sh.
S3_REGION=garage
S3_BUCKET=uploads
# Optional, bootstrap.sh only: the node's capacity in the layout. With one node
# it only has to be non-zero; it is not a quota. Default 20G.
GARAGE_CAPACITY=
+5 -9
View File
@@ -29,7 +29,7 @@
#
# NOT TESTED HERE: THE VUE BUILD
# Deliberately skipped. `docker compose up --build` in the deploy job
# already runs the full frontend build (wasm-pack + vite) while building the
# already runs the full frontend build (npm ci + vite) while building the
# vue image, and a failed image build aborts `up` BEFORE any container is
# replaced, so the old site keeps serving. Building it a second time here
# would cost the Pi several minutes per push to learn nothing new. The same
@@ -87,9 +87,7 @@ jobs:
test -f "$SRC/python/requirements-dev.txt"
echo "Exported $SHA ($REF) to $SRC"
# The whole repo is mounted, not just backend/, because
# services/env_manager_test.go reads ../../.env.example to check
# it against env_registry.json. Read-only: tests write only to
# The whole repo is mounted read-only. Tests write only to
# t.TempDir(), and a read-only mount means the container (root)
# cannot leave root-owned files in $SRC that the clean-up step,
# running as the runner user, could not delete.
@@ -170,12 +168,10 @@ jobs:
- name: Run docker compose up
working-directory: /home/adamf/deploy/web_server
env:
DOCKER_API_VERSION: "1.41"
COMPOSE_BAKE: "false"
# The lock is shared with env-apply/apply.py, so a deploy and a
# .env change made from the admin panel cannot run compose at
# the same time.
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
# The lock is shared with maintenance.yaml, so a deploy and the
# weekly rebuild cannot run compose at the same time.
run: flock .compose.lock docker compose up -d --build --remove-orphans
- name: Prune unused Docker resources
run: docker image prune -f
+11 -17
View File
@@ -21,28 +21,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
+4 -10
View File
@@ -1,15 +1,16 @@
icecast2/fallback_music/*
.claude/
!icecast2/fallback_music/.gitkeep
certbot/conf
certbot/www
backend/token/
jobs-data/
usaco-data/
.env
.env.bak
# Admin panel -> host hand-off (request and status files, holds secrets)
env-apply/run/*
!env-apply/run/.gitkeep
# flock taken by the deploy and maintenance workflows around docker compose
.compose.lock
gitea/data/*
gitea/config/app.ini
@@ -19,9 +20,6 @@ gitea-runner/.runner
gitea-runner/act_runner
gitea-runner/nohup.out
# Rust build artifacts
**/target/
# Python bytecode
__pycache__/
*.pyc
@@ -30,9 +28,6 @@ __pycache__/
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
/.venv/
# Generated WASM output
vue/src/wasm/
# Logs
logs
*.log
@@ -74,7 +69,6 @@ __screenshots__/
.deploy
*.xcf
sync-secrets.sh
# Local-only outstanding-work notes, deliberately not published
TODO-NEXT.md
+13 -10
View File
@@ -40,7 +40,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 +52,19 @@ This regenerates `graph/generated.go` and `graph/model/models_gen.go`. Resolver
## Architecture
Dockerized multi-service personal website self-hosted on a Raspberry Pi.
Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubuntu VM; formerly a Raspberry Pi).
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode).
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), chosen on the admin panel's Environment tab; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are in `env_registry.json` with `services: ["jobs"]`.
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public.
## Backend Structure
@@ -73,16 +75,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)
- `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. `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). `/stp` is `views/home3/Home3.vue`: a canvas of admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type. The canvas (`views/home3/BoxCanvas.vue`) is reusable per page key: the landing page (`/`) is one too, and admin-created `Page`s (e.g. shrines) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. 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`.
@@ -93,7 +96,7 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
- **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`.
- **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`. 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.
+313 -137
View File
@@ -4,15 +4,19 @@ How this site is put together and how to operate it. Application code is
documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only
— compose, nginx, TLS, the runner, and the runbook.
Everything runs on a single Raspberry Pi, as Docker containers on one bridge
Everything runs on a single host, `stpvm` (an x86-64 Ubuntu VM on Proxmox,
reached over Tailscale as `stpvm.tailf20278.ts.net`; until 2026-10-15 it was
the Raspberry Pi `stppi`), as Docker containers on one bridge
network, behind one nginx.
---
## 1. Service topology
Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
3000/2222, and the liquidsoap harbor port. Everything else is internal.
Only three things are reachable from outside the host: nginx on 80/443, Gitea on
3000/2222, and the liquidsoap harbor port. Everything else is internal. Web
traffic can also come in through the Cloudflare tunnel (`cloudflared`), which
dials out and publishes no port; see "Cloudflare Tunnel" in §3.
```
internet
@@ -47,20 +51,27 @@ backend icecast2 gitea sb sb-pub python | |
### Who listens where
| Service | Container name | Internal port | Public route | Published to host |
|---|---|---|---|---|
| nginx | `nginx` | 80, 443 | — | **80, 443** |
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
| silverbullet-git | n/a | n/a | none (timer loop) | no |
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by the app itself) | no |
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
| certbot | `certbot` | — | — | no |
| Service | Container name | Internal port | Public route | Published to host |
| --------------------------------------------- | ----------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------- |
| nginx | `nginx` | 80, 443 | — | **80, 443** |
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
| silverbullet-git | n/a | n/a | none (timer loop) | no |
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by nginx `auth_request`; capture API and userscript public, bearer-token) | no |
| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by nginx `auth_request`; `/api/v1/` bearer/app-checked) | no |
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
| certbot | `certbot` | — | — | no |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy nginx) | `autoheal` | — (no network) | none; reads the Docker socket | no |
| garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no |
| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by nginx `auth_request`) | no |
Container names come from `.env`, and nginx builds its upstreams from the same
variables. **Renaming a `*_HOST` value renames the container and repoints nginx
@@ -78,19 +89,28 @@ in one step — never change one without the other.**
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
backend down (502s until it appears) instead of refusing to start.
- **Admin gate.** `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
SPA login. None of these services has any auth of its own at that path.
- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
branch views stay public) are
protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure
redirects to the SPA login. Most of these services have no auth of their own at that path; the
job and activity trackers also check the session themselves. Their carve-outs, which a session
cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps:
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`.
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of
nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
file *list*; direct `/.fs/` fetches and server-rendered page URLs still serve
file _list_; direct `/.fs/` fetches and server-rendered page URLs still serve
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the
comment above `location /notes/` in `nginx_routes.conf.template`.
- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads`
volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so
user-supplied files cannot execute anything on our origin.
- **Uploads: the bucket first, then disk.** `/uploads/<f>` is fetched from
Garage's website endpoint and, if Garage has no such file or is down, from
the shared `uploads` volume (`@uploads_disk`). Both paths add `nosniff`,
`Content-Disposition: inline` and a deny-all CSP, so user-supplied files
cannot execute anything on our origin. The bucket is the source of truth;
a Garage outage only affects files that exist nowhere else. See "Garage"
in §7.
- **Rate limits** — see §6.
---
@@ -105,16 +125,16 @@ docker compose up --build
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
- renders `nginx.conf.template` if the cert is there, else
`nginx_setup.conf.template`;
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
nginx either way.
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
- renders `nginx.conf.template` if the cert is there, else
`nginx_setup.conf.template`;
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
nginx either way.
3. `certbot` obtains or confirms the certificate, then loops renewing.
4. Everything else comes up in parallel; `depends_on` here is the plain list
form, which waits only for *start*, not readiness.
form, which waits only for _start_, not readiness.
On the Pi this is triggered automatically by `.gitea/workflows/deploy.yaml`,
On the host this is triggered automatically by `.gitea/workflows/deploy.yaml`,
which has two jobs:
- **`test`** runs on every push to any branch. It exports the pushed commit
@@ -127,9 +147,9 @@ which has two jobs:
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
hard-resets the deploy checkout, and runs
`docker compose up -d --build --remove-orphans` under the
`env-apply/run/lock` flock.
`.compose.lock` flock, shared with the weekly maintenance workflow.
The test job keeps state on the Pi outside the deploy checkout: a bare
The test job keeps state on the host outside the deploy checkout: a bare
repository cache at `/home/adamf/.cache/web_server-ci/` and three named
volumes (`web_server_ci_gomod`, `web_server_ci_gobuild`, `web_server_ci_pip`).
The weekly maintenance workflow's `docker image prune -af` removes the two
@@ -148,10 +168,9 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
The override layer changes five services and disables one:
- **vue** — `npm run dev` instead of a one-shot build; `./vue` is bind-mounted
for hot reload, with anonymous-volume masks on `/app/node_modules` and
`/app/src/wasm` so the image's installed deps and compiled WASM are not hidden
by the bind mount. You need neither `node_modules` nor a Rust toolchain on the
host.
for hot reload, with an anonymous-volume mask on `/app/node_modules` so the
image's installed deps are not hidden by the bind mount. You don't need
`node_modules` on the host.
- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a
`CN=localhost` certificate (once, kept in `certbot/conf`) and render
`nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and
@@ -166,7 +185,7 @@ Visit `http://localhost`.
**`SEED_DB`** makes the Go backend populate the database with test posts, users
and messages at startup. It is set only in the dev override and must never be
set on the Pi — it would inject fake content into the live site.
set on the host — it would inject fake content into the live site.
Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
`/api`, `/gitea` and `/radio` to locally running services.
@@ -179,8 +198,7 @@ Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
The production nginx config references
`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port
80. On a brand-new host neither can go first.
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port 80. On a brand-new host neither can go first.
`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no
upstreams, nothing that can fail to load. It serves
@@ -190,7 +208,7 @@ so a half-configured site is never partially exposed.
**First run on a new domain:**
1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx
config.`
config.`
2. certbot runs `certbot certonly --webroot` and writes the certificate into
`./certbot/conf` (bind-mounted into both containers — that sharing is what
makes the whole thing work).
@@ -205,6 +223,13 @@ until the cert is inside its 30-day window, so this is well within Let's Encrypt
rate limits — it just means the window is checked twice a day. Certs are valid 90
days, so renewal lands around day 60.
**Validation method.** With `CLOUDFLARE_DNS_API_TOKEN` set, certbot proves
control of the domain by creating a `_acme-challenge` TXT record through the
Cloudflare API (DNS-01), so renewal needs no inbound port at all. That is
what lets the router's 80/443 forwards close behind the tunnel. Without the
token it uses the webroot (HTTP-01) on port 80, as it always did. Switching
either way takes effect at the next renewal; see `certbot/entrypoint.sh`.
**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container
cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the
certificate at startup and holds it in memory, so **a renewed certificate is not
@@ -212,6 +237,93 @@ served until nginx is reloaded or restarted.** In practice pushes to `main`
recreate nginx often enough to hide this. If the site ever serves an expired
cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
### Cloudflare Tunnel
The `cloudflared` container holds an outbound connection to Cloudflare and
forwards requests for the site's hostnames down it to nginx. It is a
_remotely managed_ tunnel: the only thing in this repo is the token
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
origin settings live in the dashboard.
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
terminates the visitor's TLS at its edge, and cloudflared opens a second TLS
connection to nginx. That is deliberate. Pointed at `http://nginx:80`, the
tunnel would hit the HTTP→HTTPS redirect and loop. Going to :443 keeps every
redirect, security header and the `X-Forwarded-Proto: https` the backend's
Secure cookies depend on, and needs no nginx change.
The origin is the public name, not `nginx`, because nginx carries `<DOMAIN>`
and `www.<DOMAIN>` as network aliases on `app-network` (`docker-compose.yml`).
Inside the network those names resolve to the nginx container, so the hop
never leaves the host, and cloudflared verifies the Let's Encrypt certificate
against a name it covers. `https://nginx` would fail that check and need No
TLS Verify. The flip side: **an expired certificate now takes the tunnel down
with a 502**, which is why renewal over DNS-01 (step 5) matters.
Setup, once:
1. Cloudflare dashboard → the domain must be on Cloudflare DNS.
2. Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy the
token from the install command (the long string after `--token`).
3. Put it in `.env` as `CLOUDFLARE_TUNNEL_TOKEN`, then
`docker compose up -d cloudflared`. The tunnel
shows as Healthy in the dashboard.
4. Add a public hostname per name, each with service `HTTPS` and its own
name as the URL, and no other settings:
- `www.<DOMAIN>` → `https://www.<DOMAIN>`: the site.
- `<DOMAIN>` → `https://<DOMAIN>`: nginx redirects it to www, and it serves Gitea's registry
at `/v2/`.
Creating each hostname replaces the existing A record for that name with
a CNAME to the tunnel. **That is the cutover**: until then the tunnel
carries nothing.
5. Create a Cloudflare API token (My Profile → API Tokens → "Edit zone
DNS", this zone only) and set it as `CLOUDFLARE_DNS_API_TOKEN`. certbot
then renews over DNS-01 (see Renewal above) and needs no inbound port.
6. On the host, point the apex at nginx locally (next section).
7. Close the router's 80 and 443 forwards. Once 5 and 6 are done nothing
depends on them.
#### What the tunnel does not carry, and where it goes instead
- **Certificate renewal.** Over DNS-01 with `CLOUDFLARE_DNS_API_TOKEN` set;
without it certbot falls back to HTTP-01, which needs port 80 forwarded.
The certificate matters behind the tunnel: cloudflared verifies it, as
do the registry path below and any direct LAN access. A fresh machine with no
certificate at all boots the setup config (§3), which serves nothing over
443, so the tunnel carries nothing until the first issuance.
- **Registry pushes and pulls on the host.** Cloudflare caps request bodies at
100 MB on the free plan, so a push of a larger image layer through the
tunnel fails. The runner on the host pushes to `<DOMAIN>/adamf/...` and the
stack pulls from it, both through the host's Docker daemon, which resolves
names through the host's `/etc/hosts`. Pin the apex there to the loopback:
```
127.0.0.1 <DOMAIN>
```
so registry traffic goes straight to nginx on :443, with the real
certificate, and never leaves the host. (Without it the name resolves to
Cloudflare once DNS moves there.) Only the apex: www stays on Cloudflare for anything on the host
that wants the public site. Pushing from another machine still goes
through Cloudflare and its cap; use the host's Tailscale name for that.
- **Gitea SSH (2222).** Not HTTP, so not tunnelled. Already Tailscale-only:
`GITEA_SSH_DOMAIN` in `.env` (Gitea's `SSH_DOMAIN`) is the host's MagicDNS name
and 2222 has never been forwarded. Nothing changes.
- **The radio harbor (8001).** Also a raw source protocol, so a DJ client
pointed at `<DOMAIN>:8001` stops connecting once the domain resolves to
Cloudflare. Point it at the host's Tailscale name
(`stpvm.tailf20278.ts.net:8001`) and close the 8001 forward. A guest DJ
off the tailnet would need either a Tailscale share of the host or a
Cloudflare TCP route used with `cloudflared access tcp` on their side.
#### Other limits
- Cloudflare returns a 524 if the origin sends no response bytes for 100
seconds. Streaming endpoints are fine while they keep writing; a long
silent request is not.
- Dev never runs cloudflared (`disabled` profile in `docker-compose.dev.yml`),
so a laptop cannot join the production tunnel.
---
## 4. What persists across restarts
@@ -219,27 +331,28 @@ cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
**Named volumes** — survive `docker compose down` and rebuilds; destroyed only by
`docker compose down -v` or `docker volume rm`:
| Volume | Holds | Losing it means |
|---|---|---|
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
| `uploads` | User-uploaded files (backend writes, nginx serves) | All uploaded images |
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
| Volume | Holds | Losing it means |
| ---------- | ----------------------------------------------------- | -------------------------------------------------- |
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
| `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files |
| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) |
| `garage_data` | The bucket's object bytes | Every upload stored in Garage |
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
**Bind mounts** — live in the repo checkout on the Pi, survive everything short
**Bind mounts** — live in the repo checkout on the host, survive everything short
of deleting the directory:
| Path | Holds | Notes |
|---|---|---|
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
| `./certbot/www` | ACME challenge webroot | Transient by nature |
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
| `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. |
| `./env-apply/run` | The admin panel's queued `.env` change (`request.json`) and the host's report on it (`status.json`) | Gitignored. Transient, but must be owned by the deploy user, not root — see §5. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs | |
| `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git |
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
| Path | Holds | Notes |
| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
| `./certbot/www` | ACME challenge webroot | Transient by nature |
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
| `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") |
| `./icecast2/fallback_music` | Radio fallback MP3s | Copied to the host by hand, not git |
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
**Ephemeral:** anything else inside a container. Notably the Vue build, the
rendered nginx/icecast configs, and the Gitea runner's downloaded binary
@@ -269,48 +382,21 @@ makes the site's one Claude call (the rowing photo reader); the `jobs` container
allow-list with its own database role. The backend receives `CLAUDE_API_KEY`
through `env_file` but does not use it. A new variable for either service has
to be added to its allow-list as well as
`.env.example` and `backend/services/env_registry.json`; backend tests fail if
the three disagree.
`.env.example`.
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
`.env`, and `icecast2/fallback_music/*.mp3`. The sync is **bidirectional and
resolved by modification time — newer wins, with no merge.** Editing `.env` on
both machines silently loses one side's edits. Run it before and after editing.
**`.env` is edited by hand on the host**, in
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's
`.env` (often with dev values) never reaches production by accident.
An unset variable is not an error: `envsubst` renders it as an empty string,
which for a password field means *no password*. After editing `.env`, confirm
which for a password field means _no password_. After editing `.env`, confirm
with `docker compose config`.
### Editing from the admin panel
### Changing a value on the host
The **Environment** tab at `/admin` edits `.env` on the Pi without SSH. API
keys, OAuth client settings, the email settings and the generated secrets are
editable; anything that would rename a container, move a port or lock the
backend out of Postgres is shown read-only.
The backend cannot write `.env` or reach Docker. It queues the change in
`./env-apply/run/request.json`, and a systemd path unit on the host runs
`env-apply/apply.py`, which:
1. rewrites `.env` atomically, keeping comments and order, with the previous
version saved as **`.env.bak`**;
2. runs `docker compose config -q` and restores the backup if compose rejects
the file;
3. recreates only the services that read the changed variables, plus the
backend (`docker compose up -d --no-deps --force-recreate …`);
4. writes the outcome to `status.json`, which the panel is polling.
Only those services are recreated because nginx, db, icecast2 and certbot load
the whole file too; a plain `up -d` would restart Postgres for a Steam key.
They pick the new file up at the next deploy, which is harmless.
**The watcher is installed once per host** — see the runbook. Without it the
panel still queues the change and says nothing has picked it up.
A change made this way makes the Pi's `.env` the newer copy, so the next
`./sync-secrets.sh` pulls it down to the laptop. The newer-wins caveat above
still applies: do not also edit the local copy before syncing.
Edit `.env` on the host, and recreate only the services that read the variable:
`docker compose up -d <service>`. A plain `up -d` would also restart Postgres,
since nginx, db, icecast2 and certbot load the whole file.
---
@@ -324,29 +410,32 @@ tuned value.
`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one
request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead
of that drip, and `nodelay` (used everywhere here) serves those N immediately.
So the effective behaviour is *"N instant requests, then throttled to the drip
rate"*. Anything beyond the burst gets an immediate **503**.
So the effective behaviour is _"N instant requests, then throttled to the drip
rate"_. Anything beyond the burst gets an immediate **503**.
| Zone | Rate | Burst | Applied to | Why |
|---|---|---|---|---|
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
| `upload` | 5/min | 3 | `/api/messages/upload` | Uploads can be 50MB and hit disk; bounds how fast one IP fills the volume. |
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
| Zone | Rate | Burst | Applied to | Why |
| -------------- | ------ | ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
| `upload` | 30/min | 20 | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
request, and a limit there would drop reconnect storms rather than abuse.
These zones key on the direct client IP, which is correct because nginx is the
sole edge. **If a CDN or proxy is ever put in front, they must switch to a
trusted `X-Forwarded-For` or every visitor shares one bucket.**
These zones key on `$remote_addr`. For tunnel traffic nginx rewrites that
from Cloudflare's `CF-Connecting-IP` header (`set_real_ip_from` /
`real_ip_header` in `nginx.conf.template`), trusting the header only from
cloudflared's fixed address. **If that address changes in
`docker-compose.yml` without the nginx line, every tunnel visitor shares
cloudflared's one bucket**, and the login limit locks everyone out together.
---
## 7. Runbook
All commands run from the deploy checkout on the Pi
All commands run from the deploy checkout on the host
(`~/deploy/web_server`) unless stated.
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
@@ -356,24 +445,6 @@ it. By hand:
git pull && docker compose up -d --build --remove-orphans
```
**Install the `.env` watcher** (once per host; lets the admin panel's
Environment tab apply changes):
```
./env-apply/install.sh # asks for sudo
systemctl status web-server-env-apply.path # should be active (waiting)
journalctl -u web-server-env-apply.service # one entry per applied change
```
Run it as the user that owns the checkout. `env-apply/run` must belong to that
user: if Docker created it first it is root-owned, and the script fixes that.
To apply a queued change by hand, or undo one:
```
python3 env-apply/apply.py # apply what the panel queued
cp .env.bak .env && docker compose up -d # roll back the last change
```
**Rebuild one service** (e.g. after changing only the backend):
```
@@ -410,6 +481,40 @@ docker compose ps # note: `vue` Exited(0) is correct
docker compose logs certbot # issuance / renewal outcomes
```
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
login required).
**Incoming request bodies.** nginx writes one JSON line per request, body
included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The
`traffic` container tails it, so in Dozzle pick **traffic** and each request
renders as fields you can search. From a shell:
```
tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")'
jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log
```
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
(that covers every login and the refresh call). Bodies over 64 KB, i.e.
uploads, are logged with an empty `body`, and responses are never logged.
The file is never rotated by the stack. On the host, add
`/etc/logrotate.d/web_server`:
```
/home/adamf/deploy/web_server/logs/nginx/*.log {
weekly
rotate 4
compress
missingok
notifempty
copytruncate
}
```
`copytruncate` because nginx keeps the file open; `tail -F` in `traffic`
follows the truncation.
**Reset the database** — destructive; wipes the app database **and Gitea's**:
```
@@ -427,37 +532,108 @@ manually before Gitea will start:
docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB"
```
**Sync secrets / fallback music** (from the laptop checkout, not the Pi):
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket,
with the `uploads` volume as a safety net. Nothing breaks while Garage is down
or not set up:
- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to
disk (with a log line) whenever Garage refuses a write;
- nginx serves `/uploads/` from Garage and falls back to the volume when
Garage has no such file or is unreachable, and it boots without the
`garage` container.
Turning it on:
1. Fill in `GARAGE_RPC_SECRET`, `GARAGE_ADMIN_TOKEN`, `S3_ACCESS_KEY_ID` and
`S3_SECRET_ACCESS_KEY` in `.env` **before** the deploy that adds the
containers (otherwise `garage` crash-loops on a blank secret until they
are set; nothing else is affected). `.env.example` says how to generate
each.
2. Deploy, then `garage/bootstrap.sh` (idempotent; it creates the layout, the
`uploads` bucket and the backend's key, and opens the bucket to the
website endpoint).
3. Set `S3_ENDPOINT=http://garage:3900` and `docker compose up -d backend`.
The backend logs `[upload] storing uploads in bucket uploads ...` on start.
4. Check: upload something through a canvas page or chat, then
`docker compose exec garage /garage bucket info uploads` shows the object
count going up, and the returned `/uploads/...` URL loads.
Moving the old files in (so they show in garage-webui, and so the bucket
holds everything):
```
./sync-secrets.sh
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env)
docker run --rm --network web_server_app-network \
-v web_server_uploads:/data:ro \
-e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \
-e AWS_DEFAULT_REGION=garage \
amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \
--endpoint-url http://garage:3900
```
**Set up the CI runner on a fresh Pi:**
The copies left on the volume are then only a fallback for when Garage is
down, and the rollback. One catch: a file deleted in garage-webui is still
served from its disk copy, if it has one. Once the bucket has been trusted for
a while, remove everything but `private/` from the volume.
**Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files
written to the bucket in the meantime stay reachable as long as `garage` runs;
to drop Garage entirely, first copy them back
(`aws s3 sync s3://uploads /data` with the volume mounted read-write).
**Managing files:** garage-webui at `/garage/` (site admin login). Files
uploaded there are public at `/uploads/<path>` and skip the backend's type
checks; keep them under a prefix such as `media/`. Uploads through it are
capped at 2G by nginx.
**Backups:** Garage here is one node on the same disk — it is not a backup.
Back up `garage_meta` and `garage_data` together (meta without data, or the
reverse, is useless); Garage also snapshots its metadata every 6h inside
`garage_meta`.
**Set up the CI runner on a fresh host:**
```
cd gitea-runner
bash download.sh # pulls the arm64 binary
bash download.sh # pulls the binary for this CPU
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises
```
The runner lives **outside** Docker on purpose: it runs `docker compose up`
against this stack, so it cannot be a container in it. Registration is one-shot —
`.runner` is the lasting credential; re-registering needs that file deleted *and*
`.runner` is the lasting credential; re-registering needs that file deleted _and_
a fresh token.
**Go live on the radio:** point a broadcasting client (e.g. butt) at the Pi on
**Go live on the radio:** point a broadcasting client (e.g. butt) at the host's
Tailscale name (not the domain, which resolves to Cloudflare) on
`${LIQUIDSOAP_HARBOR_PORT}` with mount `${LIQUIDSOAP_HARBOR_MOUNT}` and the
icecast source password. liquidsoap pre-empts the fallback playlist immediately
(`track_sensitive=false`). Disconnect and it falls back to the playlist, then to
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
(`reload_mode="watch"`) with no restart.
**Unhealthy containers are not restarted automatically.** `backend` and `python`
define healthchecks, but the `autoheal` watchdog that acted on them was retired
(`.deprecated/autoheal`), so `unhealthy` is only visible in `docker ps`.
`restart: always` still brings back a container whose process exits.
**Only nginx is restarted when unhealthy.** Docker marks a container
`unhealthy` but never acts on it; `restart: always` only brings back a process
that exits. The `autoheal` container restarts anything labelled
`autoheal=true`, which today is just nginx (its healthcheck fetches
`/nginx-health` on :80 every 30s; three misses, about 90s, and it is
restarted). `backend` and `python` also define healthchecks, but carry no
label, so for them `unhealthy` is only visible in `docker ps`. Add the label to
cover another service.
**Site down but every container `Up`.** That is what a stalled nginx worker
looks like (2026-10-19: 4.6 hours, every tunnel request a `TLS handshake
timeout` in `docker logs cloudflared`, and the Cloudflare dashboard still
showing the tunnel healthy, since that only covers the tunnel's own link). The
healthcheck should now catch it. If it recurs, capture the stuck worker before
restarting, since a restart destroys the only evidence of why:
```
docker inspect nginx --format '{{.State.Health.Status}}'
docker top nginx -o pid,stat,wchan:30,etime,cmd # what each worker is waiting in
docker compose restart nginx
```
---
@@ -475,7 +651,7 @@ Documented, not fixed — each would change deploy behaviour.
mounted to the same in-container path as the real wrapper. It is currently
shadowed by an explicit file mount — fragile. Deleting it would be safe but
is a file removal.
4. **The two `/uploads/` location blocks are still written twice** — once in
4. **The `/uploads/` location blocks (with `@uploads_disk`) are still written twice** — once in
`nginx.conf.template` and once in `nginx_dev_common.conf.template` —
because production adds security headers inside an auth-gated block. Every
other proxied route lives once in `nginx_routes.conf.template`, which both
+3 -18
View File
@@ -11,8 +11,7 @@
# WHAT IT NEEDS ON THE HOST
# check-backend / generate Go (the version in backend/go.mod)
# check-python python3 with the venv module
# check-vue Node + `npm install` done in vue/, and the
# generated vue/src/wasm/ directory (see below)
# check-vue Node + `npm install` done in vue/
# check-compose / dev Docker with the compose plugin
# Nothing here installs a toolchain; a missing one fails that target only.
#
@@ -69,26 +68,12 @@ $(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
check-python: $(VENV_STAMP)
cd python && ../$(VENV)/bin/python -m pytest tests -q
# `npx vite build`, NOT `npm run build`: the npm script first runs wasm-pack to
# compile the Rust crate, which needs a Rust toolchain most machines (and the
# Pi) do not have. The Vite half alone is enough to catch a broken import or
# template.
#
# It does still need the OUTPUT of that Rust step, vue/src/wasm/, which is
# generated and gitignored — so a fresh clone has none and Vite would fail with
# a bare "could not resolve ../wasm/..." error. The guards below say what is
# actually wrong instead.
# A Vite build is enough to catch a broken import or template; there is no
# test runner or linter for the frontend.
#
# The build goes to a temp directory that is removed afterwards (success or
# failure), so the check never leaves a vue/dist behind or overwrites one.
check-vue:
@test -d vue/src/wasm || { \
echo "check-vue: vue/src/wasm/ is missing."; \
echo " It is the generated (gitignored) output of the Rust crate in vue/crates/"; \
echo " and the Vite build imports it. Create it with wasm-pack:"; \
echo " cd vue && npm run build:wasm"; \
echo " (needs a Rust toolchain; the vue image builds it for you, see vue/Dockerfile)."; \
exit 1; }
@test -d vue/node_modules || { \
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
exit 1; }
+3 -3
View File
@@ -1,3 +1,4 @@
Gay bal;;s
# My Web
![screenshot](vue/public/img/screenshot.png)
@@ -32,7 +33,7 @@ certbot ── SSL Certificate Management (disabled in dev)
## Tech Stack
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX)
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
@@ -147,7 +148,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
**Protected (auth required)**
| Method | Path | Description |
| --- | --- | --- |
| POST | `/api/messages/upload` | Upload message file (rate limited: 5/min) |
| POST | `/api/messages/upload` | Upload a file for a chat message or a canvas box (rate limited: 30/min, burst 20) |
**Admin (auth + admin required)**
| Method | Path | Description |
@@ -349,7 +350,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
+14 -46
View File
@@ -172,52 +172,10 @@ 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 |
| `/notes/*path` | streams a file download, not JSON |
| `/ws` | WebSocket upgrade |
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
| `/admin/env`, `/admin/logs` | process environment and files on disk, not the data model |
### Environment tab
`handlers/handle_env.go` and `services/env_manager.go` let the admin panel
change `.env` on the Pi without SSH. The backend never reads or writes the
file and has no Docker access: it validates an edit and leaves it for the
host, which is the part trusted to act.
- **`services/env_registry.json`** lists every variable in `.env.example`
with its group, kind, whether it is editable, and the compose services that
read it. It is embedded in the binary and read from the checkout by the host
script, so one file decides what the panel offers and what the host accepts.
A test fails if it and `.env.example` disagree.
- **The `python` and `jobs` services are a third place.** They are given an
explicit `environment:` list in `docker-compose.yml` instead of the whole
`.env`, so that they never hold the site's database password or the JWT
secret. A new variable for either therefore goes in the registry (with the
service in its `services`), in `.env.example`, *and* in that list.
`TestEnvRegistryMatchesComposePythonEnvironment` reads the compose file and
fails if a variable the registry says one of them reads is not passed to
it, or if an editable variable passed to it does not list that service. Locked
variables carry no `services` and are exempt (`PYTHON_PORT` is one).
- `GET /admin/env` — the registry plus state from this process's own
environment. A secret's value is never sent, only "set" and, for values of
12+ characters, the last four.
- `PUT /admin/env` — `{"set": {NAME: value}, "generate": [NAME]}`; `""`
clears. The whole batch is validated first. Control characters are refused
because `.env` is line oriented: a newline would let an edit to an allowed
variable write a second, arbitrary one. Generated values (32 random bytes,
hex) are returned once.
- The change is written to `/backend/env-apply/request.json` (`./env-apply/run`
on the host), `0600` and chowned to that directory's owner so the
unprivileged host user can read it. `env-apply/apply.py` claims it, rewrites
`.env`, recreates the affected services and writes `status.json`.
- `GET /admin/env/status` — `idle`, `pending`, `applying`, `applied` or
`failed`. `watcher: false` means a request has sat unclaimed for 15 seconds,
i.e. nothing on the host is watching. `DELETE /admin/env/pending` withdraws
an unclaimed request.
The backend is always among the recreated services, because the values the
panel shows are the ones this process started with.
## Calling the Python service
@@ -268,6 +226,16 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
(Steam).
- **python_call.go** — `CallPython`, the one way to reach the Python service's
internal routes. See [Calling the Python service](#calling-the-python-service).
- **uploads.go** — every stored file. `Uploads.Save(ctx, fileHeader, private)`
validates against `UploadTypes` (extension, stored Content-Type, content
sniff) and `MaxUploadSize`, names the file randomly, stores it and returns
its `/uploads/...` URL; an `*UploadError` is the uploader's fault and safe
to show them. Public files go to the Garage bucket wrapped in
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
(nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
first and disk second, so either store's files work at the same URL. A new
handler that takes a file calls `store.Uploads.Save`.
- **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 +324,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=
+18
View File
@@ -76,3 +76,21 @@ 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
+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)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// 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.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.Create(&box).Error; 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 {
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.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
}
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
}
return ptrs(boxes), nil
}
+47
View File
@@ -0,0 +1,47 @@
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"
"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
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":
if box.HTML == nil {
return errors.New("an html box needs html")
}
default:
return errors.New(`box kind must be "widget" or "html"`)
}
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
}
+44
View File
@@ -0,0 +1,44 @@
package graph
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidateBox(t *testing.T) {
str := func(s string) *string { return &s }
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},
{"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)
}
}
+2730 -17
View File
File diff suppressed because it is too large Load Diff
+48
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,34 @@ 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"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type CreateFavoriteInput struct {
Type string `json:"type"`
Name string `json:"name"`
Link *string `json:"link,omitempty"`
}
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 +141,26 @@ 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"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdatePageInput struct {
Slug *string `json:"slug,omitempty"`
Title *string `json:"title,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdatePlaceInput struct {
Title *string `json:"title,omitempty"`
Location *string `json:"location,omitempty"`
+152
View File
@@ -0,0 +1,152 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// CreatePage is the resolver for the createPage field.
func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePageInput) (*models.Page, error) {
page := models.Page{
Slug: input.Slug,
Title: strings.TrimSpace(input.Title),
}
if input.AdminOnly != nil {
page.AdminOnly = *input.AdminOnly
}
if err := validateSlug(page.Slug); err != nil {
return nil, err
}
if page.Title == "" {
return nil, errors.New("a page needs a title")
}
taken, err := slugTaken(r.Store.DB, page.Slug, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a page at that address")
}
if err := r.Store.DB.Create(&page).Error; err != nil {
return nil, err
}
return &page, nil
}
// UpdatePage is the resolver for the updatePage field.
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
// Partial update, like updateBox. A new slug moves the page's boxes and
// background with it in the same transaction, since both find their page
// by slug.
var page models.Page
if err := r.Store.DB.First(&page, id).Error; err != nil {
return nil, err
}
oldSlug := page.Slug
if input.Slug != nil {
page.Slug = *input.Slug
}
if input.Title != nil {
page.Title = strings.TrimSpace(*input.Title)
}
if input.AdminOnly != nil {
page.AdminOnly = *input.AdminOnly
}
if page.Title == "" {
return nil, errors.New("a page needs a title")
}
if page.Slug != oldSlug {
if err := validateSlug(page.Slug); err != nil {
return nil, err
}
taken, err := slugTaken(r.Store.DB, page.Slug, page.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a page at that address")
}
}
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
if page.Slug != oldSlug {
if err := tx.Model(&models.Box{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
return err
}
if err := tx.Model(&models.Background{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
return err
}
}
return tx.Save(&page).Error
})
if err != nil {
return nil, err
}
return &page, nil
}
// DeletePage is the resolver for the deletePage field.
func (r *mutationResolver) DeletePage(ctx context.Context, id int) (*models.Page, error) {
// The boxes and background go too: left behind, they would reappear on
// any page later created at the same address.
var page models.Page
if err := r.Store.DB.First(&page, id).Error; err != nil {
return nil, err
}
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("page = ?", page.Slug).Delete(&models.Box{}).Error; err != nil {
return err
}
if err := tx.Where("page = ?", page.Slug).Delete(&models.Background{}).Error; err != nil {
return err
}
return tx.Delete(&page).Error
})
if err != nil {
return nil, err
}
return &page, nil
}
// Pages is the resolver for the pages field.
func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
// Public, for page indexes such as /shrines; adminOnly pages are only
// listed for an admin.
query := r.Store.DB.Order("slug ASC")
if !IsAdminFromCtx(ctx) {
query = query.Where("admin_only = ?", false)
}
var pages []models.Page
if err := query.Find(&pages).Error; err != nil {
return nil, err
}
return ptrs(pages), nil
}
// Page is the resolver for the page field.
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
// Null, not an error, for a missing page: the SPA's catch-all route asks
// this for every unknown path and shows its 404 on null. An adminOnly
// page reads as missing to everyone else, so its existence isn't leaked.
var page models.Page
err := r.Store.DB.Where("slug = ?", slug).First(&page).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
if page.AdminOnly && !IsAdminFromCtx(ctx) {
return nil, nil
}
return &page, nil
}
+73
View File
@@ -0,0 +1,73 @@
package graph
// Hand-written helpers for page.resolvers.go and box.resolvers.go, kept out
// of the resolver files for the same reason as box_helpers.go.
import (
"context"
"errors"
"regexp"
"strings"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// pageKeyPattern is the shape of a box's page key and of a page slug: lower
// case words joined by hyphens, in one or more /-separated segments. It is
// URL-safe as it stands, so the front end can use a slug as a path without
// escaping it.
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
const maxSlugLen = 100
// reservedFirstSegments are paths a page could never be reached at, because
// nginx or one of the SPA's own routes answers them first (see
// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the
// built-in canvases' page keys, whose boxes a page of the same slug would
// share. "shrines" is deliberately absent: /shrines and the shrine pages under
// it are all canvas pages.
var reservedFirstSegments = map[string]bool{
"stp": true, "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 (a built-in canvas,
// 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
}
+33
View File
@@ -0,0 +1,33 @@
package graph
import "testing"
func TestValidateSlug(t *testing.T) {
for _, c := range []struct {
slug string
ok bool
}{
{"notes-to-self", true},
{"shrines/evangelion", true},
{"shrines/neon-genesis/rei2", true},
{"", false},
{"Shrines/GTO", false}, // upper case
{"shrines/", false}, // empty segment
{"/shrines/gto", false}, // leading slash
{"shrines//gto", false}, // empty segment
{"shrines/gto-", false}, // trailing hyphen
{"shrines/../admin", false}, // dots
{"shrines", true}, // the index is a canvas page too
{"shrines/demoman", true}, // no longer an SPA route
{"admin/pages", false}, // under an SPA route
{"jobs/x", false}, // under an nginx route
{"stp", false}, // a built-in canvas's key
{"index", false}, // likewise
{"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)
}
}
}
+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, "stp", or a Page's slug), so the
# landing page and every shrine 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
}
+67
View File
@@ -0,0 +1,67 @@
# Boxes on a canvas page: the home page (/stp, page "stp"), the landing
# page's overlay (page "index") or an admin-created Page (page = its slug).
# 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).
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!
hideOnMobile: Boolean!
adminOnly: Boolean!
}
input CreateBoxInput {
page: String!
kind: String!
widget: String
html: String
title: String
x: Int
y: Int
w: Int
h: Int
z: Int
framed: Boolean
hideOnMobile: Boolean
adminOnly: Boolean
}
input UpdateBoxInput {
widget: String
html: String
title: String
x: Int
y: Int
w: Int
h: Int
z: Int
framed: Boolean
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
}
+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
}
-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")
}
}
-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
}
+70
View File
@@ -0,0 +1,70 @@
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})
}
}
// 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
}
+19 -58
View File
@@ -14,23 +14,21 @@ 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.
// - 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 refresh fallback in ValidateAdmin: both
// reach the database on the refresh path.
//
// 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 +251,20 @@ 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)
}
}
})
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
// 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.
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)
}
}
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
})
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)
}
}
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)
}
})
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)
}
}
})
}
}
+3 -3
View File
@@ -38,9 +38,9 @@ type Store struct {
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string
// Registry of .env variables and the request/status hand-off with the
// host that applies changes to them (handle_env.go).
Env *services.EnvManager
// Stores uploaded files and says where they are served
// (services.Uploads.Save). Used by the Upload handler.
Uploads *services.Uploads
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
+18 -18
View File
@@ -128,19 +128,27 @@ func main() {
}
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// UPLOADS
// Public uploads go to the Garage bucket (and to the shared `uploads`
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
// private ones to the volume. See services/uploads.go. Region and bucket
// default to what garage/garage.toml and garage/bootstrap.sh set up.
s3Region := os.Getenv("S3_REGION")
if s3Region == "" {
s3Region = "garage"
}
s3Bucket := os.Getenv("S3_BUCKET")
if s3Bucket == "" {
s3Bucket = "uploads"
}
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
// 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Nginx rate-limits the login route too.
loginLimiter := services.NewRateLimiter(5, time.Minute)
// ENVIRONMENT
// The registry is embedded, so the only way this fails is a malformed
// env_registry.json — a build mistake worth stopping for.
envManager, err := services.NewEnvManager(services.ENV_APPLY_DIR)
if err != nil {
log.Fatal(err)
}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Env: envManager}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
@@ -181,19 +189,11 @@ 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)
// 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.
+69
View File
@@ -155,3 +155,72 @@ 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:
// "stp" for the home page, "index" for the landing page's overlay, or a
// Page.Slug for an admin-created page — it is a key, not a foreign key, so the
// built-in canvases need 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"`
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"`
}
// 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, "stp", 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"`
}
+3
View File
@@ -51,6 +51,9 @@ func migrateDatabase(db *gorm.DB) error {
&models.Message{},
&models.Bookmark{},
&models.Place{},
&models.Box{},
&models.Page{},
&models.Background{},
)
if err != nil {
return err
-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."}
]
+288
View File
@@ -0,0 +1,288 @@
package services
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// Uploaded files: everything the site stores from a user and serves back at
// /uploads/. One entry point for any handler that takes a file:
//
// url, err := store.Uploads.Save(ctx, fileHeader, private)
//
// Save validates the file against UploadTypes and MaxUploadSize, gives it a
// random name, stores it, and returns the URL to put in the page. An
// *UploadError is the uploader's fault and its message is safe to show them;
// any other error is ours (log it, answer 500).
//
// WHERE FILES GO
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
// the `uploads` volume as a fallback for when Garage refuses a write. nginx
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (nginx.conf.template), so the URL is the same wherever the
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
// the only store.
// Private files (admin-only chat attachments) always go to the volume, under
// /uploads/private/, which nginx gates behind an admin check. nginx can't
// sign S3 requests, so it has no way to gate a bucket.
//
// Everything public is reachable by anyone who has the URL, with no login.
// That is why the type checks below are strict, and why names are random.
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
// disk or the bucket; nginx rate-limits the route as well.
const MaxUploadSize = 10 << 20 // 10MB
// UploadType describes one allowed file extension.
type UploadType struct {
// ContentType is stored with the file and served back with it. Garage
// returns exactly this, and the browser renders by it: nginx adds
// `nosniff`, so a wrong type means the file doesn't display.
ContentType string
// SniffPrefix is what http.DetectContentType must report for the file's
// first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty
// means "not checked": DetectContentType is too unreliable for audio and
// gif files, and checking would reject legitimate ones.
SniffPrefix string
}
// UploadTypes is the allow-list, keyed by lower-cased extension with its dot.
// Nothing a browser would execute or render as markup (.html, .svg, .js, ...)
// may ever be added: these files are served from our own origin. The
// frontend's file pickers (vue/src/uploads.js, ACCEPT) list the same types.
var UploadTypes = map[string]UploadType{
".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".png": {ContentType: "image/png", SniffPrefix: "image/"},
".gif": {ContentType: "image/gif"},
".webp": {ContentType: "image/webp", SniffPrefix: "image/"},
".mp4": {ContentType: "video/mp4", SniffPrefix: "video/"},
".webm": {ContentType: "video/webm", SniffPrefix: "video/"},
".mp3": {ContentType: "audio/mpeg"},
".ogg": {ContentType: "audio/ogg"},
".pdf": {ContentType: "application/pdf", SniffPrefix: "application/pdf"},
".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"},
}
// UploadError is a rejected upload: the uploader's mistake, with a message
// meant for them. The handler answers 400 with it.
type UploadError struct{ Message string }
func (e *UploadError) Error() string { return e.Message }
var (
ErrUploadTooLarge = &UploadError{"file too large (the limit is 10MB)"}
ErrUploadType = &UploadError{"file type not allowed"}
ErrUploadContent = &UploadError{"file content does not match extension"}
ErrUploadUnreadable = &UploadError{"failed to read file content"}
)
// Uploads stores files. Build it with NewUploads.
type Uploads struct {
public FileStore
private FileStore
}
// URL prefixes the files are served under; nginx owns both paths.
const (
publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/"
)
// NewUploads picks the stores. publicDir and privateDir are directories on the
// shared `uploads` volume (/backend/uploads/ and its private/ subdirectory in
// the container).
//
// With no S3 endpoint the public store is the volume alone, the behaviour
// before Garage. An endpoint with missing credentials is a configuration
// mistake: it is logged and the volume is used rather than failing every
// upload.
func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
disk := DiskFileStore{Dir: publicDir}
u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}}
switch {
case cfg.Endpoint == "":
log.Printf("[upload] S3_ENDPOINT unset; storing uploads on disk in %s", publicDir)
case cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" || cfg.Bucket == "":
log.Printf("[upload] S3_ENDPOINT is set but S3_BUCKET or the S3 key is missing; storing uploads on disk in %s", publicDir)
default:
log.Printf("[upload] storing uploads in bucket %s at %s (disk fallback: %s)", cfg.Bucket, cfg.Endpoint, publicDir)
u.public = FallbackFileStore{Primary: NewS3FileStore(cfg), Fallback: disk}
}
return u
}
// Save validates and stores one uploaded file and returns its URL
// (/uploads/<name>, or /uploads/private/<name>). Authorisation is the
// caller's job: only an admin may save a private file.
func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) {
if fh.Size > MaxUploadSize {
return "", ErrUploadTooLarge
}
ext := strings.ToLower(filepath.Ext(fh.Filename))
kind, ok := UploadTypes[ext]
if !ok {
return "", ErrUploadType
}
f, err := fh.Open()
if err != nil {
return "", fmt.Errorf("opening upload: %w", err)
}
defer f.Close()
if kind.SniffPrefix != "" {
// 512 bytes is all http.DetectContentType looks at. A short read is
// fine; sniffing works on a prefix, so only an empty file is an error.
buf := make([]byte, 512)
n, err := io.ReadFull(f, buf)
if n == 0 {
return "", ErrUploadUnreadable
}
if err != nil && err != io.ErrUnexpectedEOF {
return "", fmt.Errorf("reading upload: %w", err)
}
if !strings.HasPrefix(http.DetectContentType(buf[:n]), kind.SniffPrefix) {
return "", ErrUploadContent
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewinding upload: %w", err)
}
}
// The uploaded name is thrown away for 16 random bytes. That rules out
// path traversal and collisions in one go, and makes the URL unguessable.
// Only the extension survives, and it is on the allow-list.
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generating filename: %w", err)
}
name := hex.EncodeToString(b) + ext
store, prefix := u.public, publicURLPrefix
if private {
store, prefix = u.private, privateURLPrefix
}
if err := store.Put(ctx, name, kind.ContentType, f, fh.Size); err != nil {
return "", err
}
return prefix + name, nil
}
// ---- Stores ----------------------------------------------------------------
// FileStore stores one file under key. 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.
type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
}
// DiskFileStore writes files into Dir, creating it if needed.
type DiskFileStore struct{ Dir string }
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
// 0755 and 0644 so nginx, a different user, can reach and read the files.
if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err
}
out, err := os.OpenFile(filepath.Join(d.Dir, key), os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
if _, err := io.Copy(out, r); err != nil {
out.Close()
return err
}
return out.Close()
}
// 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
}
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
// Fallback instead. The upload still succeeds and its URL still works (nginx
// looks in both places), so a Garage outage costs a log line rather than
// broken uploads.
type FallbackFileStore struct {
Primary FileStore
Fallback FileStore
}
func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error {
err := f.Primary.Put(ctx, key, contentType, r, size)
if err == nil {
return nil
}
log.Printf("[upload] primary store failed, writing %s to fallback: %v", key, err)
if _, seekErr := r.Seek(0, io.SeekStart); seekErr != nil {
return fmt.Errorf("rewinding for fallback after %v: %w", err, seekErr)
}
return f.Fallback.Put(ctx, key, contentType, r, size)
}
+211
View File
@@ -0,0 +1,211 @@
package services
import (
"bytes"
"context"
"errors"
"image"
"image/png"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// 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 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 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))
}
}
+42 -7
View File
@@ -12,8 +12,24 @@
# profile, so `docker compose -f docker-compose.yml -f docker-compose.dev.yml
# up` never starts it and dev uses nginx's self-signed localhost cert instead.
#
# HOW VALIDATION WORKS (--webroot)
# Let's Encrypt HTTP-01: certbot writes a challenge token into
# HOW VALIDATION WORKS: DNS-01 (--dns-cloudflare) when CLOUDFLARE_DNS_API_TOKEN
# is set, otherwise HTTP-01 (--webroot)
# DNS-01: certbot creates a _acme-challenge TXT record through the Cloudflare
# API, Let's Encrypt looks it up, and certbot deletes it. Nothing has to
# reach the Pi, which is the point: with the site behind the Cloudflare
# tunnel, ports 80 and 443 need not be forwarded at all. The token needs
# Zone -> DNS -> Edit on this zone only. certbot insists its credentials
# arrive as a mode-600 ini file, not an environment variable, so the script
# writes one to /tmp on every start; nothing is stored on disk outside the
# container.
#
# Switching method on an existing certificate: certbot records the method
# in renewal/<DOMAIN>.conf and `renew` would keep using webroot. Flags on
# the command line override the stored ones, and the next successful
# renewal saves them, so the method flags are passed to BOTH commands below.
# An unset token after a switch therefore puts it back on webroot, too.
#
# HTTP-01, the fallback: certbot writes a challenge token into certbot writes a challenge token into
# /var/www/certbot/.well-known/acme-challenge/ and Let's Encrypt fetches it
# over plain HTTP on port 80. certbot itself listens on nothing — nginx is
# the server that answers. /var/www/certbot is the ./certbot/www bind mount,
@@ -47,12 +63,14 @@
# root-equivalent on the host, and the shared cert directory is a capability
# both containers already have.
#
# ENV VARS REQUIRED (from ./.env via `env_file`)
# ENV VARS (from ./.env via `env_file`)
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
# filed under --cert-name $DOMAIN so the path nginx expects
# (/etc/letsencrypt/live/$DOMAIN/) is stable regardless of which
# name certbot would otherwise have chosen.
# EMAIL registration/expiry-notice address for the ACME account.
# CLOUDFLARE_DNS_API_TOKEN
# optional; selects DNS-01. See HOW VALIDATION WORKS.
#
# FLAGS WORTH KNOWING
# --agree-tos --non-interactive never prompt; required in a container.
@@ -61,9 +79,10 @@
# rather than erroring out.
#
# ASSUMES EXISTS
# /var/www/certbot (shared ACME webroot, served by nginx on port 80)
# /etc/letsencrypt (persistent cert store, shared with nginx)
# Port 80 reachable from the public internet for $DOMAIN and www.$DOMAIN.
# Webroot method only: /var/www/certbot (shared ACME webroot, served by
# nginx on port 80) and port 80 reachable from the public internet for
# $DOMAIN and www.$DOMAIN.
# =============================================================================
# The reload sentinel: a file in the SHARED /etc/letsencrypt mount that nginx's
@@ -71,7 +90,23 @@
# — see RELOAD SIGNAL above.
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
certbot certonly --webroot -w /var/www/certbot \
if [ -n "${CLOUDFLARE_DNS_API_TOKEN}" ]; then
CREDENTIALS=/tmp/cloudflare.ini
# umask rather than a chmod afterwards, so the token is never readable
# by anyone else even for an instant.
(umask 077 && printf 'dns_cloudflare_api_token = %s\n' "${CLOUDFLARE_DNS_API_TOKEN}" >"${CREDENTIALS}")
# 30s rather than the plugin's 10: Let's Encrypt queries from several
# vantage points, and a lookup that lands before Cloudflare has the record
# everywhere fails the whole order.
set -- --dns-cloudflare --dns-cloudflare-credentials "${CREDENTIALS}" \
--dns-cloudflare-propagation-seconds 30
echo "Validating over DNS (Cloudflare API)."
else
set -- --webroot -w /var/www/certbot
echo "Validating over HTTP (webroot); needs port 80 reachable."
fi
certbot certonly "$@" \
--email "${EMAIL}" \
-d "${DOMAIN}" -d "www.${DOMAIN}" \
--cert-name "${DOMAIN}" \
@@ -82,7 +117,7 @@ certbot certonly --webroot -w /var/www/certbot \
trap exit TERM;
while :; do
certbot renew --webroot -w /var/www/certbot \
certbot renew "$@" \
--deploy-hook "touch ${RELOAD_SENTINEL}";
sleep 12h;
done
+12 -7
View File
@@ -16,6 +16,7 @@
# nginx_dev.conf.template and self-sign a localhost certificate.
# - python : uvicorn --reload with the app source bind-mounted.
# - certbot : disabled entirely.
# - cloudflared : disabled entirely.
#
# HOW TO REACH IT
# http://localhost (HTTPS also works on :443 with the self-signed cert, which
@@ -31,14 +32,12 @@ services:
command: ["npm", "run", "dev"]
volumes:
- ./vue:/app
# The two bare paths are ANONYMOUS-VOLUME MASKS, not typos. Binding
# ./vue over /app would otherwise hide the node_modules and WASM
# output that were installed/built *inside* the image. Declaring
# them as anonymous volumes re-exposes the image's copies on top of
# the bind mount, so `npm ci` and wasm-pack results survive and the
# host does not need node_modules or a Rust toolchain at all.
# The bare path is an ANONYMOUS-VOLUME MASK, not a typo. Binding
# ./vue over /app would otherwise hide the node_modules that were
# installed *inside* the image. Declaring it as an anonymous volume
# re-exposes the image's copy on top of the bind mount, so the
# `npm ci` result survives and the host does not need node_modules.
- /app/node_modules
- /app/src/wasm
environment:
- NODE_ENV=development
backend:
@@ -93,3 +92,9 @@ services:
# Let's Encrypt could not validate localhost anyway.
profiles:
- disabled
cloudflared:
# Same profile trick as certbot. A dev stack must never join the
# production tunnel: Cloudflare would load-balance real visitors onto
# this machine's seeded database.
profiles:
- disabled
+291 -16
View File
@@ -13,8 +13,8 @@
#
# ENV VARS
# Everything interpolated as ${VAR} below is read by the docker compose CLI
# from ./.env at the repo root (which is gitignored — see sync-secrets.sh for
# how it is distributed to the Pi). Note the two distinct mechanisms:
# from ./.env at the repo root (gitignored, and edited by hand on the host).
# Note the two distinct mechanisms:
# - ${VAR} in this file -> substituted by compose when parsing
# - `env_file: ./.env` -> the whole file injected into the container
# Many services need both: the container name comes from substitution, the
@@ -37,7 +37,8 @@
# Only nginx (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor
# port. Everything else is reachable only from inside app-network, which is
# why the backend, db, silverbullet and python have no `ports:` — they are
# deliberately not exposed and are reached through nginx.
# deliberately not exposed and are reached through nginx. Web traffic can
# also arrive through the `cloudflared` tunnel, which publishes nothing.
# =============================================================================
networks:
@@ -64,8 +65,17 @@ volumes:
dbdata:
# File upload — PERSISTENT. Written by the backend at /backend/uploads,
# served read-only by nginx at /uploads/. Shared so nginx can serve user
# uploads without proxying through the Go process.
# uploads without proxying through the Go process. Since Garage, it holds
# private attachments (always), the uploads from before the bucket, and any
# upload the backend wrote here because Garage refused it. nginx serves
# /uploads/ from the bucket first and only then from here.
uploads:
# Garage object store — PERSISTENT, both. garage_meta is the metadata DB
# (buckets, keys, the object index, the cluster layout); garage_data is the
# object bytes. Lose meta and the bytes in data are unreadable, so back up
# the two together. A fresh pair needs garage/bootstrap.sh run once.
garage_meta:
garage_data:
# Vue build — EPHEMERAL in spirit but a named volume for handoff: the
# one-shot `vue` container writes the built SPA here and exits; nginx mounts
# it at /etc/nginx/html and serves it. Repopulated on every rebuild.
@@ -115,8 +125,20 @@ services:
- silverbullet-public
- python
- jobs
- activity-tracker
- dozzle
networks:
- app-network
app-network:
# The site's public names, resolving to this container for everything
# on app-network. They exist for cloudflared: its tunnel origin is
# https://www.DOMAIN, which lands here over the bridge with a name the
# Let's Encrypt certificate actually covers, so the tunnel verifies
# TLS with no extra dashboard settings (`https://nginx` would fail the
# name check). Any other container that calls the public site now
# reaches nginx directly instead of hairpinning through the internet.
aliases:
- ${DOMAIN}
- www.${DOMAIN}
ports:
- 80:80
- 443:443
@@ -130,14 +152,36 @@ services:
- uploads:/uploads
# The SPA written by the one-shot `vue` container.
- vue_dist:/etc/nginx/html
# The JSON request-body log (nginx/payload_log.conf), kept on the host so
# it survives rebuilds and the `traffic` container can tail it. Grows
# without bound unless rotated — see DEPLOYMENT.md.
- ./logs/nginx:/var/log/nginx/payloads
# restart: always only acts when nginx's master exits. On 2026-10-19 the
# worker stalled while the master lived, and the site was down 4.6 hours
# with the container "Up". /nginx-health is answered by a worker, so a
# stall shows here; Docker only marks it unhealthy, and the `autoheal`
# label is what gets it restarted (see the autoheal service). Plain HTTP
# on :80 so it also passes in the first-boot setup config, which has no
# :443; the workers that serve :80 are the ones serving TLS.
healthcheck:
test: ["CMD", "curl", "-fsS", "--max-time", "5", "-o", "/dev/null", "http://127.0.0.1/nginx-health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
labels:
- autoheal=true
# Obtains the cert once, then renews every 12h forever. Disabled in dev via
# the `disabled` profile in docker-compose.dev.yml. Note this is the stock
# certbot image with our script bind-mounted over the entrypoint, so editing
# certbot/entrypoint.sh takes effect on restart with no rebuild. Version is
# pinned so a certbot release cannot change behaviour under us on redeploy.
# The dns-cloudflare variant is plain certbot plus the Cloudflare DNS plugin:
# with CLOUDFLARE_DNS_API_TOKEN set it validates over DNS, so renewal needs
# no inbound port, and without it falls back to the webroot method.
certbot:
image: certbot/certbot:v3.1.0
image: certbot/dns-cloudflare:v3.1.0
container_name: certbot
volumes:
- ./certbot/entrypoint.sh:/entrypoint.sh
@@ -149,6 +193,37 @@ services:
networks:
- app-network
# Cloudflare Tunnel: an OUTBOUND connection from here to Cloudflare's edge,
# which then forwards visitors' requests back down it to nginx. Nothing is
# published to the host, so with the tunnel live the router's 80/443
# forwards can be closed. The tunnel is "remotely managed": its public
# hostnames and origin settings live in the Cloudflare dashboard, and this
# container only needs the token. The routing set up there (DEPLOYMENT.md,
# "Cloudflare Tunnel") is https://www.DOMAIN, which nginx's network aliases
# resolve to nginx itself, so the certificate verifies; nginx's config,
# redirects and security headers apply to tunnel traffic exactly as to
# direct traffic, and both paths work side by side.
#
# Fixed address so nginx can trust the CF-Connecting-IP header from this
# container and no other (set_real_ip_from in nginx.conf.template). It sits
# at the top of the /16 because docker hands out dynamic addresses from the
# bottom; the two must change together.
#
# Disabled in dev via the `disabled` profile in docker-compose.dev.yml.
cloudflared:
image: cloudflare/cloudflared:2026.9.3
container_name: cloudflared
restart: always
command: ["tunnel", "--no-autoupdate", "run"]
# Explicit, not env_file: the container only ever needs the token.
environment:
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
depends_on:
- nginx
networks:
app-network:
ipv4_address: 172.28.255.250
backend:
build:
context: ./backend
@@ -177,10 +252,6 @@ services:
# rebuild, forcing a manual re-authorisation of Spotify after each
# deploy. Gitignored (it is a credential).
- ./backend/token/:/backend/token
# Hand-off directory for the admin panel's Environment tab: the backend
# queues a change here and env-apply/apply.py on the host applies it.
# The backend gets this instead of .env itself or the Docker socket.
- ./env-apply/run:/backend/env-apply
# The Obsidian vault on the host, read by the backend for the notes API.
# Same directory is mounted read-write into silverbullet (the editor) and
# read-only into silverbullet-public (the /notes/ site).
@@ -246,7 +317,8 @@ services:
#
# This is the only non-nginx service that publishes a host port, and it has
# to: LIQUIDSOAP_HARBOR_PORT is the live-DJ input. A broadcasting client
# (e.g. butt) connects straight to the Pi on that port with the icecast
# (e.g. butt) connects straight to the Pi on that port, by its Tailscale
# name now that the public domain resolves to Cloudflare, with the icecast
# source password and pre-empts the fallback playlist. It is NOT proxied
# through nginx because it is a raw source protocol, not HTTP the SPA uses.
# Note the host:container mapping uses the same variable on both sides, so
@@ -431,12 +503,14 @@ services:
#
# Like python, it gets an explicit `environment:` list rather than the whole
# .env: it never sees the site's database password or JWT secret, and has a
# database role of its own. backend/services/env_manager_test.go checks the
# list against env_registry.json.
# database role of its own. A variable the tracker reads must be added to
# the list below as well as .env.example.
#
# It has no login. AUTH_VALIDATE_URL is the backend's validate-admin route
# (the one nginx's auth_request uses), which the tracker asks with the
# visitor's cookies on each admin request.
# It has no login. nginx's auth_request gates /jobs/ like /sb/ (except the
# bearer-token capture API and the userscript), and the tracker checks
# again itself: AUTH_VALIDATE_URL is the backend's validate-admin route
# (the one nginx's auth_request uses), which it asks with the visitor's
# cookies on each admin request.
#
# ./jobs-data holds the Microsoft Graph session and the capture token. The
# image runs as uid 1000, so the directory must be owned by it.
@@ -473,6 +547,197 @@ 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) back with USACO_GIT_TOKEN. ./usaco-data holds only
# that clone, so deleting it is safe; the image runs as uid 1000, so the
# directory must be owned by it.
#
# 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
depends_on:
- gitea
networks:
- app-network
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
volumes:
- ./usaco-data:/data
# The activity tracker (time spent per app, site, walk...), served at
# /tracker/ with the prefix stripped. Built and published by its own repo
# (adamf/ccp on this Gitea), whose CI pulls :latest into this service on
# every push to main; pin ACTIVITY_TRACKER_IMAGE_TAG to hold a version.
#
# Same shape as jobs: an explicit `environment:` list and a database role of
# its own, created by hand once (the ccp README has the command). It applies
# its own migrations on start. No state outside Postgres.
#
# Two kinds of auth. Collectors send per-device bearer keys, made on the
# tracker's /tracker/setup page or with `docker exec activity-tracker
# tracker apikey create`. The dashboard and setup pages have no login of
# their own: nginx's auth_request gates them like /sb/ (everything but
# /tracker/api/v1/ and the userscript), and like jobs the tracker also asks
# AUTH_VALIDATE_URL (the backend's validate-admin) with the visitor's
# cookies and sends anyone else to /admin/login.
activity-tracker:
image: adam-french.co.uk/adamf/activity-tracker:${ACTIVITY_TRACKER_IMAGE_TAG:-latest}
container_name: activity-tracker
restart: always
depends_on:
db:
condition: service_healthy
networks:
- app-network
environment:
- DATABASE_URL=postgres://${POSTGRES_TRACKER_USER:-tracker}:${POSTGRES_TRACKER_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_TRACKER_DB:-tracker}?sslmode=disable
- TRACKER_TZ=${TRACKER_TZ:-}
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
# Echoes nginx's JSON request-body log to its own stdout, and does nothing
# else. It exists so Dozzle shows the payloads as a stream of their own,
# rendered as JSON fields, instead of interleaved with nginx's compact access
# log and error output. -F re-opens the file after rotation; -n0 skips the
# backlog on restart, which stays in the file on the host.
traffic:
image: busybox:1.37.0
container_name: traffic
restart: always
command: ["tail", "-n0", "-F", "/logs/payloads.log"]
network_mode: none
volumes:
- ./logs/nginx:/logs:ro
# Dozzle: a live, searchable web view of every container's logs, served at
# /dozzle/ behind the admin login (nginx/nginx_routes.conf.template). The
# `traffic` container is the one to watch for incoming request bodies.
#
# The Docker socket is mounted :ro, but that only stops the file being
# replaced — the API behind it is still fully usable, which is effectively
# root on the Pi. Hence: no published port, the admin auth_request in front,
# and container actions and shell left at their default of off.
dozzle:
image: amir20/dozzle:v11.2.0
container_name: dozzle
restart: always
networks:
- app-network
environment:
- DOZZLE_BASE=/dozzle
- DOZZLE_NO_ANALYTICS=true
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
# Restarts any container labelled autoheal=true once Docker marks it
# unhealthy, which Docker itself never does (restart policies only see the
# process exit). Only nginx carries the label today; give it to another
# service with a healthcheck to cover that one too. It polls every 5s.
#
# It needs the Docker socket read-write to restart things, which is root on
# the host, so it gets no network at all: nothing can reach it, and it
# reaches nothing but the socket. For the same reason the image is pinned BY
# DIGEST, never a tag, so a push to Docker Hub cannot gain root here at the
# next pull. The digest is the multi-arch index of 1.2.0, the newest tagged
# release; it calls the API unversioned, so it keeps working as the engine's
# minimum API version moves. To bump: `docker buildx imagetools inspect
# willfarrell/autoheal:<tag>` and paste the top-level Digest.
#
# This is the watchdog retired on 2026-10-01 (.deprecated/autoheal), back
# with a label filter instead of `all`, so backend's and python's
# healthchecks stay informational.
autoheal:
image: willfarrell/autoheal@sha256:31f580ef0279eaced5b38d631b08c474d70d8403c1c2fdd6ddcf2e879d5f3f7c
container_name: autoheal
restart: always
network_mode: none
environment:
- AUTOHEAL_CONTAINER_LABEL=autoheal
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# S3-compatible object store holding public uploads (the `uploads` bucket).
# The backend writes to it on :3900 once S3_ENDPOINT is set in .env; nginx
# serves /uploads/ from it anonymously on :3902, falling back to the
# `uploads` volume; garage-webui manages it via :3903. Nothing is published
# to the host. Config is garage/garage.toml (no secrets in it); the two
# secrets come from .env through the explicit list below.
#
# Nothing depends on this container being up. nginx is deliberately NOT
# given it in depends_on: its upstream is a variable, so a missing or
# crash-looping garage only makes bucket-only files 404 (everything on the
# volume is still served), never nginx's boot; and the backend falls back
# to the volume when a write fails.
#
# FIRST RUN: garage/bootstrap.sh (layout, bucket, key, website access).
# The image is FROM scratch — no shell, so no in-container init script and
# a healthcheck that calls the binary itself.
garage:
image: dxflrs/garage:v2.4.1
container_name: garage
restart: always
networks:
- app-network
environment:
- GARAGE_RPC_SECRET=${GARAGE_RPC_SECRET}
- GARAGE_ADMIN_TOKEN=${GARAGE_ADMIN_TOKEN}
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
- garage_meta:/var/lib/garage/meta
- garage_data:/var/lib/garage/data
healthcheck:
test: ["CMD", "/garage", "status"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
# Admin web UI for Garage, served at /garage/ behind the nginx admin gate.
# Manages buckets and keys, and browses/uploads/deletes objects. Its own
# login (AUTH_USER_PASS) is left unset because nginx's auth_request already
# requires the site admin — and it holds the admin token, so never publish
# its port. It reads the s3/web settings from garage.toml; the token comes
# from .env instead, since the file has none.
#
# Files uploaded here land in the PUBLIC bucket and are served at
# /uploads/<path> with none of the backend's checks. Put hand-managed media
# under a prefix (e.g. media/) so it can't collide with the backend's
# random hex names.
garage-webui:
image: khairul169/garage-webui:1.1.0
container_name: garage-webui
restart: always
depends_on:
- garage
networks:
- app-network
environment:
- BASE_PATH=/garage
- API_BASE_URL=http://garage:3903
- API_ADMIN_KEY=${GARAGE_ADMIN_TOKEN}
- S3_ENDPOINT_URL=http://garage:3900
- S3_REGION=garage
# The image has no /tmp, and Go spools any multipart upload over 32MB to
# a temp file there, so without this every large upload fails with
# "open /tmp/multipart-…: no such file or directory".
tmpfs:
- /tmp
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
# main, executed by the act_runner that lives outside docker (gitea-runner/).
@@ -504,6 +769,16 @@ services:
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
# The host's own name, which Gitea prints in SSH clone URLs. It lives in
# .env, not app.ini, so moving to another host is a one-line change;
# environment-to-ini writes it into the live app.ini on every start.
# localhost suits dev.
- GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
- GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
# Webhooks are refused to private addresses by default ("external").
# The usaco site's push hook targets http://usaco:8080 on the Docker
# network, so that one host is allowed by name.
- GITEA__webhook__ALLOWED_HOST_LIST=external,usaco
- USER_UID=1000
- USER_GID=1000
restart: always
-266
View File
@@ -1,266 +0,0 @@
#!/usr/bin/env python3
# =============================================================================
# apply.py — the host half of the admin panel's Environment tab.
#
# WHAT IT DOES
# Takes the change the backend queued in env-apply/run/request.json, merges
# it into ./.env, recreates the containers that read the changed variables,
# and reports the outcome in env-apply/run/status.json for the panel to show.
#
# WHY IT RUNS ON THE HOST
# The backend is the internet-facing process. It is given neither write
# access to .env nor the Docker socket, so the most a hijacked admin session
# can do is ask for a change to a variable this script agrees is editable.
# The list of those is backend/services/env_registry.json, read here from
# the checkout — the same file the backend embeds.
#
# WHEN IT RUNS
# On the Pi, started by the systemd path unit that install.sh sets up, the
# moment request.json appears. By hand anywhere else:
# python3 env-apply/apply.py
# On a dev machine pass the compose files the stack was started with:
# python3 env-apply/apply.py \
# --compose-cmd "docker compose -f docker-compose.yml -f docker-compose.dev.yml"
#
# SAFETY
# - The request is claimed by rename before anything else, so it is consumed
# exactly once and its secrets leave the shared directory even on failure.
# - .env is replaced atomically (temp file + rename) and the previous
# version kept as .env.bak. If compose then rejects the file, the backup
# is put back before anything is recreated.
# - Only the services that read a changed variable are recreated (plus the
# backend, whose own environment is what the panel reports). A plain
# `docker compose up -d` would restart Postgres and nginx for any edit,
# because they load the whole file too; the next deploy catches them up.
# - An flock on run/lock keeps this from overlapping itself or the deploy
# workflow, which takes the same lock.
#
# Standard library only: it has to run on a bare Raspberry Pi OS.
# =============================================================================
import argparse
import datetime
import fcntl
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Values made only of these are written bare; anything else is single-quoted,
# which dotenv reads literally (no $ interpolation, no # comments).
BARE_VALUE = re.compile(r"^[A-Za-z0-9_./:@+,=-]*$")
# How much compose output a failed run reports back to the panel.
OUTPUT_TAIL_LINES = 40
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
def format_line(name, value):
if BARE_VALUE.match(value):
return f"{name}={value}"
return f"{name}='{value}'"
def merge(text, changes):
"""Return .env text with each changed variable's line replaced in place.
Comments, blank lines and ordering are kept. A variable with no line yet
is appended.
"""
remaining = dict(changes)
out = []
for line in text.splitlines():
match = re.match(r"^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=", line)
if match and match.group(2) in changes:
name = match.group(2)
out.append((match.group(1) or "") + format_line(name, changes[name]))
remaining.pop(name, None)
else:
out.append(line)
if remaining:
if out and out[-1].strip():
out.append("")
out.append("# Added from the admin panel")
for name in sorted(remaining):
out.append(format_line(name, remaining[name]))
return "\n".join(out) + "\n"
def write_atomically(path, text):
"""Replace path, keeping its mode and owner."""
stat = os.stat(path)
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".env.tmp.")
try:
with os.fdopen(fd, "w") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, stat.st_mode & 0o7777)
try:
os.chown(tmp, stat.st_uid, stat.st_gid)
except PermissionError:
pass # not root and not the owner; the rename below still works
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
def load_registry(path):
with open(path) as handle:
return {entry["name"]: entry for entry in json.load(handle)}
def check(changes, registry):
"""Refuse anything the backend should never have asked for."""
if not isinstance(changes, dict) or not changes:
raise ValueError("the request changes nothing")
for name, value in changes.items():
entry = registry.get(name)
if entry is None or not entry.get("editable"):
raise ValueError(f"{name} is not editable")
if not isinstance(value, str):
raise ValueError(f"{name} is not a string")
if "'" in value or any(ord(c) < 0x20 or ord(c) == 0x7F for c in value):
raise ValueError(f"{name} holds a character .env cannot carry")
def services_for(names, registry):
services = {"backend"}
for name in names:
services.update(registry[name].get("services", []))
return sorted(services)
def run(cmd, cwd):
result = subprocess.run(
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
)
return result.returncode, result.stdout
def tail(text):
return "\n".join(text.strip().splitlines()[-OUTPUT_TAIL_LINES:])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--env-file", default=os.path.join(ROOT, ".env"))
parser.add_argument("--run-dir", default=os.path.join(ROOT, "env-apply", "run"))
parser.add_argument(
"--registry",
default=os.path.join(ROOT, "backend", "services", "env_registry.json"),
)
parser.add_argument(
"--compose-cmd",
default="docker compose",
help="compose invocation, e.g. to add -f files for a dev stack",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="report what would change and leave everything untouched",
)
args = parser.parse_args()
compose = shlex.split(args.compose_cmd)
compose_dir = os.path.dirname(os.path.abspath(args.env_file))
request_path = os.path.join(args.run_dir, "request.json")
claimed_path = os.path.join(args.run_dir, "request.claimed")
status_path = os.path.join(args.run_dir, "status.json")
backup_path = args.env_file + ".bak"
def report(state, request_id, **extra):
body = {"state": state, "id": request_id, "at": now(), **extra}
tmp = status_path + ".tmp"
with open(tmp, "w") as handle:
json.dump(body, handle)
os.chmod(tmp, 0o644)
os.replace(tmp, status_path)
if args.dry_run:
if not os.path.exists(request_path):
print("No request pending.")
return 0
with open(request_path) as handle:
request = json.load(handle)
registry = load_registry(args.registry)
check(request.get("set"), registry)
names = sorted(request["set"])
print("Would set:", ", ".join(names))
print("Would recreate:", ", ".join(services_for(names, registry)))
return 0
with open(os.path.join(args.run_dir, "lock"), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
# Claim first: after this rename the request cannot be applied twice,
# and a crash below leaves no secrets where the backend can read them.
try:
os.replace(request_path, claimed_path)
except FileNotFoundError:
print("No request pending.")
return 0
try:
with open(claimed_path) as handle:
request = json.load(handle)
finally:
os.unlink(claimed_path)
request_id = str(request.get("id", ""))
try:
registry = load_registry(args.registry)
changes = request.get("set")
check(changes, registry)
names = sorted(changes)
services = services_for(names, registry)
report("applying", request_id, changed=names, services=services)
with open(args.env_file) as handle:
before = handle.read()
shutil.copy2(args.env_file, backup_path)
os.chmod(backup_path, 0o600)
write_atomically(args.env_file, merge(before, changes))
# Catch a file compose cannot parse before any container is
# stopped for it.
code, output = run(compose + ["config", "-q"], compose_dir)
if code != 0:
write_atomically(args.env_file, before)
raise RuntimeError(
"compose rejected the new .env; it was restored.\n" + tail(output)
)
code, output = run(
compose + ["up", "-d", "--no-deps", "--force-recreate"] + services,
compose_dir,
)
if code != 0:
# .env keeps the new values: they are valid, and the usual
# cause here is a container that would not start, which the
# old values would not fix.
raise RuntimeError(
".env was updated but recreating the containers failed.\n"
+ tail(output)
)
except Exception as error: # noqa: BLE001 - everything is reported
report("failed", request_id, output=str(error))
print(f"Failed: {error}", file=sys.stderr)
return 1
report("applied", request_id, changed=names, services=services)
print(f"Applied {', '.join(names)}; recreated {', '.join(services)}.")
return 0
if __name__ == "__main__":
sys.exit(main())
-80
View File
@@ -1,80 +0,0 @@
#!/usr/bin/env bash
# =============================================================================
# install.sh — one-time setup, on the Pi, of the watcher behind the admin
# panel's Environment tab.
#
# WHAT IT DOES
# Installs two systemd units:
# web-server-env-apply.path watches env-apply/run/request.json
# web-server-env-apply.service runs apply.py when that file appears
# The units are generated here rather than committed because they need this
# checkout's absolute path and the user that owns it.
#
# HOW TO RUN
# From the deploy checkout, as the user that runs docker compose there:
# ./env-apply/install.sh
# It calls sudo for the three steps that need root. Re-running is safe and
# is how to pick up a change to the units below.
#
# WHY A PATH UNIT
# PathExists fires as soon as the backend writes the request, and also at
# boot if a request was queued while the Pi was down. apply.py renames the
# request away before doing anything else, so the unit cannot retrigger on
# the same file.
#
# The service runs as the checkout's owner, not root: it needs exactly what
# the deploy workflow has (write .env, run docker compose) and no more.
# DOCKER_API_VERSION and COMPOSE_BAKE mirror .gitea/workflows/deploy.yaml.
# =============================================================================
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUN_USER="$(id -un)"
RUN_DIR="${ROOT}/env-apply/run"
if [ "$RUN_USER" = "root" ]; then
echo "Run this as the user that owns the checkout, not root." >&2
exit 1
fi
if ! command -v python3 >/dev/null; then
echo "python3 is required." >&2
exit 1
fi
# The backend bind-mounts this directory. If Docker creates it first it is
# root-owned and apply.py cannot write its status there.
mkdir -p "$RUN_DIR"
if [ "$(stat -c %U "$RUN_DIR")" != "$RUN_USER" ]; then
sudo chown "$RUN_USER" "$RUN_DIR"
fi
sudo tee /etc/systemd/system/web-server-env-apply.path >/dev/null <<EOF
[Unit]
Description=Watch for .env changes queued from the admin panel
[Path]
PathExists=${RUN_DIR}/request.json
[Install]
WantedBy=multi-user.target
EOF
sudo tee /etc/systemd/system/web-server-env-apply.service >/dev/null <<EOF
[Unit]
Description=Apply a .env change queued from the admin panel
After=docker.service
[Service]
Type=oneshot
User=${RUN_USER}
WorkingDirectory=${ROOT}
Environment=DOCKER_API_VERSION=1.41
Environment=COMPOSE_BAKE=false
ExecStart=/usr/bin/env python3 ${ROOT}/env-apply/apply.py
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now web-server-env-apply.path
echo "Installed. Watching ${RUN_DIR}/request.json as ${RUN_USER}."
echo "Logs: journalctl -u web-server-env-apply.service"
View File
+109
View File
@@ -0,0 +1,109 @@
#!/bin/sh
# =============================================================================
# One-time setup of the `garage` container. Run from the repo root, on the
# host, once the container is up:
#
# garage/bootstrap.sh
#
# Idempotent: every step checks before acting, so re-running it is harmless.
# Garage keeps all of this in the garage_meta volume, so it is only needed on
# a fresh volume — once on stpvm, and again whenever a dev stack starts from
# nothing.
#
# WHY A HOST SCRIPT
# The dxflrs/garage image is FROM scratch: a single binary, no shell. There
# is nothing to run an init script with inside it, so this drives the
# binary through `docker compose exec`.
#
# WHAT IT DOES
# 1. Gives the single node a role in the cluster layout. Until it has one,
# Garage accepts connections but refuses to store anything.
# 2. Creates the bucket (S3_BUCKET, default `uploads`).
# 3. Imports the backend's access key from .env (S3_ACCESS_KEY_ID /
# S3_SECRET_ACCESS_KEY). Importing rather than letting Garage generate
# one keeps .env the single source of truth: a wiped volume comes back
# with the same credentials and the backend needs no change.
# 4. Grants that key read+write on the bucket. garage-webui also browses
# with it: it borrows the first key that has access to a bucket.
# 5. Opens the bucket on the website endpoint, which is what nginx serves
# /uploads/ from, anonymously.
#
# ENV / .env
# S3_ACCESS_KEY_ID required; "GK" + 24 hex chars
# S3_SECRET_ACCESS_KEY required; 64 hex chars
# S3_BUCKET optional, default uploads
# GARAGE_CAPACITY optional, default 20G. Only weights data placement
# between nodes; with one node it is no quota.
# COMPOSE optional, default `docker compose`. Set it to add
# the dev override, e.g.
# COMPOSE="docker compose -f docker-compose.yml -f docker-compose.dev.yml"
# =============================================================================
set -eu
COMPOSE=${COMPOSE:-docker compose}
# Read one KEY=value from .env without sourcing it: .env is not guaranteed to
# be valid shell (unquoted spaces, `$` in secrets). A value already in the
# environment wins, so the script also runs without a .env.
envval() {
eval "current=\${$1:-}"
if [ -n "$current" ]; then
printf '%s' "$current"
return
fi
[ -f .env ] || return 0
grep -E "^$1=" .env | tail -n 1 | cut -d= -f2- | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'$/\1/"
}
garage() {
$COMPOSE exec -T garage /garage "$@"
}
KEY_ID=$(envval S3_ACCESS_KEY_ID)
SECRET=$(envval S3_SECRET_ACCESS_KEY)
BUCKET=$(envval S3_BUCKET)
BUCKET=${BUCKET:-uploads}
CAPACITY=$(envval GARAGE_CAPACITY)
CAPACITY=${CAPACITY:-20G}
KEY_NAME=site-backend
# Garage rejects other shapes at import time with a less helpful message.
if ! printf '%s' "$KEY_ID" | grep -Eq '^GK[0-9a-f]{24}$'; then
echo "S3_ACCESS_KEY_ID must be GK followed by 24 hex chars (try: echo GK\$(openssl rand -hex 12))" >&2
exit 1
fi
if ! printf '%s' "$SECRET" | grep -Eq '^[0-9a-f]{64}$'; then
echo "S3_SECRET_ACCESS_KEY must be 64 hex chars (try: openssl rand -hex 32)" >&2
exit 1
fi
# 1. Layout. `node id -q` prints "<full id>@<addr>"; the id is what
# `layout assign` takes.
if garage layout show 2>/dev/null | grep -q "No nodes currently have a role"; then
NODE_ID=$(garage node id -q 2>/dev/null | cut -d@ -f1)
echo "Assigning node $(printf '%s' "$NODE_ID" | cut -c1-16) (capacity $CAPACITY)"
garage layout assign -z dc1 -c "$CAPACITY" "$NODE_ID"
garage layout apply --version 1
else
echo "Layout already applied"
fi
# 2. Bucket.
if garage bucket info "$BUCKET" >/dev/null 2>&1; then
echo "Bucket $BUCKET exists"
else
garage bucket create "$BUCKET"
fi
# 3. Key.
if garage key info "$KEY_ID" >/dev/null 2>&1; then
echo "Key $KEY_ID exists"
else
garage key import -n "$KEY_NAME" --yes "$KEY_ID" "$SECRET"
fi
# 4 and 5 are idempotent in Garage itself.
garage bucket allow --read --write "$BUCKET" --key "$KEY_ID"
garage bucket website --allow "$BUCKET"
echo "Garage ready: bucket $BUCKET, key $KEY_ID"
+51
View File
@@ -0,0 +1,51 @@
# =============================================================================
# Garage — the S3-compatible object store behind /uploads/.
#
# One node, one copy of everything (replication_factor = 1): this is storage
# on the same disk as the rest of the site, not a resilience layer, so the
# garage_meta and garage_data volumes still need backing up like the others.
#
# NO SECRETS IN THIS FILE. It is committed and mounted read-only into both
# `garage` and `garage-webui`. rpc_secret and admin_token come from the
# GARAGE_RPC_SECRET and GARAGE_ADMIN_TOKEN environment variables, which Garage
# reads in place of the config keys.
#
# Binds are 0.0.0.0 rather than Garage's usual [::]: containers on a bridge
# network without IPv6 may refuse an IPv6 bind. None of these ports is
# published to the host; everything reaches them over app-network.
#
# PORTS
# 3900 S3 API. The backend writes uploads here (signed with the key that
# garage/bootstrap.sh imports); garage-webui browses through it.
# 3901 RPC between Garage nodes. Only this node talks to itself.
# 3902 Website endpoint. Serves a bucket ANONYMOUSLY, choosing it from the
# Host header: "<bucket><root_domain>", so nginx's /uploads/ location
# sends `Host: uploads.web.garage`. Only buckets that bootstrap.sh
# opened with `garage bucket website --allow` are served.
# 3903 Admin API, used by garage-webui and authenticated by admin_token.
# =============================================================================
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "lmdb"
# LMDB can be left unreadable by a crash mid-write; a periodic snapshot of
# the metadata is what `garage meta` restores from.
metadata_auto_snapshot_interval = "6h"
replication_factor = 1
rpc_bind_addr = "0.0.0.0:3901"
rpc_public_addr = "127.0.0.1:3901"
[s3_api]
api_bind_addr = "0.0.0.0:3900"
# Any string works; it only has to match what clients sign with (S3_REGION).
s3_region = "garage"
root_domain = ".s3.garage"
[s3_web]
bind_addr = "0.0.0.0:3902"
root_domain = ".web.garage"
index = "index.html"
[admin]
api_bind_addr = "0.0.0.0:3903"
+3 -3
View File
@@ -20,7 +20,9 @@
; 22 and cannot use the host's sshd, so Gitea runs its own Go SSH server.
; 2222 is published in docker-compose.yml; the deploy workflow clones over
; ssh://git@localhost:2222.
; SSH_DOMAIN is the Pi's Tailscale MagicDNS name, not the public domain: SSH
; SSH_DOMAIN and DOMAIN are not set here: they come from GITEA_SSH_DOMAIN in
; ./.env (see docker-compose.yml). The value is the host's Tailscale
; MagicDNS name, not the public domain: SSH
; (22 and 2222) is not forwarded by the router, so the SSH clone URL Gitea
; shows only works from a device on the tailnet. HTTPS clones go through
; nginx at ROOT_URL and stay public.
@@ -50,7 +52,6 @@ TEMP_PATH = /tmp/gitea/uploads
[server]
APP_DATA_PATH = /var/lib/gitea
SSH_DOMAIN = stppi.tailf20278.ts.net
HTTP_PORT = 3000
ROOT_URL = https://adam-french.co.uk/gitea/
DISABLE_SSH = false
@@ -60,7 +61,6 @@ SSH_PORT = 2222
SSH_LISTEN_PORT = 2222
BUILTIN_SSH_SERVER_USER = git
LFS_START_SERVER = true
DOMAIN = stppi.local
LFS_JWT_SECRET =
OFFLINE_MODE = true
+7 -1
View File
@@ -1,6 +1,6 @@
# =============================================================================
# nginx image — the public edge. Stock nginx plus two tools, three config
# templates and the two partials they include.
# templates, the two partials they include and two static includes.
#
# BASE: nginx:1.27, pinned to a minor version. Official nginx images are
# multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi
@@ -44,5 +44,11 @@ COPY nginx_routes.conf.template /etc/nginx/nginx_routes.conf.template
# Static security-header include, referenced from nginx.conf.template (and
# any location that sets its own add_header). Not templated — no envsubst.
COPY security_headers.conf /etc/nginx/security_headers.conf
# Static http-level include for the JSON request-body log (both configs). Not
# templated: its $request_body etc. are nginx variables, not env vars.
COPY payload_log.conf /etc/nginx/payload_log.conf
# The payload log's directory. Normally a bind mount (./logs/nginx); created
# here so nginx still starts when run without it.
RUN mkdir -p /var/log/nginx/payloads
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+93 -14
View File
@@ -36,6 +36,15 @@
# (which carry the security headers), the `graphql` rate-limit zone and its
# location, and the limit_req_zone declarations the shared routes refer to.
# =============================================================================
# One worker per CPU. Unset, nginx runs a single worker, and on 2026-10-19 that
# one worker stalled for 4.6 hours: the master kept the container "Up" and the
# tunnel stayed connected, but every request timed out in the TLS handshake.
# With several workers a stuck one only loses the connections it holds; the
# others keep accepting. The healthcheck in docker-compose.yml (and autoheal
# restarting on it) covers the case where they all stall.
worker_processes auto;
events {
worker_connections 1024;
}
@@ -89,18 +98,22 @@ http {
# (Production only; the dev template omits it.
# Its location is at the bottom of this file,
# not in the shared route table.)
# upload 5r/m burst=3 - uploads are 50MB-capable and hit disk; this
# bounds how fast one IP can fill the volume.
# upload 30r/m burst=20 - uploads hit disk; this bounds how fast one IP
# can fill the volume. Generous because only a
# signed-in user can upload and accounts are
# admin-created, and because dropping a batch of
# pictures onto a canvas page uploads them all
# at once — the burst lets ~20 through together.
# hotel_search 3r/m burst=2 - each request holds an upstream call to
# Travelodge/TfL for up to a few minutes and the
# Python side has a single search slot, so this is
# really concurrency protection, not abuse
# protection.
#
# NOTE: the key is the direct client IP. Since nginx is the edge here (no
# CDN or upstream proxy in front), that is correct. If anything is ever put
# in front, these zones must switch to a trusted X-Forwarded-For or every
# visitor will share one bucket.
# NOTE: the key is the client IP, which is only right because of the
# real-IP lines below. Traffic through the Cloudflare tunnel reaches nginx
# from the cloudflared container, so without them every tunnel visitor
# would share that one address and one bucket.
#
# login, api, upload and hotel_search are USED from
# nginx_routes.conf.template, which dev includes too — so
@@ -109,14 +122,34 @@ http {
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=graphql:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=upload:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
# ---- Real client IP behind the Cloudflare tunnel -------------------------
# For connections from the cloudflared container, and only those, replace
# $remote_addr with the visitor's address from Cloudflare's
# CF-Connecting-IP header. Everything downstream then just works: the
# rate-limit keys above, the access log, and the X-Real-IP /
# X-Forwarded-For headers sent upstream.
#
# The trust is pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the whole app-network
# subnet. Direct visitors on the forwarded 80/443 can arrive from the
# bridge gateway, 172.28.0.1, when docker's userland proxy handles the
# connection, so trusting the subnet would let anyone pick their own IP,
# and so their own rate-limit bucket, by sending the header themselves.
# Production only: dev has no tunnel.
set_real_ip_from 172.28.255.250;
real_ip_header CF-Connecting-IP;
log_format compact
'$remote_addr "$request" $status rt=$request_time';
access_log /var/log/nginx/access.log compact;
# JSON request-body log for Dozzle; see payload_log.conf.
include /etc/nginx/payload_log.conf;
# nginx's bundled mime.types has no entry for .mjs, so ES modules would be
# served as application/octet-stream and browsers refuse to execute them.
# This adds the missing mapping without editing the shipped mime.types.
@@ -155,6 +188,15 @@ http {
root /var/www/certbot;
}
# The container healthcheck's target (docker-compose.yml). Answered by
# nginx itself, so it measures whether a worker is serving and nothing
# upstream. Unlogged, or it would put a line in the payload log every
# 30s. Every config's default :80 server has one, setup and dev too.
location = /nginx-health {
access_log off;
return 204;
}
# Redirect everything else to HTTPS
location / {
return 301 https://www.$DOMAIN$request_uri;
@@ -267,14 +309,51 @@ http {
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
# User-uploaded files, served straight off the shared `uploads` volume
# so the Go process never has to stream them. Because these are
# attacker-supplied bytes on our own origin, three headers neutralise
# them: nosniff stops content-type guessing, Content-Disposition inline
# keeps them from being treated as downloads, and the locked-down CSP
# means even an uploaded .html can run no script and load no resource.
# User-uploaded files, served by nginx so the Go process never has to
# stream them. Because these are attacker-supplied bytes on our own
# origin, three headers neutralise them: nosniff stops content-type
# guessing, Content-Disposition inline keeps them from being treated
# as downloads, and the locked-down CSP means even an uploaded .html
# can run no script and load no resource.
#
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the
# Garage bucket's website endpoint, which serves the bucket
# anonymously and picks it by the Host header (garage/garage.toml:
# s3_web); the bucket is reachable only over app-network, so this is
# the only public way in. If Garage has no such file, or is down, the
# request falls through to the shared `uploads` volume
# (@uploads_disk), which holds uploads from before Garage and anything
# the backend wrote there because Garage refused it
# (backend/services/uploads.go). So the bucket is the source of truth
# — deleting a file in garage-webui unpublishes it unless a disk copy
# exists — while a Garage outage only costs files that are nowhere
# else.
# proxy_connect_timeout 2s - Garage is on the same bridge network,
# so a slow connect means it is down; fall back quickly rather
# than after the 60s default.
# proxy_intercept_errors + error_page - Garage's 404 and any 5xx
# (including nginx's own 502 when the garage container doesn't
# exist) become a look at the disk instead.
# Range requests pass through either way, so video seeks.
# @uploads_disk sees the URI after the rewrite (/<name>), hence
# `root /uploads`. The headers are repeated, not inherited: a named
# location is its own location.
location /uploads/ {
alias /uploads/;
rewrite ^/uploads/(.*)$ /$1 break;
proxy_pass $upstream_garage_web;
proxy_set_header Host uploads.web.garage;
proxy_connect_timeout 2s;
proxy_intercept_errors on;
error_page 404 500 502 503 504 = @uploads_disk;
include /etc/nginx/security_headers.conf;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
location @uploads_disk {
root /uploads;
try_files $uri =404;
include /etc/nginx/security_headers.conf;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
+15 -1
View File
@@ -33,6 +33,10 @@
# annotated in nginx_routes.conf.template; the rate-limit reasoning is in
# nginx.conf.template.
# =============================================================================
# As in production; why is in nginx.conf.template.
worker_processes auto;
events {
worker_connections 1024;
}
@@ -54,7 +58,7 @@ http {
# kept equal to production so a limit that would bite there bites here too.
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=upload:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
log_format compact
@@ -62,6 +66,9 @@ http {
access_log /var/log/nginx/access.log compact;
# JSON request-body log for Dozzle; see payload_log.conf.
include /etc/nginx/payload_log.conf;
types {
text/javascript mjs;
}
@@ -86,6 +93,13 @@ http {
listen 80;
server_name $DOMAIN www.$DOMAIN;
# The container healthcheck's target; see nginx.conf.template. Only in
# this block, as in production, where it sits in the :80 server too.
location = /nginx-health {
access_log off;
return 204;
}
include /etc/nginx/nginx_dev_common.conf;
}
+15 -2
View File
@@ -47,14 +47,27 @@
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
# Both /uploads/ blocks are the production ones MINUS
# The /uploads/ blocks (and @uploads_disk) are the production ones MINUS
# `include security_headers.conf`: that file carries HSTS, which must
# never be sent from localhost. That one line is why they are not in
# the shared route table (see WHAT DOES NOT in
# nginx_routes.conf.template). Keep the rest in step with
# nginx.conf.template.
location /uploads/ {
alias /uploads/;
rewrite ^/uploads/(.*)$ /$1 break;
proxy_pass $upstream_garage_web;
proxy_set_header Host uploads.web.garage;
proxy_connect_timeout 2s;
proxy_intercept_errors on;
error_page 404 500 502 503 504 = @uploads_disk;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
}
location @uploads_disk {
root /uploads;
try_files $uri =404;
add_header X-Content-Type-Options nosniff always;
add_header Content-Disposition "inline" always;
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
+193 -8
View File
@@ -77,6 +77,17 @@
# 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;
# ---- Backend API -----------------------------------------------------
# Two patterns repeat through every proxied location below:
@@ -104,7 +115,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 +154,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 +181,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 +270,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 +422,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 +445,99 @@
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;
}
# 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 +552,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 +568,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;
+6
View File
@@ -45,6 +45,12 @@ http {
root /var/www/certbot;
}
# The container healthcheck's target; see nginx.conf.template.
location = /nginx-health {
access_log off;
return 204;
}
# All other requests should return 404
location / {
return 404;
+55
View File
@@ -0,0 +1,55 @@
# =============================================================================
# Payload log: one JSON line per request, body included, for inspecting what
# actually arrives at the edge. Included at http level by BOTH nginx.conf and
# nginx_dev.conf, so it is plain nginx (no envsubst) like security_headers.conf.
#
# WHERE IT GOES
# /var/log/nginx/payloads/ is bind-mounted from ./logs/nginx on the host.
# The `traffic` container tails the file to its stdout so Dozzle (/dozzle/)
# shows it as its own clean stream of JSON. The `compact` access log is
# untouched and still goes to the container's stdout.
#
# WHAT IS NOT CAPTURED
# - Bodies larger than client_body_buffer_size: nginx spools those to a
# temp file and leaves $request_body empty. Uploads therefore log with an
# empty body (their size is still in `len`).
# - Bodies of requests nginx answers itself (redirects, static files): it
# never reads them, so $request_body is empty there too.
# - Responses. nginx cannot log a proxied response body.
# - auth_request subrequests: log_subrequest is off by default.
# =============================================================================
# 64k keeps ordinary JSON/GraphQL bodies in memory (the default is 16k on
# 64-bit), which is the only case where $request_body is filled. It is a
# per-request buffer only allocated when a body arrives, so the cost is small.
client_body_buffer_size 64k;
# Redaction: any body mentioning a password, token or secret is logged as a
# placeholder rather than having the field stripped, because nginx has no JSON
# parser. That catches /auth/login, the GraphQL login and change-password
# mutations and the refresh-token call in one rule. Over-matching (a query that
# merely selects a field named *token*) costs a hidden body, never a leak.
# map is evaluated lazily at log time, after the body has been read.
map $request_body $logged_body {
"~*(password|token|secret)" "[redacted]";
default $request_body;
}
# escape=json makes each line valid JSON (quotes, newlines and control bytes
# in the body are escaped), so Dozzle renders it as fields and `jq` reads it.
log_format payloads escape=json '{'
'"time":"$time_iso8601",'
'"ip":"$remote_addr",'
'"method":"$request_method",'
'"host":"$host",'
'"uri":"$request_uri",'
'"status":"$status",'
'"rt":"$request_time",'
'"ctype":"$content_type",'
'"len":"$content_length",'
'"referer":"$http_referer",'
'"ua":"$http_user_agent",'
'"body":"$logged_body"'
'}';
access_log /var/log/nginx/payloads/payloads.log payloads;
+3 -4
View File
@@ -15,9 +15,8 @@ add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" alway
# locked-down CSP by declaring Content-Security-Policy again themselves
# (a later add_header of the same name within one response wins).
#
# ponytail: no site-wide CSP from nginx here. The SPA needs
# 'wasm-unsafe-eval' for its Rust module, Gitea (proxied at /gitea/) relies
# on inline <script> blocks its own templates generate, so a shared
# ponytail: no site-wide CSP from nginx here. Gitea (proxied at /gitea/)
# relies on inline <script> blocks its own templates generate, so a shared
# script-src would need 'unsafe-inline' — which voids almost all of CSP's
# value. If a real CSP matters again, give the SPA document its own
# script-src 'self' 'wasm-unsafe-eval' location, separate from Gitea.
# script-src 'self' location, separate from Gitea.
+3 -3
View File
@@ -94,9 +94,9 @@ Their plumbing is in two places, shared by any route added later:
outside is a 404 before its body is validated.
Every route uses one model, `MODEL` in `claude.py`: the `CLAUDE_MODEL` variable,
or `claude-sonnet-5-5` when it is blank. It is chosen on the admin panel's
Environment tab from `claude-haiku-4-5`, `claude-sonnet-5-5` and
`claude-opus-5-5`, and saving it there restarts this service. The request is
or `claude-sonnet-5-5` when it is blank. It is set in `.env` to one of
`claude-haiku-4-5`, `claude-sonnet-5-5` and `claude-opus-5-5`; recreate this
service after changing it. The request is
shaped per model by `_model_options`: a model that thinks gets
`output_config.effort: "low"` and 4,000 tokens of headroom on top of the
caller's `max_tokens`, because thinking is billed against it; Haiku 4.5 gets
+4 -5
View File
@@ -22,12 +22,11 @@ log = logging.getLogger(__name__)
T = TypeVar("T", bound=BaseModel)
# Which model every call uses. CLAUDE_MODEL is set from the admin panel's
# Environment tab (it is in backend/services/env_registry.json, whose `options`
# list is what the panel offers); changing it there recreates this container,
# which is why reading it once at import is enough. Blank means the default.
# Which model every call uses. CLAUDE_MODEL comes from .env; changing it means
# recreating this container, which is why reading it once at import is enough.
# Blank means the default.
#
# The registry's options are the ids this module has been written for. Another
# The ids listed in .env.example are the ones this module has been written for. Another
# id is passed through as it is, treated as a model that thinks (see below);
# if the API does not know it, every call fails with its `failed` message and
# the reason is in this service's log.
-11
View File
@@ -76,17 +76,6 @@ def test_haiku_gets_the_plain_request(monkeypatch):
assert call == {"model": "claude-haiku-4-5", "max_tokens": 64, "messages": MESSAGES}
def test_the_default_model_is_one_the_admin_panel_offers():
"""CLAUDE_MODEL's options in the env registry are what the Environment tab lets an admin pick."""
import json
from pathlib import Path
registry = json.loads((Path(__file__).parents[2] / "backend/services/env_registry.json").read_text())
(entry,) = [v for v in registry if v["name"] == "CLAUDE_MODEL"]
assert claude.DEFAULT_MODEL in entry["options"]
assert "python" in entry["services"]
def test_the_answer_is_found_after_a_thinking_block():
reply = SimpleNamespace(
stop_reason="end_turn",
+2 -26
View File
@@ -1,5 +1,5 @@
# =============================================================================
# Vue frontend image — compiles Rust to WASM, then builds the SPA.
# Vue frontend image — builds the SPA.
#
# THIS IS A BUILD CONTAINER, NOT A SERVER. In production the container runs
# `vite build` into /output (the shared vue_dist volume) and EXITS. nginx then
@@ -7,16 +7,7 @@
# success case, not a failure. The dev override replaces the CMD with the Vite
# dev server, and then it does stay running.
#
# STAGE 1 — WASM
# Builds crates/stp_wasm with wasm-pack into src/wasm. Only that crate
# directory is copied in, so touching Vue source never invalidates the (slow)
# Rust layer. The two cache mounts persist the cargo registry and the Rust
# target directory between builds on the host — on a Raspberry Pi this turns
# a very long compile into an incremental one. src/wasm is gitignored: it is
# generated, never committed.
#
# STAGE 2 — Vue
# package.json + package-lock.json are copied first so `npm ci` is cached
# package.json + package-lock.json are copied first so `npm ci` is cached
# independently of source changes; the npm cache is also a BuildKit cache
# mount. `npm ci` (not `npm install`) installs exactly the lockfile, so a
# rebuild can never silently pick up a different dependency version.
@@ -26,21 +17,7 @@
# --emptyOutDir is required: /output is a mounted volume, and vite refuses to
# clear a directory outside the project root without it. Without the flag,
# stale assets from a previous build would accumulate and be served.
#
# Note stage 2 is not named and is the final stage; both base images are
# multi-arch so this builds on the Pi unchanged.
# =============================================================================
# Stage 1: Build WASM from Rust
FROM rust:slim AS wasm-builder
RUN rustup target add wasm32-unknown-unknown \
&& cargo install wasm-pack
WORKDIR /wasm
COPY crates/stp_wasm/ crates/stp_wasm/
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/wasm/crates/stp_wasm/target \
wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm
# Stage 2: Build Vue frontend
FROM node:22-slim
RUN apt-get update && apt-get install -y make git && rm -rf /var/lib/apt/lists/*
WORKDIR /app
@@ -48,5 +25,4 @@ COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
COPY --from=wasm-builder /wasm/src/wasm/ src/wasm/
CMD ["sh", "-c", "npx vite build --outDir /output --emptyOutDir"]
+109 -18
View File
@@ -44,7 +44,7 @@ has to be a bare uvicorn.
```
src/
main.js entry point — awaits the wasm init, then mounts <App>
main.js entry point — mounts <App>
App.vue empty shell; all chrome lives in the layouts
router/index.js route table + the single admin route guard
graphql.js the entire GraphQL client (one axios POST)
@@ -55,8 +55,6 @@ src/
views/ page components, one directory per area
assets/styles.css design tokens + base styles (see Styling)
js/ small shared helpers
wasm/ GENERATED by `npm run build:wasm`; gitignored, do not edit
crates/stp_wasm the Rust source for the above
```
## Routing
@@ -65,13 +63,14 @@ Two layout shells, defined in `src/router/index.js`:
| Path | Layout | Notes |
| --- | --- | --- |
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint) |
| `/stp` | DefaultLayout | The personal home page: the widget grid |
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint): a box canvas, page key `index`; the old fixed page is its starter layout, `views/landing/landingLayout.js` |
| `/stp` | DefaultLayout | The personal home page: an admin-editable canvas of boxes (`views/home3/`, see "The /stp canvas" below) |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
| `/automata`, `/hotels`, `/shrines/*` | DefaultLayout | |
| `/automata`, `/hotels` | DefaultLayout | |
| `/shrines`, `/shrines/*` | DefaultLayout | All canvas pages via the catch-all: `/shrines` is an index whose links are Link boxes placed by hand |
| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there |
| `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts |
| `:pathMatch(.*)*` | DefaultLayout | 404 |
| `:pathMatch(.*)*` | DefaultLayout | `views/canvas/CanvasPage.vue`: an admin-created canvas page if one exists at the path, else the 404 (with a "create a page here" form for admins) |
Everything except the landing page is a dynamic `import()`, so Vite gives each
view its own chunk.
@@ -124,15 +123,14 @@ the Vite proxy in dev).
The backend's REST routes go through `src/api.js`, the same idea for plain JSON:
```js
const body = await api.get("/admin/logs", { fallback: "Failed to load logs" });
const songs = await api.get("/radio/songs", { fallback: "Failed to load songs" });
await api.post("/radio/upload", formData, { fallback: "Upload failed" });
```
It prefixes `/api`, resolves to the response body, and on failure throws an
`ApiError` whose `message` is the backend's `{"error": "..."}` string when there
is one, otherwise the `fallback` the caller passed. `err.status` carries the
HTTP status for the few callers that branch on it (the Environment tab treats a
401/403 while polling as "the apply rotated my session"). Any other option is
HTTP status for callers that need to branch on it. Any other option is
passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
### Which one to use
@@ -141,10 +139,31 @@ passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
| --- | --- |
| reading or writing the site's data model | `gql()`, from a store |
| doing list/create/update/delete on one GraphQL type | a store built with `createCrudStore()` |
| calling a backend REST route (uploads, admin tooling, OAuth start) | `api` |
| storing a file, or showing one that was stored | `uploadFile()` and friends from `@/uploads` |
| calling a backend REST route (admin tooling, OAuth start) | `api` |
| reading the Python service's NDJSON streams | `views/hotels/hotelsStream.js` — incremental `fetch`, not `api` |
| probing `/radio/stream` | bare `axios.head` — it is Icecast, not the API |
### Uploading files
`src/uploads.js` is the one way to store a file:
```js
import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
// <input type="file" :accept="ACCEPT.images" @change="onPick">
const url = await uploadFile(file); // "/uploads/3f9c….png", public and permanent
```
It posts to `/api/uploads`; the backend (`backend/services/uploads.go`) owns
the allowed types, the 10MB limit and the file name, and stores the file in
Garage. A refused file rejects with an `ApiError` whose message can be shown
as-is. `kindOf(url)` says image/video/audio/file, `tagFor(url)` gives the
markup for a box, `isUploadUrl(url)` checks a URL from someone else before
rendering it, and `mediaSize(file)` reads an image or video's dimensions.
`{ private: true }` (admin only) is for private chat attachments; never use
it for anything shown in a canvas box, whose sandboxed frame has no cookie.
New views should not call `gql()` or `axios` directly (a few small admin forms
still call `gql()` for a one-off mutation). A view that needs data gets a
store; a view that needs a REST route calls `api`.
@@ -169,6 +188,8 @@ true only once a fetch has succeeded, meaning the data is real. Waiting on
| `auth` | current user (`ensureLoaded()`, see Routing), plus login/logout mutations |
| `posts`, `favorites`, `activity`, `songs`, `steam` | mirror one slice of `homeData` via an `immediate` watch, and keep a placeholder value until real data arrives |
| `places` | CRUD via `createCrudStore`; sign-in only, so it is fetched lazily |
| `boxes` | CRUD via `createCrudStore`, one store per canvas page: `useBoxesStore(page)`. Public read (admin-only boxes excepted), admin write |
| `pages` | CRUD via `createCrudStore`; the admin-created canvas pages. Public read (admin-only pages excepted), admin write |
| `messages` | the chat WebSocket — not GraphQL at all |
| `models` | dormant; not imported anywhere |
@@ -187,12 +208,83 @@ Two factories keep the repeated shapes in one place:
differences between types: `itemsKey` (the name the array is
exposed under), `insert` (`"prepend"` or `"append"`), `deleteReturns`
(`"object"` for `deletePlace`, `"boolean"` for a delete that returns a
scalar — a scalar must not be given a selection set) and `extend` for extra actions.
scalar — a scalar must not be given a selection set), `args` (fixed
arguments for the list query, e.g. the boxes store's `page`) and `extend`
for extra actions.
The error contract is deliberate: `fetch()` never throws and records the
failure on `error`; the mutations throw, so the form that called them can
show the message and keep what was typed.
## The /stp canvas
`/stp` is a set of **boxes** (`Box` in GraphQL, `stores/boxes.js`) that an admin
creates, drags, resizes and edits in the browser. Changes save to the database,
so every visitor sees the saved layout. The canvas is `views/home3/BoxCanvas.vue`,
and it is not only `/stp`: every box has a `page` key, and the same component
renders any page's boxes.
- **Pages.** `"stp"` is `/stp` (`Home3.vue`). `"index"` is the landing page
(`Landing.vue`), which is nothing but the canvas. Any other key is the slug of a **`Page`** (GraphQL
type, `stores/pages.js`), an admin-created page served at `/<slug>` by the
router's catch-all (`views/canvas/CanvasPage.vue`). Pages are created from
the admin panel's Pages tab (which also has a "New shrine" form, a blank page
under `shrines/`), or from the 404 of the address you want; each can start
from a layout in `views/canvas/pageStarters.js` (Blank, Notes board). Title, address and visibility are under "Page
settings" on the page; renaming moves its boxes, deleting takes them too.
The server refuses slugs that an SPA or nginx route would answer first
(`validateSlug` in `backend/graph/page_helpers.go`) — add to that list when
adding a route.
- **Backgrounds.** Each page key can have its own background (`Background` in
GraphQL, `stores/background.js`): a colour, an image, and whether the image
fills the window, fits inside it or tiles. Admins set it with the
"Background" button next to "Edit layout" (`BackgroundEditor.vue`), which
previews live and takes an uploaded or dropped image. `DefaultLayout` paints
it behind the whole window, navbar included, while that canvas is mounted,
and falls back to the halftone. Renaming or deleting a page carries its
background along; an admin-only page's background is hidden with it.
- **Admin only.** A box or a page can be marked admin-only. The server never
sends those to anyone else, so they are fit for private notes; admins see
such boxes outlined, with a 🔒 in edit mode. The "Note" template starts
admin-only.
- **Coordinates.** `x`/`y`/`w`/`h` are px on a fixed 1400px-wide design canvas.
`BoxCanvas.vue` draws the canvas at that width and shrinks it with
`transform: scale()` to fit the window, so the arrangement is identical at
every desktop width. `BoxFrame.vue` divides pointer deltas by that scale.
`z` is the CSS z-index.
- **Two kinds of box.** `kind: "widget"` shows a built-in Vue widget by name
from `widgetRegistry.js`. The registry keys are stored data, so don't rename
them. `kind: "html"` shows admin-written HTML (`HtmlBox.vue`) in an
`<iframe sandbox="allow-scripts">` **without `allow-same-origin`**. Its
scripts run, but they have an opaque origin: they can't read cookies, call
`/api` as the visitor, or touch the page. That sandbox is what makes storing
script in the database acceptable, so never add `allow-same-origin`.
`fetch()` from a box only reaches keyless APIs that answer
`Access-Control-Allow-Origin: *` (the Weather template uses Open-Meteo).
- **Site look inside the iframe.** `frameStyles.js` copies the colour tokens in
and inlines the two fonts as `data:` URLs. An opaque origin can't load
`/fonts/` without CORS headers.
- **Editing.** Admins get an "Edit layout" toggle at desktop width. Geometry
saves on pointer release, and the box is moved locally first and put back if
the save fails. `BoxEditor.vue` is the side panel. Settings save on change;
HTML is a draft that previews live and saves with Save or Ctrl/Cmd+S, or
automatically on leaving the box (selecting another, clicking empty canvas,
Done, ✕).
CodeMirror is loaded only when that panel opens; the panel is teleported to
`<body>`.
Image and video files dropped onto the canvas in edit mode are uploaded and
each becomes an unframed box at the drop point. "Insert upload" stores a
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
tag for it at the cursor. Starter HTML is in `templates.js`; links in a box
need `target="_top"` or `_blank` (the Link templates set it), or they open
inside the frame. A canvas given a `starter` has an import button in edit
mode (it confirms first if the page isn't empty): on `/stp`, "Import current
layout" recreates the old `Home.vue` grid from `defaultLayout.js`; on `/`,
"Import old landing page" recreates the old bio and links.
- **Phones (≤700px)** get no canvas: boxes stack full-width in `(y, x)` order at
their saved height, skipping any with `hideOnMobile`. There is no separate
mobile layout. To change the order, move boxes on the desktop canvas.
## Component conventions
- Layout and one-off tweaks go in Tailwind utilities; reach for a scoped
@@ -223,10 +315,8 @@ Two factories keep the repeated shapes in one place:
- **Production** (`npm run build`): `dist/` is built into the nginx container
and served as static files, with nginx doing the same reverse-proxying.
Note `npm run build` runs `build:wasm` first, which needs **wasm-pack** on the
PATH. If you only want the Vue bundle and `src/wasm/` is already populated,
`npm run build:js` (plain `vite build`) skips that step. It is also the local
check that the app still compiles — there is no test runner or linter.
`npm run build` is a plain `vite build`. It is also the local check that the
app still compiles — there is no test runner or linter.
## Live vs legacy views
@@ -235,7 +325,9 @@ in its header comment; the summary:
| File | Status |
| --- | --- |
| `views/home/Home.vue` | live (`/stp`) — imports **Intro2** and **Gym2** |
| `views/home3/Home3.vue` | live (`/stp`) — the box canvas; its widget boxes use **Intro3** and **Gym2** |
| `views/home/shrines/{Shrines,Demoman,GTO,Evangelion,Skipskipbenben}.vue` | the old `/shrines` index and hand-written shrines (Demoman a video wall, the rest `<Wip />`), unrouted; shrines are canvas pages now |
| `views/home/Home.vue` | legacy fixed grid that `/stp` used to be; no route. Its widgets are still live through `home3/widgetRegistry.js` |
| `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported |
| `views/home/Gym.vue` | superseded by `Gym2.vue`; not imported |
| `views/home2/Home2.vue` | reachable at `/stp2`, but a static mock and unlinked |
@@ -244,7 +336,6 @@ in its header comment; the summary:
| `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable |
| `views/unused/CoverLetters.vue` | **live** despite the directory — it is the "Cover Letter" tab on `/cv` |
| `views/unused/Notes.vue` | no route points at it; not imported |
| `components/util/wasm/AutoScroll.vue` | Rust port of the JS AutoScroll; not imported |
| `components/util/{MusicPlayer,ObjectTable}.vue` | not imported |
| `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported |
| `stores/models.js`, `js/mobile-automata.mjs` | not imported |
-136
View File
@@ -1,136 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bumpalo"
version = "3.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "js-sys"
version = "0.3.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"
dependencies = [
"once_cell",
"wasm-bindgen",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "stp_wasm"
version = "0.1.0"
dependencies = [
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "syn"
version = "2.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "wasm-bindgen"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"
dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"
dependencies = [
"js-sys",
"wasm-bindgen",
]
-25
View File
@@ -1,25 +0,0 @@
[package]
name = "stp_wasm"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib"]
[dependencies]
js-sys = "0.3.85"
wasm-bindgen = "0.2.108"
web-sys = { version = "0.3.85", features = [
"console",
"Document",
"Element",
"HtmlElement",
"Window",
"Animation",
"CssStyleDeclaration",
"ResizeObserver",
"ResizeObserverEntry",
"ResizeObserverSize",
"EventTarget",
"MouseEvent",
] }
-259
View File
@@ -1,259 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;
const SPEED: f64 = 0.0005; // % per frame
const PAUSE: i32 = 2000; // ms at top/bottom
struct Inner {
el: HtmlElement,
pos: f64,
direction: f64, // 1.0 = down, -1.0 = up
hovered: bool,
cached_scroll_height: f64,
raf_id: Option<i32>,
pause_timeout_id: Option<i32>,
resize_observer: Option<web_sys::ResizeObserver>,
// closures kept alive
tick_closure: Option<Closure<dyn FnMut()>>,
resize_closure: Option<Closure<dyn FnMut(js_sys::Array)>>,
mouseenter_closure: Option<Closure<dyn FnMut()>>,
mouseleave_closure: Option<Closure<dyn FnMut()>>,
start_after_pause_closure: Option<Closure<dyn FnMut()>>,
}
#[wasm_bindgen]
pub struct AutoScroller {
inner: Rc<RefCell<Inner>>,
}
impl Inner {
fn measure_scroll_height(&mut self) {
self.cached_scroll_height = self.el.scroll_height() as f64;
}
fn stop_loop(&mut self) {
let window = web_sys::window().unwrap();
if let Some(id) = self.raf_id.take() {
window.cancel_animation_frame(id).ok();
}
if let Some(id) = self.pause_timeout_id.take() {
window.clear_timeout_with_handle(id);
}
}
}
fn start_loop(inner: &Rc<RefCell<Inner>>) {
{
let mut s = inner.borrow_mut();
s.stop_loop();
}
schedule_tick(inner);
}
fn schedule_tick(inner: &Rc<RefCell<Inner>>) {
let inner_clone = Rc::clone(inner);
// Create a fresh tick closure each frame
let closure = Closure::once(move || {
tick(&inner_clone);
});
let mut s = inner.borrow_mut();
let window = web_sys::window().unwrap();
let id = window
.request_animation_frame(closure.as_ref().unchecked_ref())
.unwrap();
s.raf_id = Some(id);
// Store the closure to keep it alive until the frame fires
s.tick_closure = Some(closure);
}
fn tick(inner: &Rc<RefCell<Inner>>) {
let should_continue;
{
let mut s = inner.borrow_mut();
s.raf_id = None;
if s.hovered {
return;
}
if s.cached_scroll_height == 0.0 {
drop(s);
schedule_tick(inner);
return;
}
let reached_bottom = s.pos >= 1.0;
let reached_top = s.pos <= 0.0;
if reached_bottom {
s.pos = 0.999;
s.direction = -1.0;
drop(s);
schedule_pause(inner);
return;
} else if reached_top && s.direction == -1.0 {
s.pos = 0.001;
s.direction = 1.0;
drop(s);
schedule_pause(inner);
return;
}
s.pos += s.direction * SPEED;
s.el.set_scroll_top((s.pos * s.cached_scroll_height) as i32);
should_continue = true;
}
if should_continue {
schedule_tick(inner);
}
}
fn schedule_pause(inner: &Rc<RefCell<Inner>>) {
{
let mut s = inner.borrow_mut();
s.stop_loop();
}
let inner_clone = Rc::clone(inner);
let closure = Closure::once(move || {
start_loop(&inner_clone);
});
let mut s = inner.borrow_mut();
let window = web_sys::window().unwrap();
let id = window
.set_timeout_with_callback_and_timeout_and_arguments_0(
closure.as_ref().unchecked_ref(),
PAUSE,
)
.unwrap();
s.pause_timeout_id = Some(id);
s.start_after_pause_closure = Some(closure);
}
#[wasm_bindgen]
impl AutoScroller {
#[wasm_bindgen(constructor)]
pub fn new(el: HtmlElement) -> AutoScroller {
let inner = Rc::new(RefCell::new(Inner {
el,
pos: 0.0,
direction: 1.0,
hovered: false,
cached_scroll_height: 0.0,
raf_id: None,
pause_timeout_id: None,
resize_observer: None,
tick_closure: None,
resize_closure: None,
mouseenter_closure: None,
mouseleave_closure: None,
start_after_pause_closure: None,
}));
// Set up mouseenter listener
{
let inner_clone = Rc::clone(&inner);
let closure = Closure::wrap(Box::new(move || {
let mut s = inner_clone.borrow_mut();
s.hovered = true;
s.stop_loop();
}) as Box<dyn FnMut()>);
let s = inner.borrow();
s.el
.add_event_listener_with_callback("mouseenter", closure.as_ref().unchecked_ref())
.unwrap();
drop(s);
inner.borrow_mut().mouseenter_closure = Some(closure);
}
// Set up mouseleave listener
{
let inner_clone = Rc::clone(&inner);
let closure = Closure::wrap(Box::new(move || {
{
let mut s = inner_clone.borrow_mut();
s.hovered = false;
if s.cached_scroll_height > 0.0 {
s.pos = s.el.scroll_top() as f64 / s.cached_scroll_height;
}
}
start_loop(&inner_clone);
}) as Box<dyn FnMut()>);
let s = inner.borrow();
s.el
.add_event_listener_with_callback("mouseleave", closure.as_ref().unchecked_ref())
.unwrap();
drop(s);
inner.borrow_mut().mouseleave_closure = Some(closure);
}
AutoScroller { inner }
}
pub fn start(&self) {
// Measure initial scroll height
self.inner.borrow_mut().measure_scroll_height();
// Set up resize observer
let inner_clone = Rc::clone(&self.inner);
let resize_closure = Closure::wrap(Box::new(move |_entries: js_sys::Array| {
inner_clone.borrow_mut().measure_scroll_height();
}) as Box<dyn FnMut(js_sys::Array)>);
let observer =
web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref()).unwrap();
// Clone the element ref and drop the borrow before calling observe(),
// because observe() can fire the resize callback synchronously,
// which would conflict with an active borrow.
let el_clone = self.inner.borrow().el.clone();
observer.observe(&el_clone);
{
let mut s = self.inner.borrow_mut();
s.resize_observer = Some(observer);
s.resize_closure = Some(resize_closure);
}
// Start with a pause then begin scrolling
schedule_pause(&self.inner);
}
pub fn destroy(&self) {
let mut s = self.inner.borrow_mut();
s.stop_loop();
if let Some(observer) = s.resize_observer.take() {
observer.disconnect();
}
if let Some(ref closure) = s.mouseenter_closure {
s.el
.remove_event_listener_with_callback(
"mouseenter",
closure.as_ref().unchecked_ref(),
)
.ok();
}
if let Some(ref closure) = s.mouseleave_closure {
s.el
.remove_event_listener_with_callback(
"mouseleave",
closure.as_ref().unchecked_ref(),
)
.ok();
}
s.mouseenter_closure = None;
s.mouseleave_closure = None;
s.resize_closure = None;
s.tick_closure = None;
s.start_after_pause_closure = None;
}
}
-135
View File
@@ -1,135 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;
const SPEED: f64 = 0.5; // pixels per frame
struct Inner {
container: HtmlElement,
item1: HtmlElement,
offset: f64,
cached_width: f64,
raf_id: Option<i32>,
resize_observer: Option<web_sys::ResizeObserver>,
// closures kept alive
animate_closure: Option<Closure<dyn FnMut()>>,
resize_closure: Option<Closure<dyn FnMut(js_sys::Array)>>,
}
#[wasm_bindgen]
pub struct HeadlineScroller {
inner: Rc<RefCell<Inner>>,
}
impl Inner {
fn measure_width(&mut self) {
let container_width = self.container.offset_width() as f64;
let item_width = self.item1.scroll_width() as f64;
self.cached_width = container_width.max(item_width);
}
}
fn schedule_frame(inner: &Rc<RefCell<Inner>>) {
let inner_clone = Rc::clone(inner);
let closure = Closure::once(move || {
animate(&inner_clone);
});
let mut s = inner.borrow_mut();
let window = web_sys::window().unwrap();
let id = window
.request_animation_frame(closure.as_ref().unchecked_ref())
.unwrap();
s.raf_id = Some(id);
s.animate_closure = Some(closure);
}
fn animate(inner: &Rc<RefCell<Inner>>) {
{
let mut s = inner.borrow_mut();
s.raf_id = None;
if s.cached_width == 0.0 {
drop(s);
schedule_frame(inner);
return;
}
s.offset -= SPEED;
if s.offset <= -s.cached_width {
s.offset += s.cached_width;
}
let transform = format!("translateX({}px)", s.offset);
s.container.style().set_property("transform", &transform).ok();
}
schedule_frame(inner);
}
#[wasm_bindgen]
impl HeadlineScroller {
#[wasm_bindgen(constructor)]
pub fn new(container: HtmlElement, item1: HtmlElement) -> HeadlineScroller {
let inner = Rc::new(RefCell::new(Inner {
container,
item1,
offset: 0.0,
cached_width: 0.0,
raf_id: None,
resize_observer: None,
animate_closure: None,
resize_closure: None,
}));
HeadlineScroller { inner }
}
pub fn start(&self) {
// Measure initial width
self.inner.borrow_mut().measure_width();
// Set up resize observer
let inner_clone = Rc::clone(&self.inner);
let resize_closure = Closure::wrap(Box::new(move |_entries: js_sys::Array| {
inner_clone.borrow_mut().measure_width();
}) as Box<dyn FnMut(js_sys::Array)>);
let observer =
web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref()).unwrap();
// Clone the element ref and drop the borrow before calling observe(),
// because observe() can fire the resize callback synchronously,
// which would conflict with an active borrow.
let container_clone = self.inner.borrow().container.clone();
observer.observe(&container_clone);
{
let mut s = self.inner.borrow_mut();
s.resize_observer = Some(observer);
s.resize_closure = Some(resize_closure);
}
// Start animation loop
schedule_frame(&self.inner);
}
pub fn destroy(&self) {
let mut s = self.inner.borrow_mut();
let window = web_sys::window().unwrap();
if let Some(id) = s.raf_id.take() {
window.cancel_animation_frame(id).ok();
}
if let Some(observer) = s.resize_observer.take() {
observer.disconnect();
}
s.animate_closure = None;
s.resize_closure = None;
}
}
-5
View File
@@ -1,5 +0,0 @@
mod auto_scroll;
mod headline;
pub use auto_scroll::AutoScroller;
pub use headline::HeadlineScroller;
+233 -348
View File
@@ -8,10 +8,13 @@
"name": "nginx-html",
"version": "0.0.0",
"dependencies": {
"@codemirror/lang-html": "^6.4.11",
"@codemirror/view": "^6.43.14",
"@mdit/plugin-katex": "^0.24.1",
"@tailwindcss/vite": "^4.1.18",
"@vueuse/core": "^14.2.1",
"axios": "^1.13.2",
"codemirror": "^6.0.2",
"dompurify": "^3.3.3",
"katex": "^0.16.27",
"markdown-it": "^14.1.0",
@@ -25,9 +28,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.1",
"vite": "^7.3.2",
"vite-plugin-top-level-await": "^1.6.0",
"vite-plugin-vue-devtools": "^8.0.3",
"vite-plugin-wasm": "^3.6.0"
"vite-plugin-vue-devtools": "^8.0.3"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
@@ -488,6 +489,139 @@
"node": ">=6.9.0"
}
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.11.1",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz",
"integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.11",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.13.1",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz",
"integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/streamparser": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search": {
"version": "6.7.2",
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.2.tgz",
"integrity": "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.37.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.6",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/streamparser": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz",
"integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==",
"license": "MIT"
},
"node_modules/@codemirror/view": {
"version": "6.43.14",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.14.tgz",
"integrity": "sha512-hC45YnmJNR1rz42OF57BLoQNFMV12/13drnvibDsR2quNDmldcb4WvYVV81hFQg56i9lcqQMEDqilhX2QDcGQQ==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
@@ -949,6 +1083,69 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lezer/common": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.3.tgz",
"integrity": "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",
"integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.6",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz",
"integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.11",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.11.tgz",
"integrity": "sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
"license": "MIT"
},
"node_modules/@mdit/helper": {
"version": "0.22.1",
"resolved": "https://registry.npmjs.org/@mdit/helper/-/helper-0.22.1.tgz",
@@ -1026,24 +1223,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/@rollup/plugin-virtual": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@rollup/plugin-virtual/-/plugin-virtual-3.0.2.tgz",
"integrity": "sha512-10monEYsBp3scM4/ND4LNH5Rxvh3e/cVeL3jWTgZ2SrQ+BmUoQcopVQvnaMcOnykb1VkxUFuDAN+0FnpTFRy2A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
@@ -1369,293 +1548,6 @@
"win32"
]
},
"node_modules/@swc/core": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.15.24.tgz",
"integrity": "sha512-5Hj8aNasue7yusUt8LGCUe/AjM7RMAce8ZoyDyiFwx7Al+GbYKL+yE7g4sJk8vEr1dKIkTRARkNIJENc4CjkBQ==",
"dev": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@swc/counter": "^0.1.3",
"@swc/types": "^0.1.26"
},
"engines": {
"node": ">=10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/swc"
},
"optionalDependencies": {
"@swc/core-darwin-arm64": "1.15.24",
"@swc/core-darwin-x64": "1.15.24",
"@swc/core-linux-arm-gnueabihf": "1.15.24",
"@swc/core-linux-arm64-gnu": "1.15.24",
"@swc/core-linux-arm64-musl": "1.15.24",
"@swc/core-linux-ppc64-gnu": "1.15.24",
"@swc/core-linux-s390x-gnu": "1.15.24",
"@swc/core-linux-x64-gnu": "1.15.24",
"@swc/core-linux-x64-musl": "1.15.24",
"@swc/core-win32-arm64-msvc": "1.15.24",
"@swc/core-win32-ia32-msvc": "1.15.24",
"@swc/core-win32-x64-msvc": "1.15.24"
},
"peerDependencies": {
"@swc/helpers": ">=0.5.17"
},
"peerDependenciesMeta": {
"@swc/helpers": {
"optional": true
}
}
},
"node_modules/@swc/core-darwin-arm64": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.15.24.tgz",
"integrity": "sha512-uM5ZGfFXjtvtJ+fe448PVBEbn/CSxS3UAyLj3O9xOqKIWy3S6hPTXSPbszxkSsGDYKi+YFhzAsR4r/eXLxEQ0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-darwin-x64": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.15.24.tgz",
"integrity": "sha512-fMIb/Zfn929pw25VMBhV7Ji2Dl+lCWtUPNdYJQYOke+00E5fcQ9ynxtP8+qhUo/HZc+mYQb1gJxwHM9vty+lXg==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-arm-gnueabihf": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.15.24.tgz",
"integrity": "sha512-vOkjsyjjxnoYx3hMEWcGxQrMgnNrRm6WAegBXrN8foHtDAR+zpdhpGF5a4lj1bNPgXAvmysjui8cM1ov/Clkaw==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-arm64-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.15.24.tgz",
"integrity": "sha512-h/oNu+upkXJ6Cicnq7YGVj9PkdfarLCdQa8l/FlHYvfv8CEiMaeeTnpLU7gSBH/rGxosM6Qkfa/J9mThGF9CLA==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-arm64-musl": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.15.24.tgz",
"integrity": "sha512-ZpF/pRe1guk6sKzQI9D1jAORtjTdNlyeXn9GDz8ophof/w2WhojRblvSDJaGe7rJjcPN8AaOkhwdRUh7q8oYIg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-ppc64-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-ppc64-gnu/-/core-linux-ppc64-gnu-1.15.24.tgz",
"integrity": "sha512-QZEsZfisHTSJlmyChgDFNmKPb3W6Lhbfo/O76HhIngfEdnQNmukS38/VSe1feho+xkV5A5hETyCbx3sALBZKAQ==",
"cpu": [
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-s390x-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-s390x-gnu/-/core-linux-s390x-gnu-1.15.24.tgz",
"integrity": "sha512-DLdJKVsJgglqQrJBuoUYNmzm3leI7kUZhLbZGHv42onfKsGf6JDS3+bzCUQfte/XOqDjh/tmmn1DR/CF/tCJFw==",
"cpu": [
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-x64-gnu": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.15.24.tgz",
"integrity": "sha512-IpLYfposPA/XLxYOKpRfeccl1p5dDa3+okZDHHTchBkXEaVCnq5MADPmIWwIYj1tudt7hORsEHccG5no6IUQRw==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-linux-x64-musl": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.15.24.tgz",
"integrity": "sha512-JHy3fMSc0t/EPWgo74+OK5TGr51aElnzqfUPaiRf2qJ/BfX5CUCfMiWVBuhI7qmVMBnk1jTRnL/xZnOSHDPLYg==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-win32-arm64-msvc": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.15.24.tgz",
"integrity": "sha512-Txj+qUH1z2bUd1P3JvwByfjKFti3cptlAxhWgmunBUUxy/IW3CXLZ6l6Gk4liANadKkU71nIU1X30Z5vpMT3BA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-win32-ia32-msvc": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.15.24.tgz",
"integrity": "sha512-15D/nl3XwrhFpMv+MADFOiVwv3FvH9j8c6Rf8EXBT3Q5LoMh8YnDnSgPYqw1JzPnksvsBX6QPXLiPqmcR/Z4qQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/core-win32-x64-msvc": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.15.24.tgz",
"integrity": "sha512-PR0PlTlPra2JbaDphrOAzm6s0v9rA0F17YzB+XbWD95B4g2cWcZY9LAeTa4xll70VLw9Jr7xBrlohqlQmelMFQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 AND MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=10"
}
},
"node_modules/@swc/counter": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@swc/types": {
"version": "0.1.26",
"resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.26.tgz",
"integrity": "sha512-lyMwd7WGgG79RS7EERZV3T8wMdmPq3xwyg+1nmAM64kIhx5yl+juO2PYIHb7vTiPgPCj8LYjsNV2T5wiQHUEaw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@swc/counter": "^0.1.3"
}
},
"node_modules/@swc/wasm": {
"version": "1.15.24",
"resolved": "https://registry.npmjs.org/@swc/wasm/-/wasm-1.15.24.tgz",
"integrity": "sha512-vFjzOE8dhJcfeTbM4+HO9Qy58IINV0ysqStAgw81uds+KqCeUDM9huN+SZ5lWZ6U+5nf8VcZoEw5N81xMtAidg==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@tailwindcss/node": {
"version": "4.1.18",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
@@ -2413,6 +2305,21 @@
],
"license": "CC-BY-4.0"
},
"node_modules/codemirror": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
"integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/commands": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/search": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -2456,6 +2363,12 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -3686,6 +3599,12 @@
"punycode": "^2.1.1"
}
},
"node_modules/style-mod": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz",
"integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==",
"license": "MIT"
},
"node_modules/superjson": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",
@@ -3825,20 +3744,6 @@
"integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
"license": "(WTFPL OR MIT)"
},
"node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"dev": true,
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/vite": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
@@ -3982,22 +3887,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/vite-plugin-top-level-await": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/vite-plugin-top-level-await/-/vite-plugin-top-level-await-1.6.0.tgz",
"integrity": "sha512-bNhUreLamTIkoulCR9aDXbTbhLk6n1YE8NJUTTxl5RYskNRtzOR0ASzSjBVRtNdjIfngDXo11qOsybGLNsrdww==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rollup/plugin-virtual": "^3.0.2",
"@swc/core": "^1.12.14",
"@swc/wasm": "^1.12.14",
"uuid": "10.0.0"
},
"peerDependencies": {
"vite": ">=2.8"
}
},
"node_modules/vite-plugin-vue-devtools": {
"version": "8.0.5",
"resolved": "https://registry.npmjs.org/vite-plugin-vue-devtools/-/vite-plugin-vue-devtools-8.0.5.tgz",
@@ -4073,16 +3962,6 @@
"vite": "^3.0.0-0 || ^4.0.0-0 || ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0"
}
},
"node_modules/vite-plugin-wasm": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.6.0.tgz",
"integrity": "sha512-mL/QPziiIA4RAA6DkaZZzOstdwbW5jO4Vz7Zenj0wieKWBlNvIvX5L5ljum9lcUX0ShNfBgCNLKTjNkRVVqcsw==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"vite": "^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8"
}
},
"node_modules/vue": {
"version": "3.5.26",
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.26.tgz",
@@ -4125,6 +4004,12 @@
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
"license": "MIT"
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
},
"node_modules/wsl-utils": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.1.0.tgz",
+5 -6
View File
@@ -7,17 +7,18 @@
"node": "^20.19.0 || >=22.12.0"
},
"scripts": {
"build:wasm": "wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm",
"dev": "vite",
"build": "npm run build:wasm && vite build",
"build:js": "vite build",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@codemirror/lang-html": "^6.4.11",
"@codemirror/view": "^6.43.14",
"@mdit/plugin-katex": "^0.24.1",
"@tailwindcss/vite": "^4.1.18",
"@vueuse/core": "^14.2.1",
"axios": "^1.13.2",
"codemirror": "^6.0.2",
"dompurify": "^3.3.3",
"katex": "^0.16.27",
"markdown-it": "^14.1.0",
@@ -31,8 +32,6 @@
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.1",
"vite": "^7.3.2",
"vite-plugin-top-level-await": "^1.6.0",
"vite-plugin-vue-devtools": "^8.0.3",
"vite-plugin-wasm": "^3.6.0"
"vite-plugin-vue-devtools": "^8.0.3"
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
* OAuth starts — everything backend/README.md lists as "not GraphQL").
*
* It does two things a bare axios call does not:
* - prefixes `/api`, so callers name the route (`api.get("/admin/logs")`);
* - prefixes `/api`, so callers name the route (`api.get("/radio/songs")`);
* - turns a failure into an ApiError whose `message` is the backend's
* `{"error": "..."}` body when there is one. Every handler reports errors
* in that shape, and each view used to dig it out of `err.response` itself.
+14 -25
View File
@@ -18,6 +18,7 @@ import { useMessagesStore } from "@/stores/messages";
import { useAuthStore } from "@/stores/auth";
import Header from "@/components/text/Header.vue";
import Link from "@/components/text/Link.vue";
import { ACCEPT, isUploadUrl, kindOf } from "@/uploads";
const messagesStore = useMessagesStore();
const authStore = useAuthStore();
@@ -116,28 +117,8 @@ async function onFileSelected(e) {
fileInput.value.value = "";
}
function isImageUrl(url) {
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
}
function isVideoUrl(url) {
return /\.(mp4|webm|ogg|mov)$/i.test(url);
}
// Public attachments live under /uploads/; attachments on private messages are
// written under /uploads/private/, which nginx gates behind an admin check.
const UPLOAD_PREFIXES = ["/uploads/", "/uploads/private/"];
/** Only render attachments the backend served from its own upload directory —
* the fileUrl arrives over the socket and is otherwise attacker-controlled.
* A strict prefix allowlist, so absolute ("https://evil/uploads/x") and
* protocol-relative ("//evil/uploads/x") URLs are rejected; "..", which could
* otherwise escape the directory, is rejected outright. */
function isSafeFileUrl(url) {
if (typeof url !== "string") return false;
if (url.includes("..")) return false;
return UPLOAD_PREFIXES.some((prefix) => url.startsWith(prefix));
}
// Attachments are rendered only if isUploadUrl() accepts them: the fileUrl
// arrives over the socket and is otherwise attacker-controlled.
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
// here only because parseMessageParts() below always runs exec() to completion
@@ -262,21 +243,28 @@ onUnmounted(() => {
>
<span v-else>{{ part.value }}</span>
</template>
<template v-if="message.fileUrl && isSafeFileUrl(message.fileUrl)">
<template v-if="isUploadUrl(message.fileUrl)">
<img
v-if="isImageUrl(message.fileUrl)"
v-if="kindOf(message.fileUrl) === 'image'"
:src="message.fileUrl"
alt="Uploaded image"
loading="lazy"
class="w-full max-w-full rounded block"
/>
<video
v-else-if="isVideoUrl(message.fileUrl)"
v-else-if="kindOf(message.fileUrl) === 'video'"
:src="message.fileUrl"
controls
preload="none"
class="w-full max-w-full max-h-48 rounded block"
/>
<audio
v-else-if="kindOf(message.fileUrl) === 'audio'"
:src="message.fileUrl"
controls
preload="none"
class="w-full max-w-full block"
/>
<Link
v-else
bare
@@ -299,6 +287,7 @@ onUnmounted(() => {
<input
ref="fileInput"
type="file"
:accept="ACCEPT.any"
class="hidden"
@change="onFileSelected"
/>
+65
View File
@@ -0,0 +1,65 @@
<script setup>
import OverlayShell from "./OverlayShell.vue";
const open = defineModel({ type: Boolean, default: false });
defineProps({
title: { type: String, default: "Are you sure?" },
message: { type: String, required: true },
confirmLabel: { type: String, default: "Confirm" },
});
const emit = defineEmits(["confirm", "cancel"]);
function cancel() {
open.value = false;
emit("cancel");
}
function confirm() {
open.value = false;
emit("confirm");
}
</script>
<template>
<OverlayShell v-model="open" :title="title" backdrop close-on-backdrop @close="cancel">
<div class="confirm bdr-1">
<h2>{{ title }}</h2>
<p>{{ message }}</p>
<div class="actions">
<button type="button" class="confirm-button" @click="confirm">{{ confirmLabel }}</button>
<button type="button" class="cancel-button" @click="cancel">Cancel</button>
</div>
</div>
</OverlayShell>
</template>
<style scoped>
.confirm {
box-sizing: border-box;
width: min(420px, calc(100vw - 24px));
padding: 16px;
color: var(--color-secondary);
background: var(--color-surface);
}
.confirm h2 {
margin-top: 0;
}
.actions {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
}
.actions button {
padding: 0.35rem 0.75rem;
color: var(--color-primary);
background: var(--color-link-bg);
border: 1px solid var(--color-primary);
cursor: pointer;
}
.confirm-button {
color: var(--color-tertiary) !important;
border-color: var(--color-tertiary) !important;
}
</style>
+6 -42
View File
@@ -1,62 +1,26 @@
<script setup>
import { watch, onUnmounted } from "vue";
import OverlayShell from "./OverlayShell.vue";
// Popup modal: a dimmed backdrop over the page with the content floated on top.
// Closes on backdrop click or Escape. Used by the home widgets so their create
// forms pop up instead of replacing the widget's contents.
const open = defineModel({ type: Boolean, default: false });
const props = defineProps({
maxWidth: { type: String, default: "420px" },
});
function onKeydown(e) {
if (e.key === "Escape") open.value = false;
}
// The Escape listener is attached only while open, so several modals on one
// page can't all react to a single keypress. `immediate` covers a modal that
// mounts already open.
watch(
open,
(isOpen) => {
if (isOpen) {
window.addEventListener("keydown", onKeydown);
} else {
window.removeEventListener("keydown", onKeydown);
}
},
{ immediate: true },
);
onUnmounted(() => window.removeEventListener("keydown", onKeydown));
</script>
<template>
<!-- Teleported to <body> so the backdrop escapes any ancestor with
overflow/transform/z-index that would otherwise clip or trap it. -->
<Teleport to="body">
<div v-if="open" class="modal-backdrop" @click.self="open = false">
<div class="modal bdr-1" :style="{ maxWidth: props.maxWidth }">
<slot />
</div>
<OverlayShell v-model="open" title="Dialog" backdrop close-on-backdrop>
<div class="modal bdr-1" :style="{ maxWidth: props.maxWidth }">
<slot />
</div>
</Teleport>
</OverlayShell>
</template>
<style scoped>
.modal-backdrop {
position: fixed;
inset: 0;
background-color: rgba(0, 0, 0, 0.65);
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
padding: 12px;
}
.modal {
box-sizing: border-box;
background-color: var(--color-surface);
padding: 16px;
width: 100%;
+132
View File
@@ -0,0 +1,132 @@
<script setup>
import { nextTick, onUnmounted, ref, watch } from "vue";
import { useOverlayStack } from "@/js/useOverlayStack";
const open = defineModel({ type: Boolean, default: false });
const emit = defineEmits(["close"]);
const props = defineProps({
role: { type: String, default: "dialog" },
title: { type: String, default: "" },
panelClass: { type: String, default: "" },
backdrop: { type: Boolean, default: false },
closeOnBackdrop: { type: Boolean, default: false },
});
const panel = ref(null);
let returnFocus = null;
let bodyLocks = 0;
let previousOverflow = "";
let bodyLocked = false;
function lockBody() {
if (!bodyLocks++) previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
bodyLocked = true;
}
function unlockBody() {
if (!bodyLocked) return;
bodyLocked = false;
if (--bodyLocks === 0) document.body.style.overflow = previousOverflow;
}
function close() {
open.value = false;
emit("close");
}
useOverlayStack(open, close);
function focusPanel() {
const target = panel.value?.querySelector("input, select, textarea, button, [tabindex]:not([tabindex='-1'])");
(target ?? panel.value)?.focus();
}
function trapFocus(event) {
if (event.key !== "Tab" || !panel.value) return;
const focusable = [...panel.value.querySelectorAll("input, select, textarea, button, [tabindex]:not([tabindex='-1'])")];
if (!focusable.length) {
event.preventDefault();
panel.value.focus();
return;
}
const first = focusable[0];
const last = focusable.at(-1);
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
watch(open, async (isOpen) => {
if (isOpen) {
lockBody();
returnFocus = document.activeElement;
await nextTick();
focusPanel();
} else if (returnFocus?.isConnected) {
unlockBody();
returnFocus.focus();
returnFocus = null;
} else {
unlockBody();
}
}, { immediate: true });
onUnmounted(() => {
unlockBody();
if (returnFocus?.isConnected) returnFocus.focus();
});
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="overlay-shell"
:class="{ 'has-backdrop': props.backdrop }"
@click.self="props.closeOnBackdrop && close()"
>
<section
ref="panel"
class="overlay-panel"
:class="props.panelClass"
:role="props.role"
:aria-modal="props.role === 'dialog' ? 'true' : undefined"
:aria-label="props.title || undefined"
tabindex="-1"
@keydown="trapFocus"
>
<slot />
</section>
</div>
</Teleport>
</template>
<style scoped>
.overlay-shell {
position: fixed;
inset: 0;
z-index: 60;
pointer-events: none;
}
.overlay-shell.has-backdrop {
display: flex;
align-items: center;
justify-content: center;
padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right))
max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
background: rgb(0 0 0 / 65%);
pointer-events: auto;
}
.overlay-panel {
max-width: 100%;
max-height: 100%;
pointer-events: auto;
outline: none;
}
</style>
@@ -1,36 +0,0 @@
<template>
<div ref="container" class="overflow-y-auto">
<slot />
</div>
</template>
<script setup>
/**
* Rust/wasm port of components/util/AutoScroll.vue — the whole rAF loop lives in
* the AutoScroller struct from src/wasm/.
*
* Note the two-step teardown: destroy() detaches the loop and listeners, free()
* releases the Rust-side memory. Skipping free() leaks the wasm allocation, which
* JS garbage collection cannot reclaim.
*
* STATUS: not imported anywhere; the JS AutoScroll is what the widgets use.
*/
import { useTemplateRef, onMounted, onBeforeUnmount } from "vue";
import { AutoScroller } from "@/wasm/stp_wasm.js";
const container = useTemplateRef("container");
let scroller = null;
onMounted(() => {
if (!container.value) return;
scroller = new AutoScroller(container.value);
scroller.start();
});
onBeforeUnmount(() => {
scroller?.destroy();
scroller?.free();
scroller = null;
});
</script>
+42
View File
@@ -0,0 +1,42 @@
import { onUnmounted, watch } from "vue";
const entries = [];
let listening = false;
function onKeydown(event) {
if (event.key !== "Escape") return;
entries.at(-1)?.close();
}
function updateListener() {
if (entries.length && !listening) {
window.addEventListener("keydown", onKeydown);
listening = true;
} else if (!entries.length && listening) {
window.removeEventListener("keydown", onKeydown);
listening = false;
}
}
/** Registers one open overlay so Escape always closes only the topmost one. */
export function useOverlayStack(open, close) {
let entry = null;
function register() {
if (entry) return;
entry = { close };
entries.push(entry);
updateListener();
}
function unregister() {
if (!entry) return;
const index = entries.indexOf(entry);
if (index !== -1) entries.splice(index, 1);
entry = null;
updateListener();
}
watch(open, (isOpen) => (isOpen ? register() : unregister()), { immediate: true });
onUnmounted(unregister);
}
+8 -1
View File
@@ -6,14 +6,21 @@
* assets/styles.css). `:key="$route.path"` forces a full remount on every path
* change so the transition actually runs even between two routes that share a
* component; `mode="out-in"` stops the outgoing and incoming pages overlapping.
*
* The background is the halftone unless the page on screen has one of its
* own (stores/background.js — set per canvas page, landing page and shrines
* included). The inline style overrides the halftone's layers.
*/
import { RouterView } from "vue-router";
import { useBackgroundStore } from "@/stores/background";
import Navbar from "@/components/Navbar.vue";
import Footer from "@/components/Footer.vue";
const background = useBackgroundStore();
</script>
<template>
<div class="default-layout halftone">
<div class="default-layout halftone" :style="background.style">
<Navbar class="no-print sticky top-0 z-50" />
<main class="default-content">
<RouterView v-slot="{ Component }">
-8
View File
@@ -1,10 +1,5 @@
/**
* App entry point. Mounts <App> on #app with the router and a fresh Pinia.
*
* The top-level `await init()` loads the Rust/wasm bundle before anything else
* renders, so components that reach for a wasm export (components/util/wasm/)
* never see an uninitialised module. Top-level await in an entry module is what
* `vite-plugin-top-level-await` in vite.config.js is there to support.
*/
import { createApp } from "vue";
@@ -12,9 +7,6 @@ import { createPinia } from "pinia";
import App from "./App.vue";
import router from "./router";
import "./assets/styles.css";
import init from "@/wasm/stp_wasm.js";
await init();
const app = createApp(App);
+11 -29
View File
@@ -5,6 +5,9 @@
* theme) and holds most routes; `/cv` mounts CVLayout (light print theme).
* `/stp2` is deliberately outside both — it is a bare full-bleed mock.
*
* Pages made in the browser (views/canvas/) have no entries here: the
* catch-all at the end looks the path up and renders the page if one exists.
*
* Only the landing page is statically imported; every other view is a dynamic
* import so Vite code-splits it into its own chunk.
*
@@ -33,7 +36,7 @@ const router = createRouter({
{
path: "stp",
name: "home",
component: () => import("@/views/home/Home.vue"),
component: () => import("@/views/home3/Home3.vue"),
},
{
path: "admin/login",
@@ -57,37 +60,16 @@ const router = createRouter({
name: "cheap-hotels",
component: () => import("@/views/hotels/CheapHotels.vue"),
},
{
path: "shrines",
name: "shrine links",
component: () => import("@/views/home/shrines/Shrines.vue"),
},
{
path: "shrines/gto",
name: "gto shrine",
component: () => import("@/views/home/shrines/GTO.vue"),
},
{
path: "shrines/skipskipbenben",
name: "skipskipbenben shrine",
component: () =>
import("@/views/home/shrines/Skipskipbenben.vue"),
},
{
path: "shrines/evangelion",
name: "evangelion shrine",
component: () =>
import("@/views/home/shrines/Evangelion.vue"),
},
{
path: "shrines/demoman",
name: "demoman shrine",
component: () => import("@/views/home/shrines/Demoman.vue"),
},
// /shrines and the shrines under it are canvas pages, made
// from the admin panel's Pages tab and served by the catch-all
// below. The old hand-written ones (views/home/shrines/) are
// unrouted.
// Anything else is an admin-created canvas page if one exists
// at that address (the Page GraphQL type), else the 404.
{
path: ":pathMatch(.*)*",
name: "404",
component: () => import("@/views/404/404.vue"),
component: () => import("@/views/canvas/CanvasPage.vue"),
},
],
},
+100
View File
@@ -0,0 +1,100 @@
/**
* Page backgrounds (the `Background` GraphQL type), one per canvas page key —
* "index" for the landing page, "stp", or a Page slug such as
* "shrines/evangelion" — and which one is on screen.
*
* DefaultLayout paints `style` behind everything, navbar included, so a
* background covers the whole window rather than just the canvas. Each
* BoxCanvas calls show(page) when it mounts and hide(page) when it goes;
* a page with no background (null) keeps the theme's halftone.
*
* `preview` is BackgroundEditor's unsaved draft: while it is set for the page
* on screen, it is what the layout paints, so every change shows at once.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { gql } from "@/graphql";
const FIELDS = "id page color image fit";
export const FITS = [
{ id: "cover", label: "Fill the window" },
{ id: "contain", label: "Fit inside the window" },
{ id: "tile", label: "Tile" },
];
/** CSS for a background, or null for the theme default. */
export function backgroundStyle(bg) {
if (!bg || (!bg.color && !bg.image)) return null;
const style = {
backgroundColor: bg.color || "var(--color-surface-deep)",
// "none" as well as a URL: either way the halftone's own layers go.
backgroundImage: bg.image ? `url("${bg.image}")` : "none",
};
if (bg.fit === "tile") {
Object.assign(style, { backgroundSize: "auto", backgroundRepeat: "repeat", backgroundPosition: "0 0" });
} else {
// Pinned to the window, so a tall page scrolls over one picture rather
// than stretching it down the whole page.
Object.assign(style, {
backgroundSize: bg.fit,
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
backgroundAttachment: "fixed",
});
}
return style;
}
export const useBackgroundStore = defineStore("background", () => {
// page key -> Background or null; a key not present hasn't been loaded.
const byPage = ref({});
const active = ref(null);
const preview = ref(null); // { page, color, image, fit }
const current = computed(() =>
preview.value && preview.value.page === active.value ? preview.value : byPage.value[active.value],
);
const style = computed(() => backgroundStyle(current.value));
async function load(page) {
try {
const data = await gql(`query Background($page: String!) { background(page: $page) { ${FIELDS} } }`, {
page,
});
byPage.value[page] = data.background;
} catch (err) {
// The theme default is a fine fallback; the page itself still loads.
console.warn(`Couldn't load the background for ${page}:`, err);
}
}
function show(page) {
active.value = page;
if (!(page in byPage.value)) load(page);
}
function hide(page) {
if (active.value === page) active.value = null;
if (preview.value?.page === page) preview.value = null;
}
async function save(page, { color, image, fit }) {
const data = await gql(
`mutation SetBackground($page: String!, $input: BackgroundInput!) {
setBackground(page: $page, input: $input) { ${FIELDS} }
}`,
{ page, input: { color, image, fit } },
);
byPage.value[page] = data.setBackground;
return data.setBackground;
}
async function clear(page) {
await gql(`mutation ClearBackground($page: String!) { clearBackground(page: $page) }`, { page });
byPage.value[page] = null;
}
return { byPage, active, preview, current, style, load, show, hide, save, clear };
});
+76
View File
@@ -0,0 +1,76 @@
/**
* Boxes on one canvas page (views/home3/BoxCanvas.vue) — full CRUD, built on
* createCrudStore().
*
* `useBoxesStore(page)` returns the store for that page key: "stp" for the
* home page, "index" for the landing page's overlay, or a Page slug. Each key
* gets its own Pinia store (id `boxes:<page>`), so moving between pages
* neither refetches a page already visited nor mixes two pages' boxes.
*
* Not part of the homeData query: the canvas has to know which boxes exist
* before it can mount the widgets that then trigger homeData, and keeping the
* two apart means a failing Spotify/Steam upstream can't blank the layout.
*
* The list query returns boxes ordered by z, so a new box (given the top z)
* belongs at the end. adminOnly boxes only come back for an admin — the
* server filters them — so the canvas refetches when the session changes.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const BOX_FIELDS = `
id
page
kind
widget
html
title
x
y
w
h
z
framed
hideOnMobile
adminOnly
`;
// The fields a duplicate copies. kind and widget/html are what make it the
// same box; geometry is offset so the copy is visibly separate.
const COPIED = ["page", "kind", "widget", "html", "title", "w", "h", "framed", "hideOnMobile", "adminOnly"];
const stores = new Map();
function defineFor(page) {
return createCrudStore(`boxes:${page}`, {
type: "Box",
list: "boxes",
fields: BOX_FIELDS,
insert: "append",
deleteReturns: "object",
args: { page: { type: "String!", value: page } },
extend: ({ items, create, update }) => {
const topZ = () => Math.max(0, ...items.value.map((b) => b.z)) + 1;
const bottomZ = () => Math.min(0, ...items.value.map((b) => b.z)) - 1;
return {
page,
topZ,
// Every box this store creates belongs to its page.
create: (input) => create({ ...input, page }),
bringToFront: (box) => update(box.id, { z: topZ() }),
sendToBack: (box) => update(box.id, { z: bottomZ() }),
duplicate: (box) => {
const input = Object.fromEntries(COPIED.map((k) => [k, box[k]]));
return create({ ...input, x: box.x + 20, y: box.y + 20, z: topZ() });
},
};
},
});
}
/** The boxes store for one page key. */
export function useBoxesStore(page) {
if (!stores.has(page)) stores.set(page, defineFor(page));
return stores.get(page)();
}
+18 -1
View File
@@ -37,6 +37,10 @@ import { gql } from "@/graphql";
* one, so the mutation text differs; the schema has both kinds.
* @param {(ctx: object) => object} [options.extend] extra state/actions merged
* into the store; receives the base members
* @param {Record<string, {type: string, value: *}>} [options.args] arguments
* for the list query, e.g. `{ page: { type: "String!", value: "stp" } }`.
* Fixed for the store's lifetime, so a list that varies needs one store per
* value (stores/boxes.js does this per page).
*/
export function createCrudStore(
id,
@@ -48,10 +52,20 @@ export function createCrudStore(
insert = "prepend",
deleteReturns = "object",
extend,
args = {},
},
) {
const deleteSelection = deleteReturns === "object" ? "{ id }" : "";
const argNames = Object.keys(args);
const listVarDecl = argNames.length
? `(${argNames.map((n) => `$${n}: ${args[n].type}`).join(", ")})`
: "";
const listArgs = argNames.length
? `(${argNames.map((n) => `${n}: $${n}`).join(", ")})`
: "";
const listVars = Object.fromEntries(argNames.map((n) => [n, args[n].value]));
return defineStore(id, () => {
const items = ref([]);
const loaded = ref(false);
@@ -62,7 +76,10 @@ export function createCrudStore(
async function fetch() {
loading.value = true;
try {
const data = await gql(`query ${type}List { ${list} { ${fields} } }`);
const data = await gql(
`query ${type}List${listVarDecl} { ${list}${listArgs} { ${fields} } }`,
listVars,
);
items.value = data[list] || [];
loaded.value = true;
error.value = null;
+8 -12
View File
@@ -8,7 +8,7 @@
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";
import { uploadFile } from "@/uploads";
/**
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
@@ -133,21 +133,17 @@ export const useMessagesStore = defineStore("messages", () => {
}
/**
* POST a file to the REST upload endpoint, then send its returned URL over
* the socket as a normal message. Two steps because the socket carries JSON
* text only. Errors surface via `lastError`.
* Store a file (uploads.js), then send its URL over the socket as a normal
* message. Two steps because the socket carries JSON text only. Errors
* surface via `lastError`.
*
* `private` is sent with the upload as well as with the message: the backend
* stores private attachments under /uploads/private/, which nginx gates
* behind an admin check.
* `private` goes to both: the upload is stored under /uploads/private/,
* which nginx gates behind an admin check, and the message is marked
* private. The two must agree.
*/
async function uploadAndSendFile(file, isPrivate = false) {
try {
const formData = new FormData();
formData.append("file", file);
formData.append("private", isPrivate ? "true" : "false");
const res = await axios.post("/api/messages/upload", formData);
const { url } = res.data;
const url = await uploadFile(file, { private: isPrivate });
if (!socket.value || !isConnected.value) return;
socket.value.send(
JSON.stringify({ text: "", fileUrl: url, private: isPrivate }),
+27
View File
@@ -0,0 +1,27 @@
/**
* Admin-created canvas pages (the `Page` GraphQL type) — full CRUD, built on
* createCrudStore().
*
* A page is only a slug and a title; what is on it lives in that slug's boxes
* store (stores/boxes.js). The list is public apart from adminOnly pages,
* which the server only returns to an admin. Single pages are looked up by
* views/canvas/CanvasPage.vue with its own `page(slug:)` query, so that
* opening one page doesn't download the whole list.
*/
import { createCrudStore } from "@/stores/createCrudStore";
export const PAGE_FIELDS = `
id
slug
title
adminOnly
`;
export const usePagesStore = createCrudStore("pages", {
type: "Page",
list: "pages",
fields: PAGE_FIELDS,
insert: "append",
deleteReturns: "object",
});
+109
View File
@@ -0,0 +1,109 @@
/**
* Uploaded files: the one module to use whenever the frontend stores a file
* or shows one it stored.
*
* import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
*
* <input type="file" :accept="ACCEPT.images" @change="…">
* const url = await uploadFile(file); // "/uploads/3f9c….png"
* kindOf(url) // "image"
*
* Files go to POST /api/uploads (backend/handlers/handle_upload.go). The
* backend decides everything that matters: the allowed types and the 10MB
* limit (backend/services/uploads.go, UploadTypes), the random file name, and
* where it is stored (the Garage bucket, falling back to disk). The URL it
* returns is permanent and public — anyone with it can load the file, no login
* — so never upload something that shouldn't be public unless it is a private
* chat attachment (`{ private: true }`, admin only).
*
* A refused file (wrong type, too large) rejects with an ApiError whose
* `message` is the backend's sentence, ready to show the user.
*/
import { api } from "@/api";
/**
* `accept` values for file pickers, matching what the backend allows. They
* only steer the picker; the backend enforces the real list.
*/
export const ACCEPT = {
images: "image/jpeg,image/png,image/gif,image/webp",
media: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg",
any: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg,application/pdf,text/plain",
};
/**
* Store one file; resolves to its URL.
*
* @param {File} file
* @param {object} [options]
* @param {boolean} [options.private] admin-only: store it under
* /uploads/private/, readable only by admins. Never use it for anything
* shown inside a canvas box — a box's sandboxed frame loads without the
* login cookie, so the file would not load.
* @returns {Promise<string>} "/uploads/<name>" or "/uploads/private/<name>"
*/
export async function uploadFile(file, { private: isPrivate = false } = {}) {
const body = new FormData();
body.append("file", file);
if (isPrivate) body.append("private", "true");
const { url } = await api.post("/uploads", body, { fallback: `Upload of ${file.name} failed` });
return url;
}
/** What a stored file is, from its URL: "image", "video", "audio" or "file". */
export function kindOf(url) {
if (/\.(jpe?g|png|gif|webp)$/i.test(url)) return "image";
if (/\.(mp4|webm)$/i.test(url)) return "video";
if (/\.(mp3|ogg)$/i.test(url)) return "audio";
return "file";
}
export const isImage = (url) => kindOf(url) === "image";
export const isVideo = (url) => kindOf(url) === "video";
/**
* Whether a URL is one of our own uploads. Use it before rendering a URL that
* came from somebody else (a chat message's fileUrl arrives over the socket
* and is otherwise attacker-controlled). A strict prefix check, so absolute
* ("https://evil/uploads/x") and protocol-relative ("//evil/uploads/x") URLs
* fail, and ".." is refused outright.
*/
export function isUploadUrl(url) {
return typeof url === "string" && !url.includes("..") && url.startsWith("/uploads/");
}
/** The markup a stored file is shown with in a box's HTML, by kind. */
export function tagFor(url) {
switch (kindOf(url)) {
case "image":
return `<img src="${url}" alt="">`;
case "video":
return `<video src="${url}" controls loop muted></video>`;
case "audio":
return `<audio src="${url}" controls></audio>`;
default:
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
}
}
/** Natural size of an image or video File, or null if it can't be read. */
export function mediaSize(file) {
return new Promise((resolve) => {
const src = URL.createObjectURL(file);
const done = (size) => {
URL.revokeObjectURL(src);
resolve(size);
};
if (file.type.startsWith("video/")) {
const v = document.createElement("video");
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
v.onerror = () => done(null);
v.src = src;
} else {
const img = new Image();
img.onload = () => done({ w: img.naturalWidth, h: img.naturalHeight });
img.onerror = () => done(null);
img.src = src;
}
});
}
+12 -4
View File
@@ -16,10 +16,9 @@ import CreateActivity from "./CreateActivity.vue";
import CreateRowing from "./CreateRowing.vue";
import CreateBookmark from "./CreateBookmark.vue";
import CreatePlace from "./CreatePlace.vue";
import ManagePages from "./ManagePages.vue";
import ManageUsers from "./ManageUsers.vue";
import ManageRadio from "./ManageRadio.vue";
import Environment from "./Environment.vue";
import Diagnostics from "./Diagnostics.vue";
const auth = useAuthStore();
@@ -31,10 +30,9 @@ const sections = [
{ id: "rowing", label: "Rowing", component: CreateRowing },
{ id: "bookmark", label: "Bookmark", component: CreateBookmark },
{ id: "place", label: "Place / Thing To Do", component: CreatePlace },
{ id: "pages", label: "Pages", component: ManagePages },
{ id: "users", label: "Manage Users", component: ManageUsers },
{ id: "radio", label: "Manage Radio", component: ManageRadio },
{ id: "environment", label: "Environment", component: Environment },
{ id: "diagnostics", label: "Diagnostics", component: Diagnostics },
];
const active = ref("place");
@@ -71,6 +69,16 @@ function handleLogout() {
>
{{ section.label }}
</button>
<!-- Logs and incoming request bodies live in Dozzle, outside the
SPA (nginx serves it at /dozzle/ behind the admin check). -->
<a
class="admin-nav-link no-underline"
href="/dozzle/"
target="_blank"
rel="noopener"
>
Logs ↗
</a>
</nav>
<section class="admin-panel bdr-2 bg-surface">
-111
View File
@@ -1,111 +0,0 @@
<script setup>
/**
* Admin panel: tail of the backend log.
*
* GET /api/admin/logs returns JSON read from the filesystem, not GraphQL —
* it is not part of the site's data model. Configuration, which used to share
* this tab, is on the Environment tab.
*
* An admin who remounts the component via tab switches re-triggers
* onMounted, which is the desired "refresh on tab change" behaviour.
*/
import { ref, onMounted, computed } from "vue";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
const lines = ref([]);
const logsError = ref("");
const loadingLogs = ref(false);
async function fetchLogs() {
loadingLogs.value = true;
try {
const res = await api.get("/admin/logs", {
fallback: "Failed to load logs",
});
lines.value = res.lines;
logsError.value = "";
} catch (err) {
logsError.value = err.message;
} finally {
loadingLogs.value = false;
}
}
// Traffic view: a filter over the log tail for "who is using my site" —
// lines with a client IP (the formatter appends it only for real visitors
// and error statuses). Skips the standard line numbers of JSON-array output.
const trafficOnly = ref(true);
const shownLines = computed(() => {
if (!trafficOnly.value) return lines.value;
return lines.value.filter((l) => /\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(l.trim()) || l.includes("!!! SERVER ERROR") || l.includes(" !!"));
});
onMounted(fetchLogs);
</script>
<template>
<div class="diagnostics">
<h1>Logs</h1>
<p class="hint">
Tail of the backend log (up to 500 lines): HTTP traffic and application
messages, newest last.
</p>
<div class="log-controls">
<label class="hint toggle">
<input type="checkbox" v-model="trafficOnly" /> visitors only
</label>
<Button :disabled="loadingLogs" @click="fetchLogs">
{{ loadingLogs ? "Loading…" : "Refresh" }}
</Button>
</div>
<p v-if="logsError" class="error">{{ logsError }}</p>
<p v-else-if="shownLines.length === 0" class="hint">
No {{ trafficOnly ? "visitor" : "" }} lines in the current tail.
</p>
<pre v-else class="log-output">{{ shownLines.join("\n") }}</pre>
</div>
</template>
<style scoped>
.diagnostics {
display: flex;
flex-direction: column;
gap: 8px;
}
.error {
color: var(--color-error, #b91c1c);
}
.hint {
font-size: 0.85rem;
opacity: 0.75;
}
.log-controls {
display: flex;
justify-content: flex-end;
gap: 12px;
align-items: center;
}
.toggle {
display: flex;
gap: 4px;
align-items: center;
cursor: pointer;
}
.log-output {
max-height: 400px;
overflow-y: auto;
padding: 8px;
background: var(--color-surface-tint, #111);
color: var(--color-primary);
font-size: 0.75rem;
line-height: 1.4;
white-space: pre-wrap;
word-break: break-all;
border: 1px solid var(--color-quaternary);
}
</style>
-549
View File
@@ -1,549 +0,0 @@
<script setup>
/**
* Admin Environment tab: every variable in .env, grouped, with the ones that
* are safe to change editable in place.
*
* Nothing here writes .env directly, and neither does the backend. Applying
* sends the staged edits to PUT /api/admin/env, which queues them for a
* script on the host (env-apply/apply.py) that rewrites the file and
* recreates the containers that read the changed variables. This component
* then polls GET /api/admin/env/status until the host reports back — through
* the backend's own restart, which is why failed polls are expected and
* ignored rather than shown.
*
* Secrets are write-only: the server sends "set" and at most the last four
* characters, never the value. A generated secret is the one exception, shown
* once from the response that created it.
*/
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
import SecretReveal from "@/components/admin/SecretReveal.vue";
import "./env.css";
const groups = ref([]);
const status = ref(null);
const error = ref("");
const loading = ref(true);
// Staged edits, none of which exist anywhere but this component until Apply.
// drafts: name -> text in the row's input
// generating: names to have the server mint a value for
// clearing: secrets to blank (a secret's empty input means "unchanged",
// so clearing one needs saying explicitly)
const drafts = reactive({});
const generating = reactive(new Set());
const clearing = reactive(new Set());
// Values the server generated in the last apply, shown once.
const revealed = ref({});
const applying = ref(false);
const outcome = ref(null); // { ok, text, output }
const awaitedId = ref("");
let pollTimer = null;
const allVars = computed(() => groups.value.flatMap((g) => g.vars));
function resetDrafts() {
for (const v of allVars.value) drafts[v.name] = v.secret ? "" : v.value || "";
generating.clear();
clearing.clear();
}
async function fetchEnv() {
try {
const res = await api.get("/admin/env", {
fallback: "Failed to load the environment",
});
groups.value = res.groups;
status.value = res.status;
error.value = "";
resetDrafts();
} catch (err) {
error.value = err.message;
} finally {
loading.value = false;
}
}
// What a row would send: null when it is untouched.
function changeFor(v) {
if (!v.editable) return null;
if (generating.has(v.name)) return { name: v.name, type: "generate" };
if (clearing.has(v.name)) return { name: v.name, type: "clear" };
const draft = (drafts[v.name] ?? "").trim();
if (v.secret) return draft ? { name: v.name, type: "set", value: draft } : null;
if (draft === (v.value || "")) return null;
return { name: v.name, type: draft ? "set" : "clear", value: draft };
}
const changes = computed(() =>
allVars.value.map((v) => ({ v, change: changeFor(v) })).filter((c) => c.change),
);
// Mirrors EnvManager.ServicesFor: the backend is always recreated.
const affectedServices = computed(() => {
const services = new Set(["backend"]);
for (const { v } of changes.value)
for (const s of v.services || []) services.add(s);
return [...services].sort();
});
const pendingNames = computed(() => new Set(status.value?.pending || []));
function toggleGenerate(v) {
if (generating.has(v.name)) return generating.delete(v.name);
generating.add(v.name);
clearing.delete(v.name);
drafts[v.name] = "";
}
function toggleClear(v) {
if (clearing.has(v.name)) return clearing.delete(v.name);
clearing.add(v.name);
generating.delete(v.name);
drafts[v.name] = "";
}
// Typing a value withdraws a staged generate or clear for the same row.
function onInput(v) {
generating.delete(v.name);
clearing.delete(v.name);
}
function pillFor(v) {
if (changeFor(v)) return { text: "changed", cls: "is-changed" };
if (pendingNames.value.has(v.name)) return { text: "pending", cls: "is-changed" };
if (!v.set) return { text: "unset", cls: "is-unset" };
if (v.secret) return { text: v.hint ? `set ••••${v.hint}` : "set", cls: "is-set" };
return { text: "set", cls: "is-set" };
}
async function apply() {
const warnings = changes.value.filter((c) => c.v.warning).map((c) => `• ${c.v.warning}`);
const lines = [
`Apply ${changes.value.length} change(s)?`,
`This recreates: ${affectedServices.value.join(", ")}. The site's API is unavailable for a few seconds.`,
...warnings,
];
if (!confirm(lines.join("\n"))) return;
const body = { set: {}, generate: [] };
for (const { change } of changes.value) {
if (change.type === "generate") body.generate.push(change.name);
else body.set[change.name] = change.type === "clear" ? "" : change.value;
}
applying.value = true;
outcome.value = null;
try {
const res = await api.put("/admin/env", body, {
fallback: "Failed to queue the change",
});
revealed.value = res.generated || {};
status.value = res.status;
awaitedId.value = res.status.id;
// Staged secrets have been sent; do not keep them in the inputs.
resetDrafts();
startPolling();
} catch (err) {
applying.value = false;
outcome.value = { ok: false, text: err.message };
}
}
function startPolling() {
stopPolling();
pollTimer = setInterval(poll, 2000);
}
function stopPolling() {
if (pollTimer) clearInterval(pollTimer);
pollTimer = null;
}
async function poll() {
let next;
try {
next = await api.get("/admin/env/status");
} catch (err) {
// 401/403 after an apply means the change invalidated this session
// (rotating BACKEND_SECRET does). Anything else is the backend
// restarting, which is the apply working.
if ([401, 403].includes(err.status)) {
stopPolling();
applying.value = false;
outcome.value = {
ok: true,
text: "Applied. Your session was signed with the old secret — log in again.",
};
}
return;
}
status.value = next;
if (next.id !== awaitedId.value) return;
if (next.state === "applied") {
stopPolling();
applying.value = false;
outcome.value = {
ok: true,
text: `Applied. Recreated ${(next.services || []).join(", ")}.`,
};
await fetchEnv();
} else if (next.state === "failed") {
stopPolling();
applying.value = false;
outcome.value = { ok: false, text: "The host could not apply the change.", output: next.output };
await fetchEnv();
}
}
async function cancelPending() {
try {
status.value = await api.delete("/admin/env/pending", {
fallback: "Failed to withdraw the change",
});
stopPolling();
applying.value = false;
outcome.value = { ok: true, text: "Pending change withdrawn. Nothing was applied." };
} catch (err) {
outcome.value = { ok: false, text: err.message };
}
}
const progressText = computed(() => {
const s = status.value;
if (!s) return "";
if (s.state === "pending") return "Queued — waiting for the host to pick it up…";
if (s.state === "applying")
return `Recreating ${(s.services || []).join(", ")}…`;
return "";
});
onMounted(async () => {
await fetchEnv();
// A change queued before this tab was opened is still worth following.
if (["pending", "applying"].includes(status.value?.state)) {
awaitedId.value = status.value.id;
applying.value = true;
startPolling();
}
});
onUnmounted(stopPolling);
</script>
<template>
<div class="env">
<h1>Environment</h1>
<p class="env-hint">
The site's <code>.env</code>. Edits are staged here, then applied on the
server, which restarts only the services that read what changed. Secrets
can be replaced but never read back.
</p>
<p v-if="error" class="env-error">{{ error }}</p>
<p v-if="loading" class="env-hint">Loading…</p>
<div v-if="Object.keys(revealed).length" class="env-revealed">
<SecretReveal
v-for="(value, name) in revealed"
:key="name"
:label="name"
:value="value"
/>
</div>
<div v-if="applying" class="env-banner">
<p>{{ progressText || "Applying…" }}</p>
<template v-if="status?.state === 'pending' && !status.watcher">
<p class="env-hint">
Nothing on the host has picked this up. On the Pi, run
<code>./env-apply/install.sh</code> once to install the watcher. To
apply this change by hand, from the repo root:
</p>
<code class="env-command">python3 env-apply/apply.py</code>
<Button class="px-2" @click="cancelPending">Withdraw change</Button>
</template>
</div>
<div v-else-if="outcome" class="env-banner" :class="outcome.ok ? 'is-ok' : 'is-failed'">
<p>{{ outcome.text }}</p>
<pre v-if="outcome.output" class="env-output">{{ outcome.output }}</pre>
</div>
<section v-for="group in groups" :key="group.name" class="env-card">
<header class="env-card-head">
<h2>{{ group.name }}</h2>
<span class="env-hint">
{{ group.vars.filter((v) => v.set).length }}/{{ group.vars.length }} set
</span>
</header>
<div
v-for="v in group.vars"
:key="v.name"
class="env-row"
:class="{ 'is-locked': !v.editable, 'is-dirty': !!changeFor(v) }"
>
<div class="env-meta">
<div class="env-name">
<code>{{ v.name }}</code>
<span class="env-pill" :class="pillFor(v).cls">{{ pillFor(v).text }}</span>
</div>
<p class="env-hint">
{{ v.purpose }}
<a
v-if="v.docsUrl && v.editable"
:href="v.docsUrl"
target="_blank"
rel="noopener noreferrer"
class="env-docs"
>{{ v.secret ? "Get a key" : "Open" }} ↗</a
>
</p>
</div>
<div v-if="v.editable" class="env-control">
<select
v-if="v.kind === 'enum' || v.kind === 'bool'"
v-model="drafts[v.name]"
:disabled="applying"
>
<option value="">(unset)</option>
<option
v-for="option in v.kind === 'bool' ? ['true', 'false'] : v.options"
:key="option"
:value="option"
>
{{ option }}
</option>
</select>
<template v-else>
<input
v-model="drafts[v.name]"
:type="v.secret ? 'password' : 'text'"
:placeholder="
generating.has(v.name)
? 'A new value will be generated'
: clearing.has(v.name)
? 'Will be cleared'
: v.secret
? v.set
? 'Paste a replacement'
: 'Paste a value'
: ''
"
:disabled="applying"
autocomplete="off"
spellcheck="false"
@input="onInput(v)"
/>
<Button
v-if="v.kind === 'generated'"
class="px-2"
:class="{ 'is-on': generating.has(v.name) }"
:disabled="applying"
@click="toggleGenerate(v)"
>
{{ v.set ? "Regenerate" : "Generate" }}
</Button>
<Button
v-if="v.secret && v.set"
class="px-2"
:class="{ 'is-on': clearing.has(v.name) }"
:disabled="applying"
@click="toggleClear(v)"
>
Clear
</Button>
</template>
<p v-if="v.warning && changeFor(v)" class="env-warning">
{{ v.warning }}
</p>
</div>
<p v-else class="env-control env-locked" :title="v.lockedReason">
<span v-if="!v.secret && v.set" class="env-value">{{ v.value }}</span>
<span class="env-hint">🔒 {{ v.lockedReason }}</span>
</p>
</div>
</section>
<footer v-if="changes.length && !applying" class="env-apply-bar">
<p>
<strong>{{ changes.length }}</strong>
{{ changes.length === 1 ? "change" : "changes" }} — recreates
{{ affectedServices.join(", ") }}
</p>
<div class="env-apply-actions">
<Button class="px-2" @click="resetDrafts">Discard</Button>
<Button class="px-2 env-apply" @click="apply">Apply</Button>
</div>
</footer>
</div>
</template>
<style scoped>
.env {
display: flex;
flex-direction: column;
gap: 10px;
}
.env-revealed {
display: flex;
flex-direction: column;
gap: 6px;
}
.env-banner {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
padding: 8px 10px;
border: 1px solid var(--color-primary);
background: var(--color-surface-tint);
}
.env-banner p {
margin: 0;
}
.env-banner.is-failed {
border-color: var(--color-error, #f87171);
}
.env-banner.is-failed > p {
color: var(--color-error, #f87171);
}
.env-command {
user-select: all;
font-size: 0.8rem;
}
.env-output {
width: 100%;
max-height: 200px;
overflow: auto;
margin: 0;
padding: 6px;
font-size: 0.75rem;
white-space: pre-wrap;
word-break: break-all;
color: var(--color-primary);
background: var(--color-surface-deep);
}
.env-row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.1fr);
gap: 4px 12px;
align-items: center;
padding: 6px 10px;
border-bottom: 1px solid var(--color-quaternary);
border-left: 2px solid transparent;
}
.env-row:last-child {
border-bottom: none;
}
.env-row.is-dirty {
border-left-color: var(--color-tertiary);
background: var(--color-surface-tint);
}
.env-row.is-locked .env-meta {
opacity: 0.6;
}
.env-name {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.env-name code {
font-size: 0.8rem;
word-break: break-all;
}
.env-docs {
margin-left: 4px;
padding: 0 4px;
font-size: 0.75rem;
white-space: nowrap;
}
.env-control {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
margin: 0;
}
.env-control input,
.env-control select {
flex: 1;
min-width: 120px;
padding: 3px 6px;
font-size: 0.85rem;
color: var(--color-primary);
background: var(--color-surface);
border: 1px solid var(--color-quaternary);
}
.env-control input:focus,
.env-control select:focus {
border-color: var(--color-primary);
outline: none;
}
.env-control :deep(button.is-on) {
color: var(--color-tertiary);
border-color: var(--color-tertiary);
}
.env-control :deep(button:disabled),
.env-control input:disabled,
.env-control select:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.env-warning {
flex-basis: 100%;
margin: 0;
font-size: 0.8rem;
color: var(--color-tertiary);
}
.env-locked {
flex-direction: column;
align-items: flex-start;
gap: 0;
}
.env-value {
font-size: 0.85rem;
color: var(--color-primary);
word-break: break-all;
}
/* Stays in view while scrolling a long list of rows, so the count of staged
changes and the Apply button are never off-screen. */
.env-apply-bar {
position: sticky;
bottom: 8px;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 10px;
border: 1px solid var(--color-tertiary);
background: var(--color-surface);
box-shadow: 0 0 12px var(--color-surface-deep);
}
.env-apply-bar p {
margin: 0;
}
.env-apply-actions {
display: flex;
gap: 8px;
}
.env-apply-actions :deep(.env-apply) {
color: var(--color-surface-deep);
background: var(--color-primary);
}
@media (max-width: 700px) {
.env-row {
grid-template-columns: 1fr;
}
}
</style>
+86
View File
@@ -0,0 +1,86 @@
<script setup>
/**
* Admin tab: the canvas pages made in the browser (views/canvas/). Lists them
* all, admin-only ones included, and creates new ones. A page's title,
* address and visibility are edited from "Page settings" on the page itself.
*
* "New shrine" is the same form with the address fixed under /shrines/. It
* starts blank and adds no link anywhere: /shrines is itself a canvas page,
* and its links are boxes put there by hand.
*/
import { usePagesStore } from "@/stores/pages";
import PageForm from "@/views/canvas/PageForm.vue";
import { ref } from "vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const pages = usePagesStore();
pages.fetch();
const removeTarget = ref(null);
const confirmationOpen = ref(false);
async function remove(page) {
removeTarget.value = page;
confirmationOpen.value = true;
}
async function confirmRemove() {
const page = removeTarget.value;
removeTarget.value = null;
if (!page) return;
try {
await pages.remove(page.id);
} catch (err) {
alert(err?.message || "Failed to delete");
}
}
</script>
<template>
<div class="flex flex-col gap-4">
<section>
<h1>Pages</h1>
<p class="text-muted">
The home page (/stp) and the landing page's notes are canvases too —
edit those on the pages themselves.
</p>
<p v-if="pages.error" class="text-tertiary">Couldn't load the pages.</p>
<table v-else-if="pages.pages.length" class="w-full">
<tr v-for="page in pages.pages" :key="page.id">
<td>
<RouterLink :to="`/${page.slug}`">/{{ page.slug }}</RouterLink>
</td>
<td>{{ page.title }}</td>
<td>{{ page.adminOnly ? "🔒 admin only" : "public" }}</td>
<td class="text-right">
<button type="button" class="text-tertiary cursor-pointer" @click="remove(page)">Delete</button>
</td>
</tr>
</table>
<p v-else-if="pages.loaded" class="text-muted">No pages yet.</p>
</section>
<section>
<h1>New shrine</h1>
<p class="text-muted">
A blank page under /shrines/. Link to it from the /shrines page with a
Link box.
</p>
<PageForm prefix="shrines/" placeholder="address, e.g. evangelion" submit-label="Create shrine" />
</section>
<section>
<h1>New page</h1>
<PageForm />
</section>
<ConfirmDialog
v-if="removeTarget"
v-model="confirmationOpen"
title="Delete page"
:message="`Delete the page “${removeTarget.title}” and everything on it?`"
confirm-label="Delete"
@confirm="confirmRemove"
@cancel="removeTarget = null"
/>
</div>
</template>
-54
View File
@@ -1,54 +0,0 @@
/*
* Card, pill and message styles for the admin Environment tab
* (Environment.vue) and any card it hosts as a child component. A plain
* stylesheet rather than a scoped block because scoped styles stop at a child
* component's root; the env- prefix is what keeps these from leaking.
*/
.env-card {
border: 1px solid var(--color-quaternary);
background: var(--color-surface-deep);
}
.env-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 4px 10px;
border-bottom: 1px solid var(--color-quaternary);
background: var(--color-surface-tint);
}
.env-card-head h2 {
margin: 0;
font-size: 1rem;
}
.env-pill {
flex: none;
padding: 0 8px;
border: 1px solid currentColor;
border-radius: 999px;
font-size: 0.7rem;
line-height: 1.5;
white-space: nowrap;
color: var(--color-muted);
}
.env-pill.is-set {
color: var(--color-secondary);
}
.env-pill.is-unset {
color: var(--color-muted);
opacity: 0.6;
}
.env-pill.is-changed {
color: var(--color-tertiary);
}
.env-hint {
margin: 0;
font-size: 0.85rem;
opacity: 0.75;
}
.env-error {
margin: 0;
color: var(--color-error, #f87171);
}
+206
View File
@@ -0,0 +1,206 @@
<script setup>
/**
* The router's catch-all: any path no other route claims is looked up as an
* admin-created canvas page (the `Page` GraphQL type) and, if there is one,
* rendered as a BoxCanvas whose page key is the slug. Otherwise it is the
* site's 404 — with, for an admin, a form to create a page right here.
*
* Static routes always win, which is why the server refuses slugs under the
* SPA's and nginx's own paths (validateSlug in backend/graph/page_helpers.go).
*
* An adminOnly page answers null to anyone else, so to them it is simply a
* 404.
*/
import { computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { gql } from "@/graphql";
import { useAuthStore } from "@/stores/auth";
import { PAGE_FIELDS, usePagesStore } from "@/stores/pages";
import BoxCanvas from "@/views/home3/BoxCanvas.vue";
import NotFound from "@/views/404/404.vue";
import PageForm from "./PageForm.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const pages = usePagesStore();
const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
// pathMatch is the path split on "/"; a trailing slash leaves an empty last
// part.
const slug = computed(() => {
const parts = route.params.pathMatch;
return (Array.isArray(parts) ? parts : [parts]).filter(Boolean).join("/");
});
const page = ref(null);
const state = ref("loading"); // loading | found | missing | error
async function load() {
const wanted = slug.value;
state.value = "loading";
try {
const data = await gql(`query Page($slug: String!) { page(slug: $slug) { ${PAGE_FIELDS} } }`, {
slug: wanted,
});
if (wanted !== slug.value) return; // navigated on while it loaded
page.value = data.page;
state.value = data.page ? "found" : "missing";
} catch {
if (wanted === slug.value) state.value = "error";
}
}
// The session matters too: signing in may reveal an adminOnly page.
watch([slug, isAdmin], load, { immediate: true });
auth.ensureLoaded();
// ---- Page settings (admin) -----------------------------------------------
const settingsOpen = ref(false);
const draft = ref({ title: "", slug: "", adminOnly: false });
const settingsError = ref("");
const deleteConfirmationOpen = ref(false);
function openSettings() {
draft.value = { title: page.value.title, slug: page.value.slug, adminOnly: page.value.adminOnly };
settingsError.value = "";
settingsOpen.value = !settingsOpen.value;
}
async function saveSettings() {
settingsError.value = "";
try {
const updated = await pages.update(page.value.id, {
title: draft.value.title.trim(),
slug: draft.value.slug.trim().replace(/^\/+|\/+$/g, ""),
adminOnly: draft.value.adminOnly,
});
settingsOpen.value = false;
if (updated.slug !== page.value.slug) router.replace(`/${updated.slug}`);
else page.value = updated;
} catch (err) {
settingsError.value = err?.message || "Failed to save";
}
}
async function deletePage() {
deleteConfirmationOpen.value = true;
}
async function confirmDeletePage() {
deleteConfirmationOpen.value = false;
try {
await pages.remove(page.value.id);
router.push("/");
} catch (err) {
settingsError.value = err?.message || "Failed to delete";
}
}
</script>
<template>
<main v-if="state === 'found'" class="canvas-page">
<BoxCanvas :key="page.slug" :page="page.slug">
<template #admin-bar>
<button type="button" class="bar-btn" :class="{ on: settingsOpen }" @click="openSettings">
Page settings
</button>
<span v-if="page.adminOnly" class="text-tertiary" title="Only admins can see this page">🔒 admin only</span>
</template>
</BoxCanvas>
<form v-if="settingsOpen" class="settings bdr-2 bg-surface" @submit.prevent="saveSettings">
<label>Title <input v-model="draft.title" type="text" required /></label>
<label>Address <input v-model="draft.slug" type="text" required /></label>
<label class="check"><input v-model="draft.adminOnly" type="checkbox" /> Only admins can see this page</label>
<div class="flex gap-2">
<button type="submit" class="bar-btn">Save</button>
<button type="button" class="bar-btn" @click="settingsOpen = false">Cancel</button>
<button type="button" class="bar-btn danger" @click="deletePage">Delete page</button>
</div>
<p v-if="settingsError" class="text-tertiary">{{ settingsError }}</p>
</form>
</main>
<p v-else-if="state === 'error'" class="state">Couldn't load this page.</p>
<template v-else-if="state === 'missing'">
<section v-if="isAdmin" class="create bdr-2 bg-surface">
<h3>No page here yet — make one?</h3>
<PageForm :slug="slug" @created="load" />
</section>
<NotFound />
</template>
<ConfirmDialog
v-if="deleteConfirmationOpen"
v-model="deleteConfirmationOpen"
title="Delete page"
:message="`Delete the page “${page.title}” and everything on it?`"
confirm-label="Delete"
@confirm="confirmDeletePage"
/>
</template>
<style scoped>
.canvas-page {
width: 100%;
min-height: 100%;
box-sizing: border-box;
padding: 10px 16px;
}
.state {
text-align: center;
color: var(--color-muted);
}
.bar-btn {
padding: 0.25rem 0.75rem;
color: var(--color-primary);
background: var(--color-link-bg);
border: 2px solid var(--color-quaternary);
font-family: var(--font-heading);
font-size: 1.1rem;
letter-spacing: 0.025em;
cursor: pointer;
}
.bar-btn:hover,
.bar-btn.on {
border-color: var(--color-primary);
}
.bar-btn.danger:hover {
border-color: var(--color-tertiary);
color: var(--color-tertiary);
}
.settings,
.create {
display: flex;
flex-direction: column;
gap: 0.5rem;
max-width: 420px;
margin: 0 auto 10px;
padding: 0.75rem;
}
.settings {
position: fixed;
top: 80px;
left: 16px;
z-index: 65;
}
.settings label {
display: flex;
flex-direction: column;
gap: 2px;
color: var(--color-muted);
}
.settings label.check {
flex-direction: row;
align-items: center;
gap: 0.4rem;
}
.settings label.check input {
width: auto;
}
</style>
+101
View File
@@ -0,0 +1,101 @@
<script setup>
/**
* Create a canvas page: its address, title, a starting layout from
* pageStarters.js, and whether only admins may see it. On success it opens
* the new page and emits `created`. Used on the admin panel's Pages tab
* (twice: any page, and a shrine under /shrines/) and on the 404 an admin sees
* at an address that has no page yet.
*/
import { ref } from "vue";
import { useRouter } from "vue-router";
import Button from "@/components/input/Button.vue";
import { usePagesStore } from "@/stores/pages";
import { useBoxesStore } from "@/stores/boxes";
import { STARTERS } from "./pageStarters";
const props = defineProps({
// Pre-filled address, e.g. the path of the 404 being looked at.
slug: { type: String, default: "" },
// Fixed leading part of the address, e.g. "shrines/" for a new shrine.
prefix: { type: String, default: "" },
starter: { type: String, default: "blank" },
placeholder: { type: String, default: "address, e.g. shrines/evangelion" },
submitLabel: { type: String, default: "Create page" },
});
const emit = defineEmits(["created"]);
const router = useRouter();
const pages = usePagesStore();
const slug = ref(props.slug);
const title = ref("");
const starter = ref(props.starter);
const adminOnly = ref(false);
const busy = ref(false);
const error = ref("");
async function submit() {
const fullSlug = props.prefix + slug.value.trim().replace(/^\/+|\/+$/g, "");
if (!title.value.trim()) {
error.value = "Title is required";
return;
}
error.value = "";
busy.value = true;
try {
const page = await pages.create({ slug: fullSlug, title: title.value.trim(), adminOnly: adminOnly.value });
// Page first, then its boxes: a starter that fails halfway leaves a page
// with some boxes, which is easy to finish by hand, rather than boxes
// under an address with no page.
const boxes = useBoxesStore(page.slug);
for (const box of STARTERS.find((s) => s.id === starter.value).boxes(page.title)) {
await boxes.create(box);
}
// On the 404 of the address just created the push is a no-op, since the
// route is unchanged; `created` is what tells that view to reload.
await router.push(`/${page.slug}`);
emit("created", page);
} catch (err) {
error.value = err?.message || "Failed to create the page";
} finally {
busy.value = false;
}
}
</script>
<template>
<form class="page-form flex flex-col gap-1" @submit.prevent="submit">
<label class="flex items-center gap-1">
<span class="text-muted">/{{ prefix }}</span>
<input v-model="slug" type="text" :placeholder="placeholder" required class="flex-1" />
</label>
<input v-model="title" type="text" placeholder="Title (required)" />
<select v-model="starter">
<option v-for="s in STARTERS" :key="s.id" :value="s.id">Start from: {{ s.label }}</option>
</select>
<label class="check">
<input v-model="adminOnly" type="checkbox" />
Only admins can see this page
</label>
<Button type="submit" :disabled="busy">{{ busy ? "Creating…" : submitLabel }}</Button>
<p v-if="error" class="text-tertiary">{{ error }}</p>
</form>
</template>
<style scoped>
.page-form select {
padding: 0.5rem;
color: var(--color-primary);
background: var(--color-surface-deep);
border: 1px solid var(--color-primary);
}
.check {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--color-secondary);
}
.check input {
width: auto;
}
</style>
+32
View File
@@ -0,0 +1,32 @@
/**
* Starting layouts for a new canvas page, offered when one is created
* (PageForm.vue). Each `boxes(title)` returns box inputs for
* stores/boxes.js — without `page`, which the store adds. Everything is an
* ordinary box afterwards: move it, edit it, delete it.
*/
const html = (title, body, geom, extra = {}) => ({ kind: "html", title, html: body, ...geom, ...extra });
function notes() {
const note = (text, x, y) =>
html(
"Note",
`<style>
body { padding: 0; }
.note { box-sizing: border-box; height: 100%; padding: .75rem 1rem; background: #f6e27a;
color: #2b2610; box-shadow: 2px 3px 0 rgba(0, 0, 0, .35); overflow: auto; }
.note h3 { margin: 0 0 .3rem; color: inherit; }
</style>
<div class="note"><h3>${text}</h3><ul><li>…</li></ul></div>`,
{ x, y, w: 260, h: 220 },
{ framed: false, adminOnly: true },
);
return [note("To do", 40, 40), note("Ideas", 330, 40), note("Bugs", 620, 40)].map((box, i) => ({
z: i + 1,
...box,
}));
}
export const STARTERS = [
{ id: "blank", label: "Blank", boxes: () => [] },
{ id: "notes", label: "Notes board (admin-only notes)", boxes: notes },
];
+5 -1
View File
@@ -1,6 +1,10 @@
<script setup>
/**
* Route `/stp` — the personal home page: an A4-shaped widget grid flanked by two
* STATUS: legacy — no route points here. `/stp` is now views/home3/Home3.vue,
* the admin-editable box canvas; views/home3/defaultLayout.js is this page's
* arrangement redrawn as boxes. Kept for reference.
*
* Was route `/stp` — the personal home page: an A4-shaped widget grid flanked by two
* sidebars.
*
* Layout is entirely CSS `grid-template-areas`: each child gets a `grid-area`
+21 -2
View File
@@ -6,13 +6,16 @@
* the `loggedIn` watcher covers someone who signs in while the page is open, and
* both check `!loaded && !loading` so the two paths can't fire two requests.
*/
import { computed, onMounted, watch } from "vue";
import { computed, onMounted, ref, watch } from "vue";
import { usePlacesStore } from "@/stores/places";
import { useAuthStore } from "@/stores/auth";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const places = usePlacesStore();
const auth = useAuthStore();
const loggedIn = computed(() => auth.loggedIn);
const removeTarget = ref(null);
const confirmationOpen = ref(false);
// Two entry points, one fetch: onMounted covers an already-signed-in visitor,
// the watcher covers signing in with the page already open. The
@@ -36,7 +39,14 @@ async function toggleDone(place) {
async function remove(place) {
if (!loggedIn.value) return;
if (!confirm(`Delete "${place.title}"?`)) return;
removeTarget.value = place;
confirmationOpen.value = true;
}
async function confirmRemove() {
const place = removeTarget.value;
removeTarget.value = null;
if (!place) return;
try {
await places.remove(place.id);
} catch (err) {
@@ -98,6 +108,15 @@ async function remove(place) {
</tbody>
</table>
</div>
<ConfirmDialog
v-if="removeTarget"
v-model="confirmationOpen"
title="Delete place"
:message="`Delete ${removeTarget.title}?`"
confirm-label="Delete"
@confirm="confirmRemove"
@cancel="removeTarget = null"
/>
</template>
<style scoped>
+78 -86
View File
@@ -20,20 +20,17 @@ import Link from "@/components/text/Link.vue";
import { shuffleArray } from "@/js/utils.js";
let srcs = [
"/img/stamps/portal.gif",
"/img/stamps/miku.gif",
"/img/stamps/utau.gif",
"/img/stamps/teto.webp",
"/img/stamps/3ds.jpg",
"/img/stamps/fry.png",
"/img/stamps/ai.png",
"/img/stamps/rei.png",
"/img/stamps/tetris.gif",
"/img/stamps/tf2.gif",
"/img/stamps/demo.gif",
"/img/stamps/demo.gif",
"/img/stamps/demo.gif",
"/img/stamps/demo.gif",
"/img/stamps/portal.gif",
"/img/stamps/miku.gif",
"/img/stamps/utau.gif",
"/img/stamps/teto.webp",
"/img/stamps/3ds.jpg",
"/img/stamps/fry.png",
"/img/stamps/ai.png",
"/img/stamps/rei.png",
"/img/stamps/tetris.gif",
"/img/stamps/tf2.gif",
"/img/stamps/demo.gif",
];
// Shuffled once at module evaluation, so the wall is ordered differently each
// page load but stable while the widget is mounted. Mutates in place.
@@ -41,17 +38,12 @@ shuffleArray(srcs);
// The two linked stamps stay first; the shuffled local ones follow.
const stamps = [
{
src: "https://www.adam-french.co.uk/img/stamps/mine.gif",
alt: "adam-french.co.uk",
href: "https://www.adam-french.co.uk",
},
{
src: "https://jacobbarron.xyz/Banneh.gif",
alt: "jacobbarron.xyz",
href: "https://jacobbarron.xyz",
},
...srcs.map((src) => ({ src, alt: src.split("/").pop().split(".")[0] })),
{
src: "https://www.adam-french.co.uk/img/stamps/mine.gif",
alt: "adam-french.co.uk",
href: "https://www.adam-french.co.uk",
},
...srcs.map((src) => ({ src, alt: src.split("/").pop().split(".")[0] })),
];
// Must match the grid track sizes in the <style> block.
@@ -66,10 +58,10 @@ const rows = ref(4);
// more slots than there are stamps — a ragged last row would leave a blank
// strip drifting into view.
const cells = computed(() =>
Array.from(
{ length: cols.value * rows.value },
(_, i) => stamps[i % stamps.length],
),
Array.from(
{ length: cols.value * rows.value },
(_, i) => stamps[i % stamps.length],
),
);
/**
@@ -78,14 +70,14 @@ const cells = computed(() =>
* Rows are also raised, if need be, until every stamp appears at least once.
*/
function fitWall() {
const el = touchscreen.value?.$el;
if (!el) return;
const el = touchscreen.value?.$el;
if (!el) return;
cols.value = Math.ceil(el.clientWidth / STAMP_W) + 1;
rows.value = Math.max(
Math.ceil(el.clientHeight / STAMP_H) + 1,
Math.ceil(stamps.length / cols.value),
);
cols.value = Math.ceil(el.clientWidth / STAMP_W) + 1;
rows.value = Math.max(
Math.ceil(el.clientHeight / STAMP_H) + 1,
Math.ceil(stamps.length / cols.value),
);
}
let resizeObserver = null;
@@ -103,79 +95,79 @@ let dy = 0.12;
* because fitWall changes the bounds whenever the cell is resized.
*/
function bounce() {
const el = touchscreen.value?.$el;
if (!el) return;
const el = touchscreen.value?.$el;
if (!el) return;
const maxX = el.scrollWidth - el.clientWidth;
const maxY = el.scrollHeight - el.clientHeight;
const maxX = el.scrollWidth - el.clientWidth;
const maxY = el.scrollHeight - el.clientHeight;
if (maxX > 0) {
posX += dx;
if (posX <= 0) {
posX = 0;
dx = -dx;
} else if (posX >= maxX) {
posX = maxX;
dx = -dx;
if (maxX > 0) {
posX += dx;
if (posX <= 0) {
posX = 0;
dx = -dx;
} else if (posX >= maxX) {
posX = maxX;
dx = -dx;
}
el.scrollLeft = posX;
}
el.scrollLeft = posX;
}
if (maxY > 0) {
posY += dy;
if (posY <= 0) {
posY = 0;
dy = -dy;
} else if (posY >= maxY) {
posY = maxY;
dy = -dy;
if (maxY > 0) {
posY += dy;
if (posY <= 0) {
posY = 0;
dy = -dy;
} else if (posY >= maxY) {
posY = maxY;
dy = -dy;
}
el.scrollTop = posY;
}
el.scrollTop = posY;
}
animId = requestAnimationFrame(bounce);
animId = requestAnimationFrame(bounce);
}
onMounted(() => {
fitWall();
// The cell's size follows the home grid's breakpoints (and the scrollbars
// appearing inside it), not just window resizes, so observe the element.
resizeObserver = new ResizeObserver(fitWall);
resizeObserver.observe(touchscreen.value.$el);
animId = requestAnimationFrame(bounce);
fitWall();
// The cell's size follows the home grid's breakpoints (and the scrollbars
// appearing inside it), not just window resizes, so observe the element.
resizeObserver = new ResizeObserver(fitWall);
resizeObserver.observe(touchscreen.value.$el);
animId = requestAnimationFrame(bounce);
});
onUnmounted(() => {
if (animId) cancelAnimationFrame(animId);
resizeObserver?.disconnect();
if (animId) cancelAnimationFrame(animId);
resizeObserver?.disconnect();
});
</script>
<template>
<Touchscreen ref="touchscreen">
<div class="wall" :style="{ '--cols': cols }">
<template v-for="(stamp, i) in cells" :key="i">
<Link v-if="stamp.href" bare :href="stamp.href">
<img :src="stamp.src" :alt="stamp.alt" />
</Link>
<img v-else :src="stamp.src" :alt="stamp.alt" loading="lazy" />
</template>
</div>
</Touchscreen>
<Touchscreen ref="touchscreen">
<div class="wall" :style="{ '--cols': cols }">
<template v-for="(stamp, i) in cells" :key="i">
<Link v-if="stamp.href" bare :href="stamp.href">
<img :src="stamp.src" :alt="stamp.alt" />
</Link>
<img v-else :src="stamp.src" :alt="stamp.alt" loading="lazy" />
</template>
</div>
</Touchscreen>
</template>
<style scoped>
img {
display: block;
width: 89px;
height: 59px;
display: block;
width: 89px;
height: 59px;
}
/* Fixed tracks rather than flex-wrap: the wall's size comes from --cols (set
by fitWall), never from how much room the cell happens to have. */
.wall {
display: grid;
grid-template-columns: repeat(var(--cols), 89px);
grid-auto-rows: 59px;
width: max-content;
display: grid;
grid-template-columns: repeat(var(--cols), 89px);
grid-auto-rows: 59px;
width: max-content;
}
</style>
+5 -1
View File
@@ -1,6 +1,10 @@
<script setup>
/**
* Route `/shrines/demoman` — a wall of TF2 Demoman clips via <VideoTable>.
* STATUS: no route points here — removed so /shrines/demoman can be made
* again as a canvas page (views/canvas/CanvasPage.vue). The clips are still
* in public/img/demoman/.
*
* Was route `/shrines/demoman` — a wall of TF2 Demoman clips via <VideoTable>.
*/
import VideoTable from "@/components/util/VideoTable.vue";
import Link from "@/components/text/Link.vue";

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