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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:51:29 +01:00
131 changed files with 13077 additions and 1129 deletions
+171
View File
@@ -0,0 +1,171 @@
# =============================================================================
# .env.dev — COMMITTED settings for the local dev stack. EVERY VALUE IS A DUMMY.
#
# Use it by copying it over the gitignored .env, then starting the dev stack:
# cp .env.dev .env
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
# It has to BE .env, not be passed with --env-file: several services declare
# `env_file: ./.env`, which compose reads regardless (see check-compose in the
# Makefile).
#
# Nothing here is secret and nothing here may ever be used in production: the
# passwords and signing keys only guard containers on your own machine, and
# every third-party credential is fake, so those integrations fail at the
# provider instead of reaching a real account. The background jobs that would
# act on real accounts are switched off as well.
#
# Keep it in step with .env.example: a new variable goes in both. Settings that
# are not secrets (hosts, ports, timezone) keep .env.example's defaults; values
# a service parses (Garage's hex secrets, Gitea's base64 JWT keys, the S3 key
# id) are dummies in the exact shape it requires, or that service won't start.
#
# The dummy Postgres credentials only work on a database volume created with
# them: an existing dbdata volume keeps whatever password it was initialised
# with. Only POSTGRES_DB is created on a fresh volume; the gitea, jobs and
# tracker databases and roles still have to be created by hand (.env.example).
# =============================================================================
# --- Postgres ----------------------------------------------------------------
POSTGRES_USER=dev
POSTGRES_PASSWORD=dev-postgres-password
POSTGRES_DB=site
POSTGRES_PORT=5432
POSTGRES_HOST=db
POSTGRES_JOBS_DB=jobs
POSTGRES_JOBS_USER=jobs
POSTGRES_JOBS_PASSWORD=dev-jobs-password
POSTGRES_TRACKER_DB=tracker
POSTGRES_TRACKER_USER=tracker
POSTGRES_TRACKER_PASSWORD=dev-tracker-password
# --- Gitea -------------------------------------------------------------------
# The two JWT secrets must decode as base64url of 32 bytes; these decode to
# the text "dev-only-not-a-secret-0123456789".
GITEA_HOST=gitea
GITEA_PORT=3000
GITEA_INTERNAL_TOKEN=dev-gitea-internal-token
GITEA_LFS_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk
GITEA_OAUTH2_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk
POSTGRES_GITEA_DB=gitea
# Blank means localhost.
GITEA_SSH_DOMAIN=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is not part of the compose stack; nothing in dev reads these.
GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=dev-runner
GITEA_RUNNER_REGISTRATION_TOKEN=dev-dummy-runner-token
# --- Email ingest (job tracker) -----------------------------------------------
# Sync is off; the credentials are fake, so a manual sign-in fails at Microsoft.
EMAIL_BACKEND=graph
MSGRAPH_CLIENT_ID=00000000-0000-0000-0000-000000000000
MSGRAPH_CLIENT_SECRET=dev-dummy-msgraph-secret
MSGRAPH_TENANT_ID=consumers
MSGRAPH_REDIRECT_URI=http://localhost/jobs/api/email/callback
IMAP_HOST=imap.invalid
IMAP_PORT=993
IMAP_EMAIL=[email protected]
IMAP_PASSWORD=dev-dummy-imap-password
EMAIL_SYNC_INTERVAL=
EMAIL_SYNC_ENABLED=false
# --- Job leads (job tracker) --------------------------------------------------
# The timer is off; "Check now" still works for the keyless board sources.
JOB_LEADS_ENABLED=false
JOB_LEADS_INTERVAL=
ADZUNA_APP_ID=dev-dummy-adzuna-id
ADZUNA_APP_KEY=dev-dummy-adzuna-key
REED_API_KEY=dev-dummy-reed-key
# --- SilverBullet (notes) ---------------------------------------------------
SILVERBULLET_HOST=silverbullet
SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public
SILVERBULLET_PUBLIC_PORT=3000
SILVERBULLET_GIT_INTERVAL=300
# --- Go backend --------------------------------------------------------------
# Must be at least 32 bytes or the backend refuses to start.
BACKEND_PORT=8080
BACKEND_HOST=backend
BACKEND_SECRET=dev-only-jwt-signing-secret-not-for-production
BACKEND_ENDPOINT=/api
# --- Obsidian vault ----------------------------------------------------------
# A checked-in, mostly-gitignored folder, so the bind mount always has a
# source owned by you; a missing path would be created by Docker as root and
# SilverBullet (uid 1000) could not write to it. It is not a git repository,
# so silverbullet-git logs that and idles instead of pushing anywhere.
OBSIDIAN_DIR=./dev/notes
# --- Spotify -----------------------------------------------------------------
# docker-compose.dev.yml overrides the redirect URI.
SPOTIFY_CLIENT_ID=dev-dummy-spotify-client-id
SPOTIFY_CLIENT_SECRET=dev-dummy-spotify-client-secret
SPOTIFY_REDIRECT_URI=
SPOTIFY_AUTH_STATE=dev-dummy-spotify-state
# --- Icecast / liquidsoap radio ----------------------------------------------
ICECAST_SOURCE_PASSWORD=dev-icecast-source-password
ICECAST_RELAY_PASSWORD=dev-icecast-relay-password
ICECAST_ADMIN_USER=admin
ICECAST_ADMIN_PASSWORD=dev-icecast-admin-password
ICECAST_HOST=icecast2
ICECAST_PORT=8000
ICECAST_MOUNT=/stream
LIQUIDSOAP_HARBOR_MOUNT=/live
LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ----------------------------------------------------------
# DOMAIN is also the auth cookie's domain, so it must be the host the browser
# is on. certbot is disabled in dev, so EMAIL is never used.
DOMAIN=localhost
EMAIL=[email protected]
# --- Cloudflare Tunnel -------------------------------------------------------
# cloudflared is disabled in dev and certbot with it.
CLOUDFLARE_TUNNEL_TOKEN=dev-dummy-tunnel-token
CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token
# --- Third-party API keys ----------------------------------------------------
# Fake keys: Claude calls (rowing photos, job posting reader) get a 401 from
# Anthropic, and the Steam widget gets nothing back.
CLAUDE_API_KEY=sk-ant-dev-dummy-key
CLAUDE_MODEL=
STEAM_API_KEY=DEVDUMMYSTEAMKEY
STEAM_ID=76561190000000000
# --- Development-only switch -------------------------------------------------
SEED_DB=true
# --- Python FastAPI service (/py/) -------------------------------------------
PYTHON_HOST=python
PYTHON_PORT=8000
# --- Job tracker (/jobs/) -----------------------------------------------------
JOBS_IMAGE_TAG=
# --- USACO site (/usaco/) ------------------------------------------------------
USACO_IMAGE_TAG=
USACO_GIT_TOKEN=dev-dummy-gitea-token
USACO_WEBHOOK_SECRET=dev-dummy-webhook-secret
# --- Activity tracker (/tracker/) --------------------------------------------
ACTIVITY_TRACKER_IMAGE_TAG=
TRACKER_TZ=Europe/London
TFL_APP_KEY=dev-dummy-tfl-key
# --- Garage object store (public /uploads/) -----------------------------------
# Shapes Garage enforces: 64 hex for the RPC secret, "GK" + 24 hex for the key
# id, 64 hex for the secret. Uploads fall back to the `uploads` volume until
# garage/bootstrap.sh has imported this key and created the bucket.
GARAGE_RPC_SECRET=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
GARAGE_ADMIN_TOKEN=dev-garage-admin-token
S3_ACCESS_KEY_ID=GK0123456789abcdef01234567
S3_SECRET_ACCESS_KEY=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210
S3_ENDPOINT=http://garage:3900
S3_REGION=garage
S3_BUCKET=uploads
GARAGE_CAPACITY=1G
+45 -4
View File
@@ -20,7 +20,8 @@
# docker compose up -d <service>.
#
# ADDING A VARIABLE
# If the python or jobs service reads it, add it to that service's
# Add it to .env.dev as well, with a dummy value, so the dev stack keeps
# starting. If the python or jobs service reads it, add it to that service's
# `environment:` list in docker-compose.yml too, or the container never
# receives it.
#
@@ -204,9 +205,10 @@ CLOUDFLARE_TUNNEL_TOKEN=
CLOUDFLARE_DNS_API_TOKEN=
# --- Third-party API keys (backend) ------------------------------------------
# CLAUDE_API_KEY is used by the python service, which makes every Claude call
# in the stack: the rowing photo reader, the job posting reader and the email
# pipeline's classifier. The backend no longer calls Claude itself.
# CLAUDE_API_KEY is used by the python service, which makes the main site's
# Claude calls: the rowing photo reader, the job posting reader and the email
# pipeline's classifier. The backend no longer calls Claude itself. The jobs
# and usaco containers get the same key for their own calls.
CLAUDE_API_KEY=
# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5
# (the default when blank) or claude-opus-5-5. Recreate the python service
@@ -235,6 +237,10 @@ JOBS_IMAGE_TAG=
# a commit sha to pin. Changing it needs
# `docker compose pull usaco && docker compose up -d usaco`.
USACO_IMAGE_TAG=
# The same for its code runner (usaco-runner), which the usaco repo's CI
# publishes and rolls alongside it. It takes no other settings: it has no
# secrets by design.
USACO_RUNNER_IMAGE_TAG=
# Gitea access token (repository: read and write on adamf/usaco). The site
# clones with it and pushes the admin's edits back.
USACO_GIT_TOKEN=
@@ -242,6 +248,29 @@ USACO_GIT_TOKEN=
# (http://usaco:8080/usaco/api/hooks/gitea). Blank turns the hook off and
# the site only pulls every 10 minutes. Generate with `openssl rand -hex 32`.
USACO_WEBHOOK_SECRET=
# Model for the problem explanations (the admin's Explain button), separate
# from CLAUDE_MODEL because those are long, considered answers rather than
# extraction. Blank means claude-opus-5-5. The key is CLAUDE_API_KEY above;
# without it the button is off and the rest of the site works.
USACO_CLAUDE_MODEL=
# Monthly cap on the USACO site's estimated Claude spend, in dollars (e.g.
# 20). Once a calendar month (UTC) reaches it, new Explain/review/concept/
# evaluate jobs are refused until the 1st. Blank: no cap; the spend is still
# shown on the site's stats page to the admin.
USACO_CLAUDE_MONTHLY_BUDGET=
# Recording reviews (the admin uploads themselves explaining a solution).
# Claude cannot take audio, so this OpenAI key transcribes it (whisper-1,
# about $0.006 a minute). Blank turns reviews off.
USACO_OPENAI_API_KEY=
# Optional: keep the recordings for playback in a PRIVATE Garage bucket,
# never `uploads` (that one is served publicly at /uploads/). Its own key,
# same shapes as S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY above. With the
# key blank the recordings are thrown away once transcribed. One-off setup:
# docker compose exec -T garage /garage bucket create usaco-audio
# docker compose exec -T garage /garage key import -n usaco-site --yes "$USACO_S3_ACCESS_KEY_ID" "$USACO_S3_SECRET_ACCESS_KEY"
# docker compose exec -T garage /garage bucket allow --read --write usaco-audio --key "$USACO_S3_ACCESS_KEY_ID"
USACO_S3_ACCESS_KEY_ID=
USACO_S3_SECRET_ACCESS_KEY=
# --- Activity tracker (/tracker/) --------------------------------------------
# An image built and published by the ccp repo's CI. Blank runs :latest; set a
@@ -251,6 +280,18 @@ ACTIVITY_TRACKER_IMAGE_TAG=
# IANA timezone that decides where a "day" starts in daily summaries. Blank is UTC.
TRACKER_TZ=Europe/London
# --- Receipt printer (/receipt/) ---------------------------------------------
# Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi,
# which reaches the printer over the home LAN, and nginx proxies to it over
# Tailscale.
# host:port of that server, by Tailscale IP. Blank points nowhere and
# /receipt/ answers "offline".
RECEIPT_WEB_UPSTREAM=100.107.152.119:8765
# Shared secret nginx adds as X-Receipt-Token; the same value as
# RECEIPT_WEB_TOKEN in stppi's ~/.config/receipt-web.env. Generate with
# `openssl rand -hex 32`. Changing it needs `docker compose up -d nginx`.
RECEIPT_WEB_TOKEN=
# TfL Unified API key (500 req/min); used by the Python hotel finder
TFL_APP_KEY=
+4 -1
View File
@@ -2,7 +2,10 @@ name: Weekly Maintenance
on:
schedule:
- cron: "0 1 * * 0"
# 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and
# every container, so it runs when nobody is likely to be mid-edit;
# 01:00 kept catching late-night SilverBullet saves.
- cron: "0 5 * * 0"
workflow_dispatch:
jobs:
+71
View File
@@ -0,0 +1,71 @@
# =============================================================================
# renovate.yaml — weekly dependency-update PRs, opened against this repo.
#
# Renovate stands in for Dependabot, which does not exist outside GitHub. What
# it updates is configured in /renovate.json5; this file is only how it runs.
#
# HOW IT RUNS
# The same host-mode act_runner as deploy.yaml, so (as there) nothing but
# git and docker is assumed on the host: Renovate runs from its own image.
# --network host lets the container reach Gitea on localhost:3000, the port
# the runner itself registers against, so this keeps working while nginx or
# the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same reason:
# without it Renovate clones from the URL Gitea advertises, which is
# ROOT_URL — the public https://…/gitea/ path.
#
# WHAT HAPPENS AFTER
# Each update is pushed as a renovate/* branch, which triggers deploy.yaml's
# `test` job like any other push (and never its `deploy` job, which is
# main-only). Nothing is merged automatically: merging is deploying.
# Renovate also keeps a "Dependency Dashboard" issue open listing everything
# pending; ticking a box there is picked up on the next run, so run this
# workflow by hand (workflow_dispatch) to act on it sooner.
#
# THE TOKEN
# RENOVATE_TOKEN is a repo Actions secret: a Gitea access token for the
# account the PRs come from (a dedicated `renovate` user with write access
# to this repo, ideally), scopes read:user, read:organization,
# write:repository, write:issue.
# RENOVATE_GITHUB_COM_TOKEN is optional: any github.com token with no
# scopes. Without it Renovate is rate-limited by GitHub and leaves release
# notes out of the PRs. (Gitea refuses secret names starting GITHUB_, hence
# the prefix.) Both reach the container as `-e NAME` with no value, so they
# are copied from this step's env and never appear in the process list.
#
# The renovate/renovate:44 tag floats within the major (--pull always picks
# up the newest 44.x each week); Renovate itself proposes the next major via
# the regex manager in renovate.json5.
# =============================================================================
name: Renovate
on:
schedule:
# 04:00 UTC Monday: clear of the Sunday 05:00 maintenance rebuild, and
# done before the working week so the PRs are waiting.
- cron: "0 4 * * 1"
workflow_dispatch:
jobs:
renovate:
runs-on: self-hosted
steps:
- name: Run Renovate
shell: bash
env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
GITHUB_COM_TOKEN: ${{ secrets.RENOVATE_GITHUB_COM_TOKEN }}
run: |
set -eu
if [ -z "$RENOVATE_TOKEN" ]; then
echo "The RENOVATE_TOKEN Actions secret is not set (repo Settings -> Actions -> Secrets)."
exit 1
fi
docker run --rm --pull always --network host \
-e RENOVATE_PLATFORM=gitea \
-e RENOVATE_ENDPOINT=http://localhost:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/web_server \
-e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \
renovate/renovate:44
+4
View File
@@ -76,3 +76,7 @@ TODO-NEXT.md
# SilverBullet git deploy key (key material only; the README stays)
silverbullet/ssh/*
!silverbullet/ssh/README.md
# Dev notes vault (OBSIDIAN_DIR in .env.dev); only the README is tracked
dev/notes/*
!dev/notes/README.md
.gstack/
+10 -8
View File
@@ -10,15 +10,16 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
make check
```
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing.
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it.
### Full stack (dev mode, HTTP only)
```
cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
### Full stack (production, HTTPS)
@@ -62,7 +63,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. 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.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public.
@@ -75,7 +76,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
- `graph/generated.go` — auto-generated by gqlgen, do not edit
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background)
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout, Component, CoverLetter, CoverSnippet)
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more
@@ -84,8 +85,8 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
- `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages. `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/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components, coverLetters, coverSnippets. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `Page`s (e.g. shrines, and `/stp`, the `Page` with slug `stp`) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. A `Layout` is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). A `Component` is a saved, named HTML box: "+ New box" places copies of it, and the canvas's Components button also places it *linked* (`Box.componentId`), so the box shows the component's HTML and editing it edits every linked box; the built-in starters in `templates.js` become components through that panel's "Import built-ins". Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md`
- `src/components/` — reusable UI components
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
@@ -95,8 +96,9 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. nginx's *permission gate* (`set $auth_permission <key>; auth_request /internal/auth/validate;`, see `nginx/nginx_routes.conf.template`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its location from the admin gate to the permission gate. `/auth/validate-admin` and the admin gate are unchanged.
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
- **Environment variables**: every variable goes in `.env.example`. 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.
- **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor.
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
@@ -115,4 +117,4 @@ Each area has its own README with the detail that doesn't belong here:
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
- **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating.
- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead — e.g. `views/unused/CoverLetters.vue` is actually live on `/cv`.
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof.
+38
View File
@@ -68,6 +68,7 @@ backend icecast2 gitea sb sb-pub python | |
| certbot | `certbot` | — | — | no |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no |
| receipt printer (`receipt serve`, adamf/receipt_maker) | — (runs on **stppi**, not in this stack) | 8765 on stppi's Tailscale IP (`RECEIPT_WEB_UPSTREAM`) | `/receipt/`, prefix stripped (permission-gated on `receipt` by nginx `auth_request`; nginx adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy nginx) | `autoheal` | — (no network) | none; reads the Docker socket | no |
| garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no |
@@ -97,6 +98,11 @@ in one step — never change one without the other.**
job and activity trackers also check the session themselves. Their carve-outs, which a session
cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps:
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`.
- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead, which also lets in a
non-admin account granted `receipt` in the admin panel's Manage Users tab. Not signed in
redirects to the login; signed in without the grant redirects to `/no-access`. To let a
friend print: create their user (admin panel → User), then tick "Receipt printer" for them
under Manage Users. Revoking is the same tick, and applies on their next request.
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of
nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
@@ -162,9 +168,18 @@ validation — run it before pushing, since a red `test` job blocks the deploy.
### Development
```
cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
`.env.dev` is committed and holds only dummy values, so the stack starts
without any real credential and cannot reach a real account. Features that
need one fail at the provider, which is the point. It must become `.env`
rather than be passed with `--env-file`, because several services read
`env_file: ./.env` directly. Its Postgres passwords only match a `dbdata`
volume created with them, and as in production only `POSTGRES_DB` is created
automatically.
The override layer changes five services and disables one:
- **vue** — `npm run dev` instead of a one-shot build; `./vue` is bind-mounted
@@ -260,6 +275,17 @@ against a name it covers. `https://nginx` would fail that check and need No
TLS Verify. The flip side: **an expired certificate now takes the tunnel down
with a 502**, which is why renewal over DNS-01 (step 5) matters.
An alias only exists while nginx is running, so cloudflared also pins both
names to nginx's fixed address (`172.28.255.251`) with `extra_hosts`. Without
that, while nginx is stopped for a deploy or the weekly maintenance, the name
falls through to public DNS, resolves to Cloudflare itself, and visitors see
Cloudflare error 1000 instead of a 502.
The aliases have a side effect for anything else on `app-network` that uses
the public name for a port nginx does not serve. `silverbullet-git` pushes to
Gitea's SSH on `<DOMAIN>:2222`, so it maps `<DOMAIN>` to the host gateway
instead, where Gitea publishes that port.
Setup, once:
1. Cloudflare dashboard → the domain must be on Cloudflare DNS.
@@ -605,6 +631,18 @@ against this stack, so it cannot be a container in it. Registration is one-shot
`.runner` is the lasting credential; re-registering needs that file deleted _and_
a fresh token.
**Dependency updates (Renovate).** Dependabot is GitHub-only, so
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday
at 04:00 UTC (or by hand from the Actions tab), configured by
`renovate.json5`. It opens PRs from `renovate/*` branches, which get the
normal `test` job; nothing automerges, because merging to `main` deploys. It
needs a `RENOVATE_TOKEN` repo Actions secret: create a `renovate` Gitea user,
add it to this repo as a collaborator with write access, and mint a token for
it with `read:user`, `read:organization`, `write:repository` and
`write:issue`. `RENOVATE_GITHUB_COM_TOKEN` (any github.com token, no scopes)
is optional and lifts GitHub's rate limit on release-note lookups. The first
run opens a "Dependency Dashboard" issue listing everything pending.
**Go live on the radio:** point a broadcasting client (e.g. butt) at the host's
Tailscale name (not the domain, which resolves to Cloudflare) on
`${LIQUIDSOAP_HARBOR_PORT}` with mount `${LIQUIDSOAP_HARBOR_MOUNT}` and the
+1
View File
@@ -303,6 +303,7 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
Run the full stack over plain HTTP without SSL certificates:
```sh
cp .env.dev .env # committed, dummy values only
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
+15 -1
View File
@@ -64,6 +64,16 @@ graph/ GraphQL layer
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
and will transparently refresh, so returning admins are recognised without a
visible re-login.
- `GET /auth/validate/:permission` is the same for one named permission
(200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
*permission gate*, which lets a non-admin account into one service — the
receipt printer at `/receipt/` — without making it an admin. Grantable keys
are the registry `services.PermissionTypes` (`services/permissions.go`);
a user's grants are `User.Permissions`, set from the admin panel's Manage
Users tab (`setUserPermissions`). Admins pass every permission check. The
check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which
nginx forwards to the gated service as `X-Remote-User`.
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
is revoked server-side, and a token that has already been issued stays valid
until it expires. The same is true of demoting an admin: it takes effect on
@@ -173,6 +183,7 @@ for the things GraphQL cannot do:
| `/auth/*` | cookie handling and the status-code-only admin probe |
| `/spotify/callback` | OAuth providers redirect a *browser* here |
| `/uploads`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
| `/uploads` (GET, admin) | lists the stored files, next to the endpoint that stores them |
| `/notes/*path` | streams a file download, not JSON |
| `/ws` | WebSocket upgrade |
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
@@ -235,7 +246,10 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
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`.
handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind
admin-only `GET /uploads`, for the canvas's upload picker) returns the union
of bucket and disk, allow-listed types only, newest first; it is admin-only
because listing would give away every unguessable URL.
- **notes.go** — path-traversal-safe file lookup for the notes directory.
- **seed.go** — dev-only test data. Creates an admin with the password
`password`, so it must never run in production (`SEED_DB=true` is set only
+34
View File
@@ -34,6 +34,10 @@ models:
resolver: false
deletedAt:
resolver: false
# Not a database model: the fixed registry in services/permissions.go.
PermissionType:
model:
- adam-french.co.uk/backend/services.PermissionType
Post:
model:
- adam-french.co.uk/backend/models.Post
@@ -94,3 +98,33 @@ models:
fields:
deletedAt:
resolver: false
Layout:
model:
- adam-french.co.uk/backend/models.Layout
fields:
deletedAt:
resolver: false
boxCount:
resolver: true
hasBackground:
resolver: true
Component:
model:
- adam-french.co.uk/backend/models.Component
fields:
deletedAt:
resolver: false
uses:
resolver: true
CoverLetter:
model:
- adam-french.co.uk/backend/models.CoverLetter
fields:
deletedAt:
resolver: false
CoverSnippet:
model:
- adam-french.co.uk/backend/models.CoverSnippet
fields:
deletedAt:
resolver: false
+37
View File
@@ -7,6 +7,7 @@ package graph
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
@@ -35,18 +36,40 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
if input.Framed != nil {
box.Framed = *input.Framed
}
if input.Shadow != nil {
box.Shadow = *input.Shadow
}
if input.HideOnMobile != nil {
box.HideOnMobile = *input.HideOnMobile
}
if input.AdminOnly != nil {
box.AdminOnly = *input.AdminOnly
}
// A linked box takes its html from the component, so its own is
// dropped rather than stored as a copy that would quietly go stale.
if input.ComponentID != nil {
id := uint(*input.ComponentID)
exists, err := componentExists(r.Store.DB, id)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.New("there is no such component")
}
box.Kind = "html"
box.Widget = nil
box.HTML = nil
box.ComponentID = &id
}
if err := validateBox(&box); err != nil {
return nil, err
}
if err := r.Store.DB.Create(&box).Error; err != nil {
return nil, err
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
return &box, nil
}
@@ -64,6 +87,11 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
box.Widget = input.Widget
}
if input.HTML != nil {
// A linked box's html is the component's; changing it here would
// only fork a copy. The editor sends it to updateComponent instead.
if box.ComponentID != nil {
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
}
box.HTML = input.HTML
}
if input.Title != nil {
@@ -77,6 +105,9 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
if input.Framed != nil {
box.Framed = *input.Framed
}
if input.Shadow != nil {
box.Shadow = *input.Shadow
}
if input.HideOnMobile != nil {
box.HideOnMobile = *input.HideOnMobile
}
@@ -89,6 +120,9 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
if err := r.Store.DB.Save(&box).Error; err != nil {
return nil, err
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
return &box, nil
}
@@ -127,5 +161,8 @@ func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box,
if err := query.Order("z ASC, id ASC").Find(&boxes).Error; err != nil {
return nil, err
}
if err := fillLinked(r.Store.DB, boxes); err != nil {
return nil, err
}
return ptrs(boxes), nil
}
+25 -1
View File
@@ -6,6 +6,8 @@ package graph
import (
"errors"
"fmt"
"strings"
"adam-french.co.uk/backend/models"
)
@@ -14,6 +16,10 @@ import (
// be grabbed again on the canvas.
const minBoxSize = 40
// maxShadowLen bounds a box's shadow, which is a single CSS value: even a
// stack of a few comma-separated shadows is well under it.
const maxShadowLen = 200
func setInt(dst *int, src *int) {
if src != nil {
*dst = *src
@@ -33,15 +39,33 @@ func validateBox(box *models.Box) error {
return errors.New("a widget box needs a widget name")
}
case "html":
if box.HTML == nil {
// A linked box's html lives on its component (fillLinked).
if box.HTML == nil && box.ComponentID == nil {
return errors.New("an html box needs html")
}
default:
return errors.New(`box kind must be "widget" or "html"`)
}
if box.ComponentID != nil && box.Kind != "html" {
return errors.New("only an html box can be linked to a component")
}
if err := validateShadow(&box.Shadow); err != nil {
return err
}
box.X = max(box.X, 0)
box.Y = max(box.Y, 0)
box.W = max(box.W, minBoxSize)
box.H = max(box.H, minBoxSize)
return nil
}
// validateShadow trims a box-shadow value and bounds its length. The value is
// not parsed: the front end sets it through a style binding, so it can only
// ever be the one property, and an invalid value just draws no shadow.
func validateShadow(shadow *string) error {
*shadow = strings.TrimSpace(*shadow)
if len(*shadow) > maxShadowLen {
return fmt.Errorf("a shadow is at most %d characters", maxShadowLen)
}
return nil
}
+3
View File
@@ -8,6 +8,7 @@ import (
func TestValidateBox(t *testing.T) {
str := func(s string) *string { return &s }
one := uint(1)
for _, c := range []struct {
name string
@@ -20,6 +21,8 @@ func TestValidateBox(t *testing.T) {
{"html with html", models.Box{Page: "stp", Kind: "html", HTML: str("<p>hi</p>")}, false},
{"html with empty html", models.Box{Page: "stp", Kind: "html", HTML: str("")}, false},
{"html without html", models.Box{Page: "stp", Kind: "html"}, true},
{"linked html without html", models.Box{Page: "stp", Kind: "html", ComponentID: &one}, false},
{"linked widget", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), ComponentID: &one}, true},
{"no page", models.Box{Kind: "widget", Widget: str("Chat")}, true},
{"bad page", models.Box{Page: "Shrines/GTO", Kind: "widget", Widget: str("Chat")}, true},
{"unknown kind", models.Box{Page: "stp", Kind: "iframe", HTML: str("x")}, true},
+195
View File
@@ -0,0 +1,195 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// Uses is the resolver for the uses field.
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
// One count per component, which is fine for an admin-only list of a
// handful; soft-deleted boxes are excluded by GORM's default scope.
var count int64
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
return 0, err
}
return int(count), nil
}
// CreateComponent is the resolver for the createComponent field.
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
// Framed defaults to true and the size to 300x200, as for a new box.
name, err := usableComponentName(r.Store.DB, input.Name, 0)
if err != nil {
return nil, err
}
c := models.Component{Name: name, Title: input.Title, HTML: input.HTML, W: 300, H: 200, Framed: true}
setInt(&c.W, input.W)
setInt(&c.H, input.H)
if input.Framed != nil {
c.Framed = *input.Framed
}
if input.Shadow != nil {
c.Shadow = *input.Shadow
}
if input.AdminOnly != nil {
c.AdminOnly = *input.AdminOnly
}
c.W = max(c.W, minBoxSize)
c.H = max(c.H, minBoxSize)
if err := validateShadow(&c.Shadow); err != nil {
return nil, err
}
if err := r.Store.DB.Create(&c).Error; err != nil {
return nil, err
}
return &c, nil
}
// UpdateComponent is the resolver for the updateComponent field.
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
// Partial, like updateBox. Nothing to do for the linked boxes: they
// read the html from here every time they are fetched.
var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := usableComponentName(r.Store.DB, *input.Name, c.ID)
if err != nil {
return nil, err
}
c.Name = name
}
if input.Title != nil {
c.Title = input.Title
}
if input.HTML != nil {
c.HTML = *input.HTML
}
setInt(&c.W, input.W)
setInt(&c.H, input.H)
if input.Framed != nil {
c.Framed = *input.Framed
}
if input.Shadow != nil {
c.Shadow = *input.Shadow
}
if input.AdminOnly != nil {
c.AdminOnly = *input.AdminOnly
}
c.W = max(c.W, minBoxSize)
c.H = max(c.H, minBoxSize)
if err := validateShadow(&c.Shadow); err != nil {
return nil, err
}
if err := r.Store.DB.Save(&c).Error; err != nil {
return nil, err
}
return &c, nil
}
// DeleteComponent is the resolver for the deleteComponent field.
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
// The linked boxes keep showing what they showed, as copies, so
// deleting a component never changes a page. One transaction, so a
// failure can't leave boxes linked to a deleted component.
var c models.Component
if err := r.Store.DB.First(&c, id).Error; err != nil {
return nil, err
}
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
if err := detachFrom(tx, &c); err != nil {
return err
}
return tx.Delete(&c).Error
})
if err != nil {
return nil, err
}
return &c, nil
}
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
// The box becomes the component's first linked instance, so carrying
// on editing it edits the component. A box that is already linked
// would make a component of a component's html; detach it first.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
}
if box.Kind != "html" || box.HTML == nil {
return nil, errors.New("only an html box can be saved as a component")
}
if box.ComponentID != nil {
return nil, errors.New("that box is already linked to a component")
}
name, err := usableComponentName(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
c := models.Component{
Name: name, Title: box.Title, HTML: *box.HTML,
W: box.W, H: box.H, Framed: box.Framed, Shadow: box.Shadow, AdminOnly: box.AdminOnly,
}
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&c).Error; err != nil {
return err
}
box.ComponentID = &c.ID
box.HTML = nil
return tx.Save(&box).Error
})
if err != nil {
return nil, err
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
return &box, nil
}
// DetachBox is the resolver for the detachBox field.
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
// The html is filled in from the component and then saved, which is
// exactly the copy fillLinked otherwise never lets reach the row.
var box models.Box
if err := r.Store.DB.First(&box, id).Error; err != nil {
return nil, err
}
if box.ComponentID == nil {
return nil, errors.New("that box isn't linked to a component")
}
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
return nil, err
}
box.ComponentID = nil
if err := r.Store.DB.Save(&box).Error; err != nil {
return nil, err
}
return &box, nil
}
// Components is the resolver for the components field.
func (r *queryResolver) Components(ctx context.Context) ([]*models.Component, error) {
var components []models.Component
if err := r.Store.DB.Order("name ASC").Find(&components).Error; err != nil {
return nil, err
}
return ptrs(components), nil
}
// Component returns ComponentResolver implementation.
func (r *Resolver) Component() ComponentResolver { return &componentResolver{r} }
type componentResolver struct{ *Resolver }
+112
View File
@@ -0,0 +1,112 @@
package graph
// Hand-written helpers for component.resolvers.go, kept out of the resolver
// file for the same reason as box_helpers.go.
import (
"errors"
"fmt"
"strings"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const maxComponentNameLen = 100
// cleanComponentName trims name and reports why it can't be a component's
// name.
func cleanComponentName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a component needs a name")
}
if len(name) > maxComponentNameLen {
return name, fmt.Errorf("a component name is at most %d characters", maxComponentNameLen)
}
return name, nil
}
// componentNameTaken reports whether a live component other than exceptID
// has this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// usableComponentName checks name and answers with a sentence if it can't be
// used, so the resolvers that name a component share one set of messages.
func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error) {
name, err := cleanComponentName(name)
if err != nil {
return name, err
}
taken, err := componentNameTaken(db, name, exceptID)
if err != nil {
return name, err
}
if taken {
return name, errors.New("there is already a component with that name")
}
return name, nil
}
// fillLinked sets each linked box's in-memory HTML to its component's, with
// one query for all of them. Only for boxes about to be returned or
// snapshotted: a linked row's own HTML is nil, and saving a filled box would
// freeze a copy of the component into it. A box whose component has gone
// (deleted outside deleteComponent, which detaches first) is left with
// empty HTML rather than failing the whole page.
func fillLinked(db *gorm.DB, boxes []models.Box) error {
var ids []uint
for _, b := range boxes {
if b.ComponentID != nil {
ids = append(ids, *b.ComponentID)
}
}
if len(ids) == 0 {
return nil
}
var components []models.Component
if err := db.Where("id IN ?", ids).Find(&components).Error; err != nil {
return err
}
html := make(map[uint]string, len(components))
for _, c := range components {
html[c.ID] = c.HTML
}
for i := range boxes {
if id := boxes[i].ComponentID; id != nil {
h := html[*id]
boxes[i].HTML = &h
}
}
return nil
}
// fillLinkedOne is fillLinked for a single box.
func fillLinkedOne(db *gorm.DB, box *models.Box) error {
boxes := []models.Box{*box}
if err := fillLinked(db, boxes); err != nil {
return err
}
*box = boxes[0]
return nil
}
// componentExists reports whether id is a live component, for linking a box
// to it.
func componentExists(db *gorm.DB, id uint) (bool, error) {
var count int64
err := db.Model(&models.Component{}).Where("id = ?", id).Count(&count).Error
return count > 0, err
}
// detachFrom gives every box linked to component c its own copy of c's HTML
// and unlinks it, inside tx.
func detachFrom(tx *gorm.DB, c *models.Component) error {
return tx.Model(&models.Box{}).Where("component_id = ?", c.ID).
Updates(map[string]any{"html": c.HTML, "component_id": nil}).Error
}
+30
View File
@@ -0,0 +1,30 @@
package graph
import (
"strings"
"testing"
)
func TestCleanComponentName(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "Clock", "Clock", false},
{"trimmed", " Clock \n", "Clock", false},
{"empty", "", "", true},
{"only spaces", " ", "", true},
{"at the limit", strings.Repeat("a", maxComponentNameLen), strings.Repeat("a", maxComponentNameLen), false},
{"too long", strings.Repeat("a", maxComponentNameLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanComponentName(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
+153
View File
@@ -0,0 +1,153 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
)
// CreateCoverLetter is the resolver for the createCoverLetter field.
func (r *mutationResolver) CreateCoverLetter(ctx context.Context, input model.CreateCoverLetterInput) (*models.CoverLetter, error) {
name, err := cleanCoverLetterName(input.Name)
if err != nil {
return nil, err
}
if err := checkCoverLetterBody(input.Body); err != nil {
return nil, err
}
taken, err := coverLetterNameTaken(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a cover letter with that name")
}
letter := models.CoverLetter{Name: name, Body: input.Body}
if err := r.Store.DB.Create(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// UpdateCoverLetter is the resolver for the updateCoverLetter field.
func (r *mutationResolver) UpdateCoverLetter(ctx context.Context, id int, input model.UpdateCoverLetterInput) (*models.CoverLetter, error) {
var letter models.CoverLetter
if err := r.Store.DB.First(&letter, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := cleanCoverLetterName(*input.Name)
if err != nil {
return nil, err
}
taken, err := coverLetterNameTaken(r.Store.DB, name, letter.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a cover letter with that name")
}
letter.Name = name
}
if input.Body != nil {
if err := checkCoverLetterBody(*input.Body); err != nil {
return nil, err
}
letter.Body = *input.Body
}
if err := r.Store.DB.Save(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// DeleteCoverLetter is the resolver for the deleteCoverLetter field.
func (r *mutationResolver) DeleteCoverLetter(ctx context.Context, id int) (*models.CoverLetter, error) {
var letter models.CoverLetter
if err := r.Store.DB.First(&letter, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&letter).Error; err != nil {
return nil, err
}
return &letter, nil
}
// CreateCoverSnippet is the resolver for the createCoverSnippet field.
func (r *mutationResolver) CreateCoverSnippet(ctx context.Context, input model.CreateCoverSnippetInput) (*models.CoverSnippet, error) {
text, err := cleanSnippetText(input.Text)
if err != nil {
return nil, err
}
snippet := models.CoverSnippet{Text: text}
if input.Section != nil {
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
return nil, err
}
}
if err := r.Store.DB.Create(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// UpdateCoverSnippet is the resolver for the updateCoverSnippet field.
func (r *mutationResolver) UpdateCoverSnippet(ctx context.Context, id int, input model.UpdateCoverSnippetInput) (*models.CoverSnippet, error) {
// Letters it was dropped into keep their own copy of the old text.
var snippet models.CoverSnippet
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
return nil, err
}
var err error
if input.Text != nil {
if snippet.Text, err = cleanSnippetText(*input.Text); err != nil {
return nil, err
}
}
if input.Section != nil {
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
return nil, err
}
}
if err := r.Store.DB.Save(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// DeleteCoverSnippet is the resolver for the deleteCoverSnippet field.
func (r *mutationResolver) DeleteCoverSnippet(ctx context.Context, id int) (*models.CoverSnippet, error) {
var snippet models.CoverSnippet
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&snippet).Error; err != nil {
return nil, err
}
return &snippet, nil
}
// CoverLetters is the resolver for the coverLetters field.
func (r *queryResolver) CoverLetters(ctx context.Context) ([]*models.CoverLetter, error) {
var letters []models.CoverLetter
if err := r.Store.DB.Order("updated_at DESC").Find(&letters).Error; err != nil {
return nil, err
}
return ptrs(letters), nil
}
// CoverSnippets is the resolver for the coverSnippets field.
func (r *queryResolver) CoverSnippets(ctx context.Context) ([]*models.CoverSnippet, error) {
var snippets []models.CoverSnippet
if err := r.Store.DB.Order("section ASC, created_at DESC").Find(&snippets).Error; err != nil {
return nil, err
}
return ptrs(snippets), nil
}
+84
View File
@@ -0,0 +1,84 @@
package graph
// Hand-written helpers for cover_letter.resolvers.go, kept out of the
// resolver file for the same reason as box_helpers.go.
import (
"encoding/json"
"errors"
"fmt"
"strings"
"unicode/utf8"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const (
maxCoverLetterNameLen = 100
// A letter is a page of text; 100 KB is far beyond any real one and
// still small enough that a runaway client can't fill the table.
maxCoverLetterBodyLen = 100 * 1024
maxSnippetTextLen = 5000
maxSnippetSectionLen = 100
)
// cleanCoverLetterName trims name and reports why it can't be a letter's
// name.
func cleanCoverLetterName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a cover letter needs a name")
}
if len(name) > maxCoverLetterNameLen {
return name, fmt.Errorf("a cover letter name is at most %d characters", maxCoverLetterNameLen)
}
return name, nil
}
// coverLetterNameTaken reports whether a live letter other than exceptID has
// this name. Checked up front, like layoutNameTaken, so the admin gets a
// sentence rather than a constraint violation.
func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// checkCoverLetterBody reports why body can't be stored. The server never
// reads inside it, so it only has to be a JSON object of a sane size — an
// array or a bare string would be a frontend bug worth refusing early.
func checkCoverLetterBody(body string) error {
if len(body) > maxCoverLetterBodyLen {
return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024)
}
var obj map[string]json.RawMessage
// null unmarshals into a nil map without error, so it is caught here too.
if err := json.Unmarshal([]byte(body), &obj); err != nil || obj == nil {
return errors.New("a cover letter body must be a JSON object")
}
return nil
}
// cleanSnippetText trims text and reports why it can't be a bank paragraph.
// Counted in characters, not bytes, since the limit is about how much prose
// fits rather than storage.
func cleanSnippetText(text string) (string, error) {
text = strings.TrimSpace(text)
if text == "" {
return text, errors.New("a paragraph can't be empty")
}
if utf8.RuneCountInString(text) > maxSnippetTextLen {
return text, fmt.Errorf("a paragraph is at most %d characters", maxSnippetTextLen)
}
return text, nil
}
// cleanSnippetSection trims a snippet's section title.
func cleanSnippetSection(section string) (string, error) {
section = strings.TrimSpace(section)
if utf8.RuneCountInString(section) > maxSnippetSectionLen {
return section, fmt.Errorf("a section title is at most %d characters", maxSnippetSectionLen)
}
return section, nil
}
@@ -0,0 +1,76 @@
package graph
import (
"strings"
"testing"
)
func TestCleanCoverLetterName(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "Acme", "Acme", false},
{"trimmed", " Acme \n", "Acme", false},
{"empty", "", "", true},
{"only spaces", " ", "", true},
{"at the limit", strings.Repeat("a", maxCoverLetterNameLen), strings.Repeat("a", maxCoverLetterNameLen), false},
{"too long", strings.Repeat("a", maxCoverLetterNameLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanCoverLetterName(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
func TestCheckCoverLetterBody(t *testing.T) {
for _, c := range []struct {
name, in string
wantErr bool
}{
{"object", `{"v":1,"sections":[]}`, false},
{"empty object", `{}`, false},
{"array", `[]`, true},
{"string", `"hi"`, true},
{"null", `null`, true},
{"not json", `{`, true},
{"empty", ``, true},
{"too big", `{"x":"` + strings.Repeat("a", maxCoverLetterBodyLen) + `"}`, true},
} {
t.Run(c.name, func(t *testing.T) {
if err := checkCoverLetterBody(c.in); (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
})
}
}
func TestCleanSnippetText(t *testing.T) {
for _, c := range []struct {
name, in, want string
wantErr bool
}{
{"plain", "I like Go.", "I like Go.", false},
{"trimmed", "\n I like Go. ", "I like Go.", false},
{"empty", " ", "", true},
// Characters, not bytes: 5000 two-byte runes still fit.
{"multibyte at the limit", strings.Repeat("é", maxSnippetTextLen), strings.Repeat("é", maxSnippetTextLen), false},
{"too long", strings.Repeat("a", maxSnippetTextLen+1), "", true},
} {
t.Run(c.name, func(t *testing.T) {
got, err := cleanSnippetText(c.in)
if (err != nil) != c.wantErr {
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
}
if !c.wantErr && got != c.want {
t.Fatalf("got %q, want %q", got, c.want)
}
})
}
}
+8 -3
View File
@@ -187,9 +187,14 @@ func TestSignedInMutationsArePinned(t *testing.T) {
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
"user": "admin",
"places": "signedIn",
"users": "admin",
"user": "admin",
"places": "signedIn",
"layouts": "admin",
"components": "admin",
"coverLetters": "admin",
"coverSnippets": "admin",
"permissionTypes": "signedIn",
}
got := map[string]string{}
for _, field := range schemaUnderTest().Query.Fields {
+4149 -32
View File
File diff suppressed because it is too large Load Diff
+147
View File
@@ -0,0 +1,147 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver
// implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.95
import (
"context"
"errors"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
// BoxCount is the resolver for the boxCount field.
func (r *layoutResolver) BoxCount(ctx context.Context, obj *models.Layout) (int, error) {
// Decoded rather than stored, so it can never disagree with the boxes.
boxes, err := decodeLayoutBoxes(obj)
if err != nil {
return 0, err
}
return len(boxes), nil
}
// HasBackground is the resolver for the hasBackground field.
func (r *layoutResolver) HasBackground(ctx context.Context, obj *models.Layout) (bool, error) {
return obj.Background != nil, nil
}
// CreateLayout is the resolver for the createLayout field.
func (r *mutationResolver) CreateLayout(ctx context.Context, input model.CreateLayoutInput) (*models.Layout, error) {
// A snapshot of the page as it is now, adminOnly boxes included —
// which is why every layout field is @admin.
name, err := cleanLayoutName(input.Name)
if err != nil {
return nil, err
}
if !validPageKey(input.Page) {
return nil, errors.New("a layout needs a valid page")
}
taken, err := layoutNameTaken(r.Store.DB, name, 0)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a layout with that name")
}
layout, empty, err := snapshotPage(r.Store.DB, input.Page, name)
if err != nil {
return nil, err
}
if empty {
return nil, errors.New("that page has nothing on it to save")
}
if err := r.Store.DB.Create(&layout).Error; err != nil {
return nil, err
}
return &layout, nil
}
// UpdateLayout is the resolver for the updateLayout field.
func (r *mutationResolver) UpdateLayout(ctx context.Context, id int, input model.UpdateLayoutInput) (*models.Layout, error) {
// Only the name changes: a layout is a snapshot, and saving the page
// again under a new name is how its content is refreshed.
var layout models.Layout
if err := r.Store.DB.First(&layout, id).Error; err != nil {
return nil, err
}
if input.Name != nil {
name, err := cleanLayoutName(*input.Name)
if err != nil {
return nil, err
}
taken, err := layoutNameTaken(r.Store.DB, name, layout.ID)
if err != nil {
return nil, err
}
if taken {
return nil, errors.New("there is already a layout with that name")
}
layout.Name = name
}
if err := r.Store.DB.Save(&layout).Error; err != nil {
return nil, err
}
return &layout, nil
}
// DeleteLayout is the resolver for the deleteLayout field.
func (r *mutationResolver) DeleteLayout(ctx context.Context, id int) (*models.Layout, error) {
// Pages it was loaded onto keep their boxes: they were copies.
var layout models.Layout
if err := r.Store.DB.First(&layout, id).Error; err != nil {
return nil, err
}
if err := r.Store.DB.Delete(&layout).Error; err != nil {
return nil, err
}
return &layout, nil
}
// ApplyLayout is the resolver for the applyLayout field.
func (r *mutationResolver) ApplyLayout(ctx context.Context, id int, page string, replace bool) ([]*models.Box, error) {
// One transaction, so a replace that fails partway leaves the page as
// it was rather than half emptied.
var layout models.Layout
if err := r.Store.DB.First(&layout, id).Error; err != nil {
return nil, err
}
exists, err := canvasExists(r.Store.DB, page)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.New("there is no page at that address")
}
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
return applyLayoutTo(tx, &layout, page, replace)
})
if err != nil {
return nil, err
}
boxes, err := pageBoxes(r.Store.DB, page)
if err != nil {
return nil, err
}
if err := fillLinked(r.Store.DB, boxes); err != nil {
return nil, err
}
return ptrs(boxes), nil
}
// Layouts is the resolver for the layouts field.
func (r *queryResolver) Layouts(ctx context.Context) ([]*models.Layout, error) {
var layouts []models.Layout
if err := r.Store.DB.Order("created_at DESC").Find(&layouts).Error; err != nil {
return nil, err
}
return ptrs(layouts), nil
}
// Layout returns LayoutResolver implementation.
func (r *Resolver) Layout() LayoutResolver { return &layoutResolver{r} }
type layoutResolver struct{ *Resolver }
+275
View File
@@ -0,0 +1,275 @@
package graph
// Hand-written helpers for layout.resolvers.go, kept out of the resolver file
// for the same reason as box_helpers.go.
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"gorm.io/gorm"
)
const maxLayoutNameLen = 100
// layoutBox is one box as a layout stores it: what makes it look the way it
// does, without the id and page that tie a row to one canvas. Changing these
// field names would make older layouts load with the renamed fields empty.
type layoutBox struct {
Kind string `json:"kind"`
Widget *string `json:"widget,omitempty"`
HTML *string `json:"html,omitempty"`
Title *string `json:"title,omitempty"`
X int `json:"x"`
Y int `json:"y"`
W int `json:"w"`
H int `json:"h"`
Z int `json:"z"`
Framed bool `json:"framed"`
Shadow string `json:"shadow,omitempty"`
HideOnMobile bool `json:"hideOnMobile"`
AdminOnly bool `json:"adminOnly"`
// ComponentID is the component a linked box was linked to. HTML is
// stored too, so that a layout outlives the component: loading links the
// box again if the component is still there and uses HTML if not.
ComponentID *uint `json:"componentId,omitempty"`
}
type layoutBackground struct {
Color string `json:"color"`
Image string `json:"image"`
Fit string `json:"fit"`
}
// cleanLayoutName trims name and reports why it can't be a layout's name.
func cleanLayoutName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return name, errors.New("a layout needs a name")
}
if len(name) > maxLayoutNameLen {
return name, fmt.Errorf("a layout name is at most %d characters", maxLayoutNameLen)
}
return name, nil
}
// layoutNameTaken reports whether a live layout other than exceptID has this
// name. Checked up front, like slugTaken, so the admin gets a sentence rather
// than a constraint violation.
func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
var count int64
err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
return count > 0, err
}
// canvasExists reports whether page is a canvas boxes can be put on: the
// landing page, or a live Page. Loading a layout onto any other key would
// leave its boxes where nothing shows them.
func canvasExists(db *gorm.DB, page string) (bool, error) {
if page == "index" {
return true, nil
}
if !validPageKey(page) {
return false, nil
}
var count int64
err := db.Model(&models.Page{}).Where("slug = ?", page).Count(&count).Error
return count > 0, err
}
// pageBoxes is every box on page, adminOnly ones included, in the order the
// boxes query returns them. Only for admin-only callers.
func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) {
var boxes []models.Box
err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error
return boxes, err
}
// snapshotPage is an unsaved Layout holding page's boxes and background as
// they are now. empty is true when there was nothing to keep.
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
boxes, err := pageBoxes(db, page)
if err != nil {
return layout, false, err
}
if err := fillLinked(db, boxes); err != nil {
return layout, false, err
}
stored := make([]layoutBox, len(boxes))
for i, b := range boxes {
stored[i] = layoutBox{
Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z,
Framed: b.Framed, Shadow: b.Shadow, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
ComponentID: b.ComponentID,
}
}
boxesJSON, err := json.Marshal(stored)
if err != nil {
return layout, false, err
}
layout = models.Layout{Name: name, SourcePage: page, Boxes: string(boxesJSON)}
var bg models.Background
err = db.Where("page = ?", page).First(&bg).Error
switch {
case err == nil:
bgJSON, err := json.Marshal(layoutBackground{Color: bg.Color, Image: bg.Image, Fit: bg.Fit})
if err != nil {
return layout, false, err
}
s := string(bgJSON)
layout.Background = &s
case !errors.Is(err, gorm.ErrRecordNotFound):
return layout, false, err
}
return layout, len(boxes) == 0 && layout.Background == nil, nil
}
func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
var boxes []layoutBox
if err := json.Unmarshal([]byte(layout.Boxes), &boxes); err != nil {
return nil, fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
}
return boxes, nil
}
// pageLabel is how a page key reads in a generated layout name.
func pageLabel(page string) string {
if page == "index" {
return "/"
}
return "/" + page
}
// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken.
func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
name := base
for n := 2; ; n++ {
taken, err := layoutNameTaken(db, name, 0)
if err != nil || !taken {
return name, err
}
name = fmt.Sprintf("%s (%d)", base, n)
}
}
// applyLayoutTo copies layout onto page inside tx; see applyLayout in
// layout.graphql for what replace does. The copies are new rows, so the page
// owns them outright.
func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error {
stored, err := decodeLayoutBoxes(layout)
if err != nil {
return err
}
// Added on top, the copies keep their own stacking order but all sit
// above what the page already has.
zShift := 0
if replace {
// What is being replaced is kept first, so a replace can be undone by
// loading that layout back. A page with nothing on it has nothing to
// keep.
name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s",
pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04")))
if err != nil {
return err
}
backup, empty, err := snapshotPage(tx, page, name)
if err != nil {
return err
}
if !empty {
if err := tx.Create(&backup).Error; err != nil {
return err
}
}
if err := tx.Where("page = ?", page).Delete(&models.Box{}).Error; err != nil {
return err
}
if err := tx.Where("page = ?", page).Delete(&models.Background{}).Error; err != nil {
return err
}
} else if len(stored) > 0 {
var top *int
if err := tx.Model(&models.Box{}).Where("page = ?", page).Select("MAX(z)").Scan(&top).Error; err != nil {
return err
}
if top != nil {
lowest := stored[0].Z
for _, b := range stored {
lowest = min(lowest, b.Z)
}
zShift = *top + 1 - lowest
}
}
live, err := liveComponents(tx, stored)
if err != nil {
return err
}
boxes := make([]models.Box, len(stored))
for i, b := range stored {
boxes[i] = models.Box{
Page: page, Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z + zShift,
Framed: b.Framed, Shadow: b.Shadow, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
}
if b.ComponentID != nil && live[*b.ComponentID] {
boxes[i].ComponentID = b.ComponentID
boxes[i].HTML = nil
}
if err := validateBox(&boxes[i]); err != nil {
return err
}
}
if len(boxes) > 0 {
if err := tx.Create(&boxes).Error; err != nil {
return err
}
}
// Adding on top leaves the page's own background alone.
if replace && layout.Background != nil {
var saved layoutBackground
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
return fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
}
bg, err := backgroundFrom(page, model.BackgroundInput{Color: saved.Color, Image: saved.Image, Fit: saved.Fit})
if err != nil {
return err
}
if err := tx.Create(&bg).Error; err != nil {
return err
}
}
return nil
}
// liveComponents is the set of components the stored boxes were linked to
// that still exist, so applyLayoutTo knows which boxes to link again.
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
var ids []uint
for _, b := range stored {
if b.ComponentID != nil {
ids = append(ids, *b.ComponentID)
}
}
live := map[uint]bool{}
if len(ids) == 0 {
return live, nil
}
var found []uint
if err := db.Model(&models.Component{}).Where("id IN ?", ids).Pluck("id", &found).Error; err != nil {
return nil, err
}
for _, id := range found {
live[id] = true
}
return live, nil
}
+54
View File
@@ -42,8 +42,31 @@ type CreateBoxInput struct {
H *int `json:"h,omitempty"`
Z *int `json:"z,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
ComponentID *int `json:"componentId,omitempty"`
}
type CreateComponentInput struct {
Name string `json:"name"`
Title *string `json:"title,omitempty"`
HTML string `json:"html"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type CreateCoverLetterInput struct {
Name string `json:"name"`
Body string `json:"body"`
}
type CreateCoverSnippetInput struct {
Text string `json:"text"`
Section *string `json:"section,omitempty"`
}
type CreateFavoriteInput struct {
@@ -52,6 +75,11 @@ type CreateFavoriteInput struct {
Link *string `json:"link,omitempty"`
}
type CreateLayoutInput struct {
Name string `json:"name"`
Page string `json:"page"`
}
type CreatePageInput struct {
Slug string `json:"slug"`
Title string `json:"title"`
@@ -151,10 +179,36 @@ type UpdateBoxInput struct {
H *int `json:"h,omitempty"`
Z *int `json:"z,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdateComponentInput struct {
Name *string `json:"name,omitempty"`
Title *string `json:"title,omitempty"`
HTML *string `json:"html,omitempty"`
W *int `json:"w,omitempty"`
H *int `json:"h,omitempty"`
Framed *bool `json:"framed,omitempty"`
Shadow *string `json:"shadow,omitempty"`
AdminOnly *bool `json:"adminOnly,omitempty"`
}
type UpdateCoverLetterInput struct {
Name *string `json:"name,omitempty"`
Body *string `json:"body,omitempty"`
}
type UpdateCoverSnippetInput struct {
Text *string `json:"text,omitempty"`
Section *string `json:"section,omitempty"`
}
type UpdateLayoutInput struct {
Name *string `json:"name,omitempty"`
}
type UpdatePageInput struct {
Slug *string `json:"slug,omitempty"`
Title *string `json:"title,omitempty"`
+5 -5
View File
@@ -24,11 +24,11 @@ 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.
// landing page's key "index", whose boxes a page of the same slug would
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
// pages under it and the home page /stp are all canvas pages.
var reservedFirstSegments = map[string]bool{
"stp": true, "stp2": true, "index": true, "admin": true, "cv": 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,
@@ -52,7 +52,7 @@ func validateSlug(slug string) error {
}
// 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,
// and the caller is not an admin. A key with no Page row (the landing page,
// or a page that doesn't exist) is not hidden.
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
if IsAdminFromCtx(ctx) {
+3 -2
View File
@@ -21,8 +21,9 @@ func TestValidateSlug(t *testing.T) {
{"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", true}, // the home page is a canvas page too
{"stp2", false}, // an SPA route
{"index", false}, // the landing canvas's key
{"stp-fan-page", true}, // only whole segments are reserved
} {
err := validateSlug(c.slug)
+7
View File
@@ -8,6 +8,7 @@ package graph
import (
"context"
"fmt"
"strings"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
@@ -23,6 +24,12 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
return nil, fmt.Errorf("unauthorized")
}
// The admin form submits whatever is in its fields, so an accidental click
// on an empty form would otherwise publish a blank post to the feed.
if strings.TrimSpace(input.Title) == "" {
return nil, fmt.Errorf("a post needs a title")
}
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
if err := r.Store.DB.Create(&post).Error; err != nil {
return nil, err
+2 -2
View File
@@ -1,6 +1,6 @@
# 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
# boxes ("index" for the landing page, or a Page's slug), so the landing
# page and every other canvas page are set the same way. Edited from the
# canvas's "Background" button; see models.Background.
#
# Anyone may read it, as part of the page, except that an adminOnly page's
+13 -3
View File
@@ -1,11 +1,13 @@
# 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).
# Boxes on a canvas page: the landing page (page "index") or an
# admin-created Page (page = its slug; the home page /stp is the Page "stp").
# Anyone may read a page's layout — it is the page — but only an admin may
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
# are px on a fixed 1400px-wide design canvas; see models.Box.
#
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
# (`html` rendered in a sandboxed iframe on the front end).
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
# componentId is linked to that Component: its html is the component's, and
# updateBox refuses to change it (component.graphql).
type Box {
id: ID!
@@ -22,8 +24,11 @@ type Box {
h: Int!
z: Int!
framed: Boolean!
# A CSS box-shadow value, or "" for none.
shadow: String!
hideOnMobile: Boolean!
adminOnly: Boolean!
componentId: ID
}
input CreateBoxInput {
@@ -38,8 +43,12 @@ input CreateBoxInput {
h: Int
z: Int
framed: Boolean
shadow: String
hideOnMobile: Boolean
adminOnly: Boolean
# Links the new box to this component; kind is then "html" and html is
# ignored.
componentId: ID
}
input UpdateBoxInput {
@@ -52,6 +61,7 @@ input UpdateBoxInput {
h: Int
z: Int
framed: Boolean
shadow: String
hideOnMobile: Boolean
adminOnly: Boolean
}
+67
View File
@@ -0,0 +1,67 @@
# Components: named HTML boxes that can be placed on any canvas page, either
# as a copy (an ordinary box) or linked (a Box whose componentId is set).
# Linked boxes share only the html — editing a component changes every box
# linked to it — while title, geometry, frame and visibility stay each box's
# own. title, w, h, framed, shadow and adminOnly here are what a newly placed box
# starts with. See models.Component and graph/component_helpers.go.
#
# Admin only throughout, reads included, because a component may have been
# saved from an adminOnly note. A linked box's html still reaches visitors
# through the boxes query, which is the point.
type Component {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
title: String
html: String!
w: Int!
h: Int!
framed: Boolean!
shadow: String!
adminOnly: Boolean!
# How many boxes are linked to it.
uses: Int!
}
input CreateComponentInput {
name: String!
title: String
html: String!
w: Int
h: Int
framed: Boolean
shadow: String
adminOnly: Boolean
}
input UpdateComponentInput {
name: String
title: String
html: String
w: Int
h: Int
framed: Boolean
shadow: String
adminOnly: Boolean
}
extend type Query {
# By name.
components: [Component!]! @admin
}
extend type Mutation {
createComponent(input: CreateComponentInput!): Component! @admin
# A new html changes every box linked to it.
updateComponent(id: ID!, input: UpdateComponentInput!): Component! @admin
# Detaches every linked box first, giving each its own copy of the html, so
# no page changes.
deleteComponent(id: ID!): Component! @admin
# Makes html box `id` into a component named `name`, from its html, title,
# size, frame, shadow and adminOnly, and links the box to it. Answers with the box.
saveBoxAsComponent(id: ID!, name: String!): Box! @admin
# Gives linked box `id` its own copy of the component's html and unlinks it.
detachBox(id: ID!): Box! @admin
}
+60
View File
@@ -0,0 +1,60 @@
# Cover letters: saved letters from the /cv Cover Letter tab, and the bank of
# reusable paragraphs dragged into them. A letter's body is JSON the frontend
# owns (views/CV/coverLetter.js); the server only checks it is a JSON object
# of a sane size. See models.CoverLetter and graph/cover_letter_helpers.go.
#
# Admin only throughout, reads included: /cv is public, but the letters are
# drafts addressed to particular employers.
type CoverLetter {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
# The whole letter, as a JSON object.
body: String!
}
type CoverSnippet {
id: ID!
createdAt: Time!
text: String!
# The section title it was written for; "" for none. Only groups the bank.
section: String!
}
input CreateCoverLetterInput {
name: String!
body: String!
}
input UpdateCoverLetterInput {
name: String
body: String
}
input CreateCoverSnippetInput {
text: String!
section: String
}
input UpdateCoverSnippetInput {
text: String
section: String
}
extend type Query {
# Most recently updated first.
coverLetters: [CoverLetter!]! @admin
# By section, then newest first.
coverSnippets: [CoverSnippet!]! @admin
}
extend type Mutation {
createCoverLetter(input: CreateCoverLetterInput!): CoverLetter! @admin
updateCoverLetter(id: ID!, input: UpdateCoverLetterInput!): CoverLetter! @admin
deleteCoverLetter(id: ID!): CoverLetter! @admin
createCoverSnippet(input: CreateCoverSnippetInput!): CoverSnippet! @admin
updateCoverSnippet(id: ID!, input: UpdateCoverSnippetInput!): CoverSnippet! @admin
deleteCoverSnippet(id: ID!): CoverSnippet! @admin
}
+48
View File
@@ -0,0 +1,48 @@
# Saved layouts: a named copy of one canvas page's boxes and background,
# which can be loaded onto any canvas page — the landing page ("index") or a
# Page's slug. Loading copies: the new boxes belong to the target page, so
# editing a page afterwards never changes the layout or another page. Moving
# a layout is saving it on one page and loading it on another with
# replace: true. See models.Layout and graph/layout_helpers.go.
#
# Admin only throughout, reads included, because a layout keeps a page's
# adminOnly boxes along with the rest.
type Layout {
id: ID!
createdAt: Time!
updatedAt: Time!
name: String!
# The page key it was saved from.
sourcePage: String!
boxCount: Int!
hasBackground: Boolean!
}
input CreateLayoutInput {
name: String!
# The page key to save, as it is now.
page: String!
}
input UpdateLayoutInput {
name: String
}
extend type Query {
# Newest first.
layouts: [Layout!]! @admin
}
extend type Mutation {
createLayout(input: CreateLayoutInput!): Layout! @admin
# Renames it; what a layout holds never changes after it is saved.
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
deleteLayout(id: ID!): Layout! @admin
# Copies the layout onto `page` and answers with that page's boxes.
# replace: false adds the copies on top of what is there, leaving the
# background alone. replace: true first saves the page as a layout named
# "<page> before <layout>, <time>", then swaps its boxes and background
# for the layout's.
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
}
+16
View File
@@ -4,6 +4,17 @@ type User {
updatedAt: Time!
username: String!
admin: Boolean!
# Keys of the gated services this user may use (see PermissionType). Admins
# pass every permission check whatever this holds.
permissions: [String!]!
}
# One grantable service, from services.PermissionTypes: `key` is what is
# stored and what nginx gates on, `label` and `path` are for display.
type PermissionType {
key: String!
label: String!
path: String!
}
input CreateUserInput {
@@ -14,10 +25,15 @@ input CreateUserInput {
extend type Query {
users: [User!]! @admin
user(id: ID!): User @admin
# @signedIn rather than @admin: /account lists a non-admin's own services
# from it. The list itself is not a secret.
permissionTypes: [PermissionType!]! @signedIn
}
extend type Mutation {
createUser(input: CreateUserInput!): User! @admin
deleteUser(id: ID!): User! @admin
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
# Replaces the user's whole permission list; unknown keys are rejected.
setUserPermissions(id: ID!, permissions: [String!]!): User! @admin
}
+43
View File
@@ -8,9 +8,11 @@ package graph
import (
"context"
"fmt"
"slices"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"golang.org/x/crypto/bcrypt"
)
@@ -72,6 +74,41 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return &user, nil
}
// SetUserPermissions is the resolver for the setUserPermissions field.
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
// The whole list is replaced, so the admin panel sends every ticked box
// each time. An unknown key is refused rather than dropped, so a stale
// front end cannot silently save less than it showed. The stored list is
// rebuilt in registry order, which also drops duplicates.
want := map[string]bool{}
for _, key := range permissions {
if !services.ValidPermission(key) {
return nil, fmt.Errorf("unknown permission %q", key)
}
want[key] = true
}
granted := []string{}
for _, p := range services.PermissionTypes {
if want[p.Key] {
granted = append(granted, p.Key)
}
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
// No token bump needed: the permission gate reads this column on every
// request, so the change applies to the user's next one.
user.Permissions = granted
if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// Users is the resolver for the users field.
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
var users []models.User
@@ -89,3 +126,9 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
}
return &user, nil
}
// PermissionTypes is the resolver for the permissionTypes field.
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
// A copy, so nothing downstream can write through to the registry.
return ptrs(slices.Clone(services.PermissionTypes)), nil
}
+72 -36
View File
@@ -93,51 +93,86 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
}
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// decide whether to show admin UI. It answers with a bare status code and no
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
// decide whether to show admin UI, nginx's admin gate calls as an
// auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
// new cookie pair as a side effect, so a returning admin is recognised
// without a visible re-login.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
accessToken, err := ctx.Cookie("access_token")
if err != nil {
// No access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// On the access-token path admin is read from the token, as
// everywhere else; on the refresh path there is no admin claim, and
// the row is what makes that path pick up a revoked admin flag.
if claims == nil {
return user.Admin
}
return
}
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err != nil {
// Expired, invalid or revoked access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
}
return
}
admin, ok := (*claims)["admin"].(bool)
if !ok || !admin {
ctx.Status(http.StatusForbidden)
return
}
ctx.Status(http.StatusOK)
admin, ok := (*claims)["admin"].(bool)
return ok && admin
})
}
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
// ValidatePermission backs GET /auth/validate/:permission, nginx's permission
// gate (see services/permissions.go). Same bare-status contract and refresh
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in an nginx location fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The bool does not mean "is an admin" — it means "this function already
// wrote the response". It returns true both for a successful admin refresh
// (200, new cookies set) and for a valid non-admin (403), and false only when
// it could not decide, leaving the caller to send 401. Getting this backwards
// would send two status codes for one request.
// The decision reads the user row, not the token, for admins as well: a
// grant, a revoke or a demotion applies on the very next request.
func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission")
if !services.ValidPermission(key) {
ctx.Status(http.StatusNotFound)
return
}
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
return services.HasPermission(user, key)
})
}
// validateSession is the body shared by the two validate endpoints: identify
// the caller from the access token, or failing that the refresh token, and
// answer 200 / 403 / 401 according to allow.
//
// Admin status is re-read from the database here, which is what makes the
// refresh path pick up a revoked admin flag.
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which nginx can lift with
// auth_request_set and hand to the service behind the gate, so that service
// knows who is using it without having accounts of its own.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err == nil {
if !allow(user, claims) {
ctx.Status(http.StatusForbidden)
return
}
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return
}
}
// No access token, or an expired, invalid or revoked one — try refreshing.
if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized)
}
}
// tryRefreshAndValidate re-authenticates from the refresh token.
//
// The bool does not mean "allowed" — it means "this function already wrote
// the response". It returns true both for a successful refresh (200, new
// cookies set) and for a valid but unauthorised user (403, no new cookies),
// and false only when it could not decide, leaving the caller to send 401.
// Getting this backwards would send two status codes for one request.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
@@ -150,7 +185,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
return false
}
if !user.Admin {
if !allow(user, nil) {
ctx.Status(http.StatusForbidden)
return true
}
@@ -162,6 +197,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
store.setAuthCookies(ctx, tokens)
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return true
}
+19
View File
@@ -49,6 +49,25 @@ func (store *Store) Upload(ctx *gin.Context) {
}
}
// ListUploads backs GET /uploads (admin): every public upload, newest first,
// for the upload picker on the canvas pages (vue/src/components/util/
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
//
// Admin-only because the listing is the one thing that turns unguessable
// upload URLs into known ones; see services.Uploads.List.
func (store *Store) ListUploads(ctx *gin.Context) {
files, err := store.Uploads.List(ctx.Request.Context())
if err != nil {
log.Printf("[upload] listing failed: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list uploads"})
return
}
if files == nil {
files = []services.StoredFile{} // [] rather than null for the frontend
}
ctx.JSON(http.StatusOK, gin.H{"files": files})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
+23 -2
View File
@@ -23,8 +23,9 @@ import (
// 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.
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
@@ -251,6 +252,26 @@ func TestRequestIsAdmin(t *testing.T) {
}
}
// --- Permission gate ------------------------------------------------------
// An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in an nginx
// location shows up as a 404 rather than as a missing grant.
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Store{}
for _, key := range []string{"no-such-service", "admin", ""} {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "permission", Value: key}}
ctx.Request = httptest.NewRequest("GET", "/auth/validate/"+key, nil)
s.ValidatePermission(ctx)
if ctx.Writer.Status() != 404 {
t.Errorf("key %q: status %d, want 404", key, ctx.Writer.Status())
}
}
}
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
+2
View File
@@ -167,6 +167,7 @@ func main() {
r.GET("/auth/check", store.CheckToken)
r.POST("/auth/logout", store.Logout)
r.GET("/auth/validate-admin", store.ValidateAdmin)
r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY
// The callback must be open — Spotify redirects a logged-out browser to
@@ -190,6 +191,7 @@ func main() {
// the handler checks the cookies itself to decide admin privileges.
r.GET("/ws", store.ConnectWebSocket)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile)
+96 -6
View File
@@ -39,6 +39,14 @@ type User struct {
// Admin gates almost every mutation. It is copied into the access token,
// so a change here only takes effect on the user's next token refresh.
Admin bool `json:"admin"`
// Permissions names the gated services this non-admin user may use, one
// key each from services.PermissionTypes (admins pass every check
// regardless). Unlike Admin it is never copied into a token: the gate
// reads it from the row, which services.Auth loads on every request
// anyway, so a grant or revoke takes effect on the user's next request.
// Stored as a JSON array in one text column; a row from before the
// column existed reads as NULL, i.e. no permissions.
Permissions []string `gorm:"serializer:json" json:"permissions"`
// TokenVersion is the session generation counter. Every issued JWT
// carries the value current at the time it was minted, and
// services.Auth rejects a token whose value no longer matches, so
@@ -157,9 +165,9 @@ type Place struct {
}
// 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
// "index" for the landing page, or a Page.Slug for an admin-created page
// (the home page is the Page "stp") — it is a key, not a foreign key, so the
// built-in landing canvas needs no Page row. Its position and size are in px on a
// fixed 1400px-wide design canvas, which the page scales down on narrower
// screens — so the stored numbers mean the same thing for every visitor. Kind "widget" renders a built-in Vue component named by Widget;
// kind "html" renders HTML in a sandboxed iframe on the front end, which is
@@ -183,11 +191,20 @@ type Box struct {
// 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"`
Framed bool `gorm:"not null" json:"framed"`
// Shadow is a CSS box-shadow value drawn around the box, or "" for none.
// It is independent of Framed, so an unframed box can still cast one.
Shadow string `gorm:"not null;default:''" json:"shadow"`
HideOnMobile bool `gorm:"not null;default:false" json:"hideOnMobile"`
// AdminOnly boxes are never sent to anyone but an admin (the boxes
// resolver filters them out), so they suit private notes.
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
// ComponentID links an html box to a Component, whose HTML it shows
// instead of its own: the row's HTML is nil, and the resolvers fill it in
// from the component before answering (graph/component_helpers.go). There
// is deliberately no association field — with one, DB.Save(&box) would
// write the component back too.
ComponentID *uint `gorm:"index" json:"componentId"`
}
// Page is an admin-created canvas page, served by the SPA's catch-all route
@@ -207,7 +224,7 @@ type Page struct {
}
// 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
// key a Box has: "index" for the landing page, or a Page's slug), so
// built-in canvases and admin-created pages are set the same way. A page with
// no row shows the theme's halftone; deleting the row is "reset to default".
// The unique index is partial for the same reason as Page's.
@@ -224,3 +241,76 @@ type Background struct {
// Fit is how Image fills the window: "cover", "contain" or "tile".
Fit string `gorm:"not null;default:cover" json:"fit"`
}
// Layout is a named copy of one canvas page's boxes and background, saved so
// it can be loaded onto any page later (graph/layout_helpers.go). It is a
// snapshot, not a link: loading it creates new boxes that belong to the
// target page, so editing either page afterwards never touches the other or
// the layout. The content is JSON rather than child rows because nothing
// queries inside it — it is only ever written whole and read whole. The
// unique index is partial for the same reason as Page's.
type Layout struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
// SourcePage is the page key it was saved from, for the list only.
SourcePage string `gorm:"not null" json:"sourcePage"`
// Boxes is a JSON array of the boxes' content and geometry, without id
// or page.
Boxes string `gorm:"type:text;not null" json:"-"`
// Background is the page's background as JSON, or nil if it had none.
Background *string `gorm:"type:text" json:"-"`
}
// Component is a named HTML box that can be placed on any canvas page, either
// as a copy (an ordinary box) or linked (a box with ComponentID set). Linked
// boxes share only the HTML — editing it changes every one of them at once —
// while title, geometry, frame and visibility stay each box's own, since
// those are about where it sits on a page rather than what it is. Title, W,
// H, Framed, Shadow and AdminOnly are the defaults a newly placed box starts
// with.
// Widgets are not components: a widget box is just a name, with nothing
// worth sharing. The unique index is partial for the same reason as Page's.
type Component struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_components_name,unique,where:deleted_at IS NULL" json:"name"`
Title *string `json:"title"`
HTML string `gorm:"type:text;not null" json:"html"`
W int `gorm:"not null" json:"w"`
H int `gorm:"not null" json:"h"`
// No gorm default on Framed, for the same reason as Box.Framed.
Framed bool `gorm:"not null" json:"framed"`
Shadow string `gorm:"not null;default:''" json:"shadow"`
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
}
// CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the
// whole letter as JSON (contact block, sections, paragraphs; the shape is
// views/CV/coverLetter.js's) because only the frontend ever reads inside it —
// the same reasoning as Layout.Boxes. The unique index is partial for the
// same reason as Page's.
type CoverLetter struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_cover_letters_name,unique,where:deleted_at IS NULL" json:"name"`
Body string `gorm:"type:text;not null" json:"body"`
}
// CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into
// a letter as a copy. Section is the title of the section it was written for,
// only used to group the bank; a snippet can be dropped into any section.
type CoverSnippet struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Text string `gorm:"type:text;not null" json:"text"`
Section string `gorm:"not null;default:''" json:"section"`
}
+1 -1
View File
@@ -155,7 +155,7 @@ func tokenVersionOf(v uint) uint {
// verifies the signature and expiry, reads the id claim, loads the row, and
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
+21 -1
View File
@@ -54,12 +54,32 @@ func migrateDatabase(db *gorm.DB) error {
&models.Box{},
&models.Page{},
&models.Background{},
&models.Layout{},
&models.Component{},
&models.CoverLetter{},
&models.CoverSnippet{},
)
if err != nil {
return err
}
return nil
return ensureStpPage(db)
}
// ensureStpPage turns the home page (/stp) into an ordinary canvas Page once.
// It used to be a built-in canvas with its own route; its boxes and
// background were already keyed "stp", so a Page row with that slug is all
// it takes. Unscoped, so that deleting the page on purpose sticks rather than
// bringing it back on the next start.
func ensureStpPage(db *gorm.DB) error {
var count int64
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil
}
return db.Create(&models.Page{Slug: "stp", Title: "STP"}).Error
}
// InitDatabase connects to Postgres and runs the auto-migration.
+49
View File
@@ -0,0 +1,49 @@
package services
import (
"slices"
"adam-french.co.uk/backend/models"
)
// Per-service permissions: how a non-admin account is let into one gated
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
Label string
Path string
}
// PermissionTypes is the full set of grantable permissions, in display order.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
}
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key
})
}
// HasPermission reports whether user may use the service gated on key. It
// reads the row, not a token, so Admin here is the current database value.
func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key)
}
+54
View File
@@ -0,0 +1,54 @@
package services
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidPermission(t *testing.T) {
for _, p := range PermissionTypes {
if !ValidPermission(p.Key) {
t.Errorf("listed key %q reported invalid", p.Key)
}
}
for _, key := range []string{"", "admin", "Receipt", "receipt "} {
if ValidPermission(key) {
t.Errorf("unlisted key %q reported valid", key)
}
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
if seen[p.Key] {
t.Errorf("duplicate key %q", p.Key)
}
seen[p.Key] = true
for _, r := range p.Key {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
t.Errorf("key %q has %q; use lowercase letters, digits and '-'", p.Key, r)
}
}
}
}
func TestHasPermission(t *testing.T) {
cases := []struct {
name string
user models.User
want bool
}{
{"admin passes without a grant", models.User{Admin: true}, true},
{"granted user passes", models.User{Permissions: []string{"receipt"}}, true},
{"other grant does not count", models.User{Permissions: []string{"other"}}, false},
{"no grants (NULL column) fails", models.User{}, false},
}
for _, c := range cases {
if got := HasPermission(&c.user, "receipt"); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
+6 -1
View File
@@ -29,6 +29,11 @@ var logQuietDrop = map[string]bool{
"/auth/check": true, // front-end session check
}
// logQuietDropPrefix is the permission gate's auth_request subrequest
// (/auth/validate/<key>), dropped on 2xx for the same reason as
// /auth/validate-admin above: it repeats on every request to a gated page.
const logQuietDropPrefix = "/auth/validate/"
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
// signature so it plugs into gin.LoggerWithFormatter.
func TrafficLogFormatter(params gin.LogFormatterParams) string {
@@ -63,7 +68,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
// is still interesting (an expired session raging against refresh, a
// broken admin gate) and is kept.
if logQuietDrop[path] && params.StatusCode < 400 {
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
return ""
}
+9
View File
@@ -25,6 +25,15 @@ func TestTrafficFormatterDropsQuietHeartbeats(t *testing.T) {
}
}
func TestTrafficFormatterDropsPermissionGate(t *testing.T) {
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 200, "172.28.0.6", time.Millisecond)); out != "" {
t.Fatalf("permission-gate 200 should be dropped, got %q", out)
}
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 403, "172.28.0.6", time.Millisecond)); out == "" {
t.Fatal("a refused permission check must stay visible")
}
}
func TestTrafficFormatterKeepsHeartbeatFailures(t *testing.T) {
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 401, "172.28.0.6", time.Millisecond))
if out == "" {
+124 -3
View File
@@ -4,13 +4,16 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -184,13 +187,51 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
return prefix + name, nil
}
// StoredFile is one public upload, as listed for the admin's upload picker.
type StoredFile struct {
Name string `json:"name"`
URL string `json:"url"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
// List returns every public upload, newest first. Private files are never
// listed: they live in their own store, which this doesn't touch.
//
// The caller must be an admin. An upload's URL is public but unguessable, and
// that is the only thing keeping a file nobody linked to from being found; a
// listing anyone could read would hand every one of them out.
//
// Only names with an extension on the allow-list are returned, so anything
// else that ends up in the bucket or the directory (by hand, through
// garage-webui) never reaches a page through the picker.
func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
files, err := u.public.List(ctx)
if err != nil {
return nil, err
}
out := files[:0]
for _, f := range files {
if _, ok := UploadTypes[strings.ToLower(filepath.Ext(f.Name))]; ok {
f.URL = publicURLPrefix + f.Name
out = append(out, f)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Modified.After(out[j].Modified) })
return out, nil
}
// ---- Stores ----------------------------------------------------------------
// FileStore stores one file under key. 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.
// FileStore stores one file under key, and lists what it holds. r is a
// ReadSeeker because the S3 client must hash the body before sending it over
// plain HTTP, and because FallbackFileStore rewinds it to retry; a
// multipart.File satisfies it.
//
// List returns top-level files only, with URL unset (Uploads.List fills it).
type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
List(ctx context.Context) ([]StoredFile, error)
}
// DiskFileStore writes files into Dir, creating it if needed.
@@ -212,6 +253,31 @@ func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _
return out.Close()
}
// List skips subdirectories, which is what keeps the private/ directory
// (inside the public one on the volume) out of the listing. A directory that
// doesn't exist yet just holds nothing.
func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
entries, err := os.ReadDir(d.Dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var files []StoredFile
for _, e := range entries {
if !e.Type().IsRegular() {
continue
}
info, err := e.Info()
if err != nil {
continue // deleted between ReadDir and here
}
files = append(files, StoredFile{Name: e.Name(), Size: info.Size(), Modified: info.ModTime()})
}
return files, nil
}
// S3FileStore writes files into one bucket of an S3-compatible server.
type S3FileStore struct {
client *s3.Client
@@ -266,6 +332,31 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
return nil
}
// List pages through the whole bucket. Keys containing "/" are skipped: they
// are not uploads (Save never makes one) but something put under a prefix by
// hand, and nginx's /uploads/<name> only ever serves a top-level name anyway.
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
var files []StoredFile
pages := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{Bucket: aws.String(s.bucket)})
for pages.HasMorePages() {
page, err := pages.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("s3 list %s: %w", s.bucket, err)
}
for _, obj := range page.Contents {
key := aws.ToString(obj.Key)
if key == "" || strings.Contains(key, "/") {
continue
}
files = append(files, StoredFile{Name: key, Size: aws.ToInt64(obj.Size), Modified: aws.ToTime(obj.LastModified)})
}
}
return files, nil
}
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
// Fallback instead. The upload still succeeds and its URL still works (nginx
// looks in both places), so a Garage outage costs a log line rather than
@@ -286,3 +377,33 @@ func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r i
}
return f.Fallback.Put(ctx, key, contentType, r, size)
}
// List is the union of both stores, since nginx serves from both: the
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the
// fallback's files are returned alone, as for Put.
func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) {
primary, err := f.Primary.List(ctx)
if err != nil {
log.Printf("[upload] primary store failed to list, listing fallback only: %v", err)
primary = nil
}
fallback, fbErr := f.Fallback.List(ctx)
if fbErr != nil {
if err != nil {
return nil, fmt.Errorf("listing both stores: %v; %w", err, fbErr)
}
log.Printf("[upload] fallback store failed to list: %v", fbErr)
}
seen := make(map[string]bool, len(primary))
for _, file := range primary {
seen[file.Name] = true
}
for _, file := range fallback {
if !seen[file.Name] {
primary = append(primary, file)
}
}
return primary, nil
}
+98 -1
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
// Covered here: the type table (the upload trust boundary's data), Save's
@@ -21,7 +22,7 @@ import (
// 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
// Not covered: a successful PutObject or ListObjectsV2 against Garage. That needs the garage
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
// fileHeader builds the *multipart.FileHeader a handler would get from
@@ -59,6 +60,17 @@ func (r *recordingStore) Put(_ context.Context, key, contentType string, rd io.R
return nil
}
func (r *recordingStore) List(context.Context) ([]StoredFile, error) { return nil, nil }
// listStore lists a fixed set of files, or fails.
type listStore struct {
files []StoredFile
err error
}
func (l listStore) Put(context.Context, string, string, io.ReadSeeker, int64) error { return nil }
func (l listStore) List(context.Context) ([]StoredFile, error) { return l.files, l.err }
func TestUploadTypes(t *testing.T) {
t.Run("nothing executable or markup is allowed", func(t *testing.T) {
// Served from our own origin with no login, so anything a browser
@@ -209,3 +221,88 @@ func TestFallbackWhenBucketRefuses(t *testing.T) {
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(img))
}
}
func TestDiskFileStoreList(t *testing.T) {
if files, err := (DiskFileStore{Dir: filepath.Join(t.TempDir(), "missing")}).List(context.Background()); err != nil || len(files) != 0 {
t.Fatalf("missing dir: got %v, %v; want nothing and no error", files, err)
}
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "a.png"), []byte("abc"), 0644)
os.MkdirAll(filepath.Join(dir, "private"), 0755)
os.WriteFile(filepath.Join(dir, "private", "secret.png"), []byte("x"), 0644)
files, err := (DiskFileStore{Dir: dir}).List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 1 || files[0].Name != "a.png" || files[0].Size != 3 {
t.Fatalf("got %+v, want just a.png (3 bytes): private/ must not be listed", files)
}
}
func TestFallbackFileStoreList(t *testing.T) {
ctx := context.Background()
bucket := listStore{files: []StoredFile{{Name: "a.png", Size: 1}, {Name: "b.png"}}}
disk := listStore{files: []StoredFile{{Name: "a.png", Size: 2}, {Name: "c.png"}}}
files, err := FallbackFileStore{Primary: bucket, Fallback: disk}.List(ctx)
if err != nil {
t.Fatal(err)
}
names := map[string]int64{}
for _, f := range files {
names[f.Name] = f.Size
}
if len(files) != 3 || names["a.png"] != 1 || len(names) != 3 {
t.Errorf("got %+v, want a (from the bucket), b and c once each", files)
}
t.Run("bucket down", func(t *testing.T) {
files, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: disk}.List(ctx)
if err != nil || len(files) != 2 {
t.Errorf("got %+v, %v; want the disk's two files", files, err)
}
})
t.Run("both down", func(t *testing.T) {
_, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: listStore{err: errors.New("gone")}}.List(ctx)
if err == nil {
t.Error("want an error when neither store can list")
}
})
}
func TestFallbackListWhenBucketRefuses(t *testing.T) {
// The real S3 client against a server that refuses: the listing still
// comes back, from disk.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "on-disk.png"), pngBytes(), 0644)
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
files, err := u.List(context.Background())
if err != nil || len(files) != 1 || files[0].URL != "/uploads/on-disk.png" {
t.Fatalf("got %+v, %v; want the one disk file", files, err)
}
}
func TestUploadsList(t *testing.T) {
now := time.Now()
u := &Uploads{public: listStore{files: []StoredFile{
{Name: "old.png", Modified: now.Add(-time.Hour)},
{Name: "page.html", Modified: now},
{Name: "new.JPG", Modified: now.Add(-time.Minute)},
{Name: "noext", Modified: now},
}}}
files, err := u.List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 2 || files[0].URL != "/uploads/new.JPG" || files[1].URL != "/uploads/old.png" {
t.Fatalf("got %+v, want new.JPG then old.png, nothing off the allow-list", files)
}
}
+8
View File
@@ -0,0 +1,8 @@
# Dev notes vault
`OBSIDIAN_DIR` in `.env.dev` points here, so the dev stack's SilverBullet
instances and the backend's `/notes` endpoint have a vault to mount. Anything
you write here is gitignored; only this README is tracked.
It is deliberately not a git repository, so `silverbullet-git` logs that and
idles instead of syncing it anywhere.
+95 -3
View File
@@ -51,6 +51,13 @@ networks:
ipam:
config:
- subnet: 172.28.0.0/16
# The usaco site's code runner and nothing else but the site. internal:
# no route out, so code submitted to it cannot reach the internet, and
# being off app-network keeps it away from postgres, gitea, garage and the
# backend. Docker picks the subnet; nothing here pins an address on it.
usaco-runner-net:
driver: bridge
internal: true
# PERSISTENT vs EPHEMERAL state
# Named volumes below survive `docker compose down` and container rebuilds;
@@ -139,6 +146,11 @@ services:
aliases:
- ${DOMAIN}
- www.${DOMAIN}
# Fixed for cloudflared's extra_hosts (see there): an alias only
# exists while nginx is running, and this address is pinned to the
# same names for when it is not. Top of the /16 beside cloudflared's,
# away from docker's dynamic allocations.
ipv4_address: 172.28.255.251
ports:
- 80:80
- 443:443
@@ -220,6 +232,15 @@ services:
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
depends_on:
- nginx
# Pins the tunnel origin's names to nginx's fixed address. nginx's aliases
# vanish while it is stopped (every deploy and the weekly maintenance), and
# docker's DNS then forwards the name to public DNS, which answers with
# Cloudflare's own IPs: the tunnel sent requests back to the edge and
# visitors got error 1000. /etc/hosts wins over DNS, so a stopped nginx is
# now a refused connection, which cloudflared reports as a plain 502.
extra_hosts:
- "${DOMAIN}:172.28.255.251"
- "www.${DOMAIN}:172.28.255.251"
networks:
app-network:
ipv4_address: 172.28.255.250
@@ -441,11 +462,18 @@ services:
# inside the container. Since SilverBullet itself runs with no SB_USER, that
# gate is the only thing protecting it, so the blast radius stays here.
silverbullet-git:
image: alpine/git:v2.49.1
image: alpine/git:v2.54.0
container_name: "${SILVERBULLET_GIT_HOST:-silverbullet-git}"
restart: always
networks:
- app-network
# The vault's remotes are ssh://git@DOMAIN:2222/..., but nginx's network
# aliases make DOMAIN resolve to nginx on app-network, which has no :2222,
# so every pull and push was refused. /etc/hosts wins over Docker's DNS, so
# this sends DOMAIN back to the host, where gitea publishes 2222. The name
# is unchanged, so known_hosts still matches.
extra_hosts:
- "${DOMAIN}:host-gateway"
# Same uid SilverBullet writes as, so commits don't leave root-owned objects
# in .git that the host user can no longer clean up.
user: "1000:1000"
@@ -555,10 +583,23 @@ services:
# 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
# (status, link, notes, statement, explanations) back with USACO_GIT_TOKEN.
# CLAUDE_API_KEY powers the admin's Explain button (USACO_CLAUDE_MODEL picks
# the model; blank is claude-opus-5-5). Recording reviews also need
# USACO_OPENAI_API_KEY to transcribe, and keep the audio in Garage's
# private usaco-audio bucket when USACO_S3_* is set (the site refuses to
# start with only some S3_* set, so all five go together or not at all:
# the blank-key case blanks the rest). USACO_CLAUDE_MONTHLY_BUDGET (dollars,
# blank for none) stops new Claude jobs once a month's estimated spend
# reaches it. ./usaco-data holds that clone, the background jobs' records
# and the Claude spend ledger; deleting it is safe (it re-clones) but loses
# any answer not yet committed. The image runs as uid 1000, so the
# directory must be owned by it.
#
# On stop it lets running Claude jobs finish for up to SHUTDOWN_GRACE (5m
# by default) before exiting, so stop_grace_period must be longer than
# that, or Docker kills it mid-job.
#
# Same explicit `environment:` list as jobs. Like the tracker it has no
# login: visitors see solved problems, and AUTH_VALIDATE_URL decides who
# is the admin from the visitor's cookies.
@@ -566,18 +607,69 @@ services:
image: adam-french.co.uk/adamf/usaco:${USACO_IMAGE_TAG:-latest}
container_name: usaco
restart: always
stop_grace_period: 6m
depends_on:
- gitea
- usaco-runner
networks:
- app-network
- usaco-runner-net
environment:
- GIT_REMOTE_URL=http://${GITEA_HOST}:${GITEA_PORT}/adamf/usaco.git
- GIT_TOKEN=${USACO_GIT_TOKEN:-}
- WEBHOOK_SECRET=${USACO_WEBHOOK_SECRET:-}
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
- CLAUDE_API_KEY=${CLAUDE_API_KEY:-}
- CLAUDE_MODEL=${USACO_CLAUDE_MODEL:-}
- CLAUDE_MONTHLY_BUDGET=${USACO_CLAUDE_MONTHLY_BUDGET:-}
- TRANSCRIBE_API_KEY=${USACO_OPENAI_API_KEY:-}
- S3_ACCESS_KEY_ID=${USACO_S3_ACCESS_KEY_ID:-}
- S3_SECRET_ACCESS_KEY=${USACO_S3_SECRET_ACCESS_KEY:-}
- S3_ENDPOINT=${USACO_S3_ACCESS_KEY_ID:+http://garage:3900}
- S3_REGION=${USACO_S3_ACCESS_KEY_ID:+garage}
- S3_BUCKET=${USACO_S3_ACCESS_KEY_ID:+usaco-audio}
- RUNNER_URL=http://usaco-runner:8081
volumes:
- ./usaco-data:/data
# The usaco site's code runner (site/Dockerfile.runner in adamf/usaco):
# compiles and runs solutions against their tests, and lints them, for the
# admin's solve page. It runs submitted code, so it has no secrets (no
# environment at all) and is only on usaco-runner-net, which is internal:
# no internet, and nothing but the site can reach it. Published by
# adamf/usaco's CI, which rolls it before `usaco`; pin
# USACO_RUNNER_IMAGE_TAG to hold a version.
#
# The hardening is the point:
# read_only the image is not writable; only /tmp is
# tmpfs /tmp one directory per request, removed after. Must NOT be
# noexec: the compiled program runs from it. Its pages count
# against mem_limit.
# mem_limit, cpus
# on top of the runner's own per-program limits (512 MB
# address space, CPU time, 64 MB files, wall clock)
# pids_limit what stops a fork bomb: the runner does not set
# RLIMIT_NPROC (it counts the whole uid, the server's own
# threads included). The image's tini reaps the leftovers.
# cap_drop, no-new-privileges
# the runner needs no capabilities, and runs as uid 1000
usaco-runner:
image: adam-french.co.uk/adamf/usaco-runner:${USACO_RUNNER_IMAGE_TAG:-latest}
container_name: usaco-runner
restart: always
networks:
- usaco-runner-net
read_only: true
tmpfs:
- /tmp:size=256m,exec
mem_limit: 1g
cpus: 2
pids_limit: 128
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
# The activity tracker (time spent per app, site, walk...), served at
# /tracker/ with the prefix stripped. Built and published by its own repo
# (adamf/ccp on this Gitea), whose CI pulls :latest into this service on
+8 -1
View File
@@ -87,6 +87,11 @@
# SILVERBULLET_PUBLIC_HOST / _PORT
# public notes viewer upstream (defaulted below)
# PYTHON_HOST / PYTHON_PORT FastAPI upstream (defaulted below)
# RECEIPT_WEB_UPSTREAM host:port of the receipt printer server on
# stppi, over Tailscale (defaulted below to
# a dead port, so /receipt/ reads "offline")
# RECEIPT_WEB_TOKEN shared secret nginx adds to /receipt/
# requests (defaulted below to empty)
# DEV_MODE "true" only via docker-compose.dev.yml
# CERT_WATCH_INTERVAL optional, seconds between certificate-watch
# polls (default 60). Production only.
@@ -107,11 +112,13 @@ export SILVERBULLET_HOST="${SILVERBULLET_HOST:-silverbullet}"
export SILVERBULLET_PORT="${SILVERBULLET_PORT:-3000}"
export SILVERBULLET_PUBLIC_HOST="${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}"
export SILVERBULLET_PUBLIC_PORT="${SILVERBULLET_PUBLIC_PORT:-3000}"
export RECEIPT_WEB_UPSTREAM="${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}"
export RECEIPT_WEB_TOKEN="${RECEIPT_WEB_TOKEN:-}"
# The envsubst allow-list, defined once and reused by both full-config branches
# and by every partial, so the lists cannot drift apart. It MUST stay
# single-quoted here and be passed as "$ENVSUBST_VARS" (one argument) below.
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT} ${RECEIPT_WEB_UPSTREAM} ${RECEIPT_WEB_TOKEN}'
# Render the shared proxy route table. Done ONCE, here, ahead of the three-way
# decision, rather than inside each branch:
+89
View File
@@ -88,6 +88,11 @@
# nginx_dev_common.conf.template) and the garage-webui admin UI.
set $upstream_garage_web http://garage:3902;
set $upstream_garage_webui http://garage-webui:3909;
# The receipt printer's server is the one upstream OFF this host: it
# runs on stppi, which reaches the printer over the home LAN, and is
# reached over Tailscale by IP (MagicDNS names don't resolve in this
# container).
set $upstream_receipt "http://${RECEIPT_WEB_UPSTREAM}";
# ---- Backend API -----------------------------------------------------
# Two patterns repeat through every proxied location below:
@@ -538,6 +543,52 @@
proxy_set_header X-Forwarded-Proto $scheme;
}
# ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi
# (not in this stack: that machine reaches the printer on the home LAN). A page
# for printing a note or an uploaded image, plus its API. Behind the
# permission gate on `receipt`, so an account granted it in the admin
# panel can print without being an admin; the prefix IS stripped. The
# server trusts nothing without X-Receipt-Token, which only this proxy
# adds (proxy_set_header replaces any copy the client sent), and is
# told who is printing in X-Remote-User, likewise only set here. The
# token is quoted so an unset one still renders a valid config. When
# stppi is off or unreachable the connect fails fast and
# @receipt_offline answers.
location = /receipt {
return 301 /receipt/;
}
location ^~ /receipt/ {
set $auth_permission receipt;
auth_request /internal/auth/validate;
auth_request_set $auth_user $upstream_http_x_auth_user;
error_page 401 = @auth_denied;
error_page 403 = @auth_forbidden;
error_page 502 504 = @receipt_offline;
limit_req zone=api burst=10 nodelay;
# The server caps uploads at 16 MB; this leaves room for the
# multipart framing around one.
client_max_body_size 17m;
rewrite ^/receipt/(.*)$ /$1 break;
proxy_pass $upstream_receipt;
proxy_connect_timeout 3s;
# An image print (connect, dither, send) takes a few seconds; a
# dead printer socket gives up after escpos's 60 s timeout.
proxy_read_timeout 90s;
proxy_set_header X-Receipt-Token "${RECEIPT_WEB_TOKEN}";
proxy_set_header X-Remote-User $auth_user;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location @receipt_offline {
default_type text/plain;
return 503 "The receipt printer machine is offline.\n";
}
# Where the tracker used to be. The SPA routes were client-side, so
# these only catch bookmarks and typed URLs. The userscript's old
# @updateURL lands on the third, which is how installed copies find
@@ -590,3 +641,41 @@
location @auth_denied {
return 302 /admin/login?redirect=$request_uri;
}
# ---- Permission gate (/receipt/) ----
# The same auth_request mechanism as the admin gate above, but asking
# GET /auth/validate/<key> whether the session holds one named
# permission (services/permissions.go; admins hold them all). A gated
# location sets $auth_permission and points auth_request here:
#
# set $auth_permission <key>;
# auth_request /internal/auth/validate;
# error_page 401 = @auth_denied;
# error_page 403 = @auth_forbidden;
#
# The variable reaches the subrequest because nginx subrequests share
# the parent request's variables, and `set` runs in the rewrite phase,
# before auth_request's access phase. It must NOT also be given a
# default at server level: a subrequest re-runs the server-level
# rewrite phase, so that `set` would blank the shared value before
# this location reads it. (A location that forgets to set it asks for
# /auth/validate/, which matches no route: denied.) 401 (not signed in) goes to the
# login page as before; 403 (signed in, not granted) goes to a page
# that says so, since sending a signed-in user to log in again only
# shows them "Already signed in". On success the backend returns the
# username in X-Auth-User, which a location can forward with
# auth_request_set (see /receipt/). The body/limit settings are the
# admin-validate location's, for the same reasons.
location = /internal/auth/validate {
internal;
client_max_body_size 0;
rewrite ^ /auth/validate/$auth_permission break;
proxy_pass $upstream_backend;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Cookie $http_cookie;
}
location @auth_forbidden {
return 302 /no-access?path=$request_uri;
}
+115
View File
@@ -0,0 +1,115 @@
// =============================================================================
// renovate.json5 — dependency-update PRs (this repo's Dependabot).
//
// WHY RENOVATE AND NOT DEPENDABOT
// Dependabot only runs on GitHub, and this repo lives on the self-hosted
// Gitea. Renovate does the same job against Gitea's API. It is run by
// .gitea/workflows/renovate.yaml on the stack's own runner, which is where
// the platform, endpoint and token are set; this file is only *what* to
// update.
//
// WHAT IT WATCHES
// gomod backend/go.mod (go.sum and `go mod tidy` come along)
// npm vue/package.json + package-lock.json
// pip_requirements python/requirements.txt, requirements-dev.txt
// dockerfile every */Dockerfile FROM line
// docker-compose every image: in docker-compose*.yml
// custom (below) the images deploy.yaml and renovate.yaml `docker run`
//
// NOTHING IS AUTOMERGED, on purpose: a merge to main IS a deploy. Each
// Renovate branch is pushed to Gitea, so deploy.yaml's `test` job runs on it
// (go vet/test and pytest) — but that job skips the Vue build, so an npm PR is
// only proven by `make check-vue` locally or by the deploy itself (where a
// failed build stops before any container is replaced).
// =============================================================================
{
$schema: "https://docs.renovatebot.com/renovate-schema.json",
extends: ["config:recommended"],
timezone: "Europe/London",
// Replaces config:recommended's list rather than adding to it. .deprecated/
// holds parked services whose manifests are not built any more.
ignorePaths: ["**/node_modules/**", ".deprecated/**"],
// A release has to have been out this long before a PR proposes it, so a
// compromised or quickly-yanked version never reaches a branch.
minimumReleaseAge: "3 days",
postUpdateOptions: ["gomodTidy"],
customManagers: [
{
// deploy.yaml runs the tests in `docker run golang:… / python:…`, which
// no built-in manager reads. They must match backend/Dockerfile and
// python/Dockerfile (see deploy.yaml's header), so they share those
// images' groups below and land in the same PR. Also matches the
// Renovate image in renovate.yaml, and the copies in comments, which
// keeps those accurate.
customType: "regex",
managerFilePatterns: ["/^\\.gitea/workflows/[^/]+\\.ya?ml$/"],
matchStrings: ["(?<depName>golang|python|renovate/renovate):(?<currentValue>[0-9][\\w.-]*)"],
datasourceTemplate: "docker",
},
],
packageRules: [
// The job tracker, usaco and activity-tracker images are built by their
// own repos and roll themselves out on `:latest`; there is nothing here
// to bump.
{
matchDatasources: ["docker"],
matchPackageNames: ["adam-french.co.uk/**"],
enabled: false,
},
// A Postgres major needs a dump and restore of the dbdata volume (the new
// server refuses the old data directory), so it is done by hand, never
// from a PR.
{
matchDatasources: ["docker"],
matchPackageNames: ["postgres"],
matchUpdateTypes: ["major"],
enabled: false,
},
// Non-major updates batched per ecosystem, so the runner tests one branch
// a week per language instead of one per package. Majors stay separate.
// These come before the named groups below because a later matching rule
// wins: gqlgen and the go directive must not be swept in here.
{
matchManagers: ["gomod"],
matchUpdateTypes: ["minor", "patch", "digest"],
groupName: "Go modules (non-major)",
},
{
matchManagers: ["npm"],
matchUpdateTypes: ["minor", "patch"],
groupName: "npm (non-major)",
},
{
matchManagers: ["pip_requirements"],
matchUpdateTypes: ["minor", "patch"],
groupName: "Python packages (non-major)",
},
// One PR per toolchain: the Dockerfile base, the CI test image and (for
// Go) the go.mod `go` directive move together.
{
matchPackageNames: ["golang", "go"],
groupName: "Go toolchain",
},
{
matchDatasources: ["docker"],
matchPackageNames: ["python"],
groupName: "Python image",
},
// gqlgen's runtime and gqlparser are versioned together. If a bump breaks
// the build, regenerate (`go run github.com/99designs/gqlgen generate`)
// on the branch.
{
matchPackageNames: ["github.com/99designs/gqlgen", "github.com/vektah/gqlparser/**"],
groupName: "gqlgen",
},
],
}
+63 -14
View File
@@ -64,8 +64,9 @@ Two layout shells, defined in `src/router/index.js`:
| Path | Layout | Notes |
| --- | --- | --- |
| `/` | 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` |
| `/stp` | DefaultLayout | The personal home page: an ordinary canvas page (the `Page` with slug `stp`) served by the catch-all, see "The /stp canvas" below |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin`. The login page is everyone's, admin or not |
| `/account`, `/no-access` | DefaultLayout | `views/account/Account.vue`, guarded by `meta.requiresSignIn`: the gated services a non-admin has been granted. `/no-access` is where nginx's permission gate sends a signed-in visitor without the grant |
| `/automata`, `/hotels` | DefaultLayout | |
| `/shrines`, `/shrines/*` | DefaultLayout | All canvas pages via the catch-all: `/shrines` is an index whose links are Link boxes placed by hand |
| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there |
@@ -160,7 +161,10 @@ 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.
rendering it, and `mediaSize(file)` reads an image or video's dimensions
(from a `File` or a stored URL). `listUploads()` (admin only) lists every
public upload, newest first; `components/util/UploadPicker.vue` is the modal
that shows them as a grid to choose from.
`{ private: true }` (admin only) is for private chat attachments; never use
it for anything shown in a canvas box, whose sandboxed frame has no cookie.
@@ -224,14 +228,18 @@ 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
- **Pages.** `"index"` is the landing page
(`Landing.vue`), which is nothing but the canvas. Any other key is the slug of a **`Page`** (GraphQL
type, `stores/pages.js`), an admin-created page served at `/<slug>` by the
router's catch-all (`views/canvas/CanvasPage.vue`). Pages are created from
the admin panel's Pages tab (which also has a "New shrine" form, a blank page
under `shrines/`), or from the 404 of the address you want; each can start
from a layout in `views/canvas/pageStarters.js` (Blank, Notes board). Title, address and visibility are under "Page
from a layout in `views/canvas/pageStarters.js` (Blank, Notes board, Old /stp grid). Title, address and visibility are under "Page
settings" on the page; renaming moves its boxes, deleting takes them too.
`/stp` is one of these pages too (slug `stp`): it used to have its own route
(`Home3.vue`, now legacy), and the backend creates its `Page` row once at
start-up (`ensureStpPage` in `backend/services/database.go`), so it can be
renamed, hidden or deleted like any other.
The server refuses slugs that an SPA or nginx route would answer first
(`validateSlug` in `backend/graph/page_helpers.go`) — add to that list when
adding a route.
@@ -239,10 +247,38 @@ renders any page's boxes.
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
previews live and takes an uploaded, dropped or already-uploaded image
(`UploadPicker`). `DefaultLayout` paints
it behind the whole window, navbar included, while that canvas is mounted,
and falls back to the halftone. Renaming or deleting a page carries its
background along; an admin-only page's background is hidden with it.
- **Saved layouts.** A **`Layout`** (GraphQL type, `stores/layouts.js`) is a
named copy of one page's boxes and background, made with the "Layouts"
button next to "Background" (`LayoutPanel.vue`). "Load here" copies a layout
onto the page on screen; the admin panel's Pages tab copies one onto any page
without opening it. Loading onto a page with boxes asks whether to replace
them or add on top (copies stacked above). A replace first saves the page
as a layout called "<page> before <layout>, <time>", so it can be undone by
loading that back. They are copies, not links: editing a page never changes
a layout or another page. That is also how a layout moves: save it on one
page, load it on another. The copying happens on the server
(`backend/graph/layout_helpers.go`); the browser only sees names and box
counts. All of it is admin-only, since a layout keeps admin-only boxes.
- **Components.** A **`Component`** (GraphQL type, `stores/components.js`) is
a named HTML box. "+ New box" lists them and places a copy, an ordinary box.
The "Components" button (`ComponentPanel.vue`) can also place one
**linked**: the box has a `componentId`, the server answers with the
component's html in its `html` (`fillLinked` in
`backend/graph/component_helpers.go`), and saving the html in `BoxEditor`
saves the component, so every linked box on every page changes. Only the
html is shared; title, geometry, frame, shadow and visibility stay each box's own.
"Save as component" in the editor makes a component from an html box and
links it; "Detach" gives a linked box its own copy. Deleting a component
detaches its boxes first, so no page changes. A layout keeps both the link
and the html, and loading it links again only if the component still
exists. The built-in starters in `templates.js` are not listed directly:
"Import built-ins" in the panel makes them components, after which they can
be edited or deleted like the rest. Admin-only throughout.
- **Admin only.** A box or a page can be marked admin-only. The server never
sends those to anyone else, so they are fit for private notes; admins see
such boxes outlined, with a 🔒 in edit mode. The "Note" template starts
@@ -266,21 +302,32 @@ renders any page's boxes.
`/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;
the save fails. Dragging snaps a box's edges and centre to other boxes'
edges and centres and to the canvas's sides, centre and top, within 6 screen
px, and draws a pink guide along each line it then shares; a resize snaps
the dragged edge the same way. Elsewhere the 5px grid applies. The pure
geometry is `alignment.js`; the admin bar's "Align" button turns it off (kept
per browser by `editorPrefs.js`), and holding Ctrl/⌘ mid-drag skips it.
`BoxEditor.vue` is the side panel. Settings save on change;
HTML is a draft that previews live and saves with Save or Ctrl/Cmd+S, or
automatically on leaving the box (selecting another, clicking empty canvas,
Done, ✕).
CodeMirror is loaded only when that panel opens; the panel is teleported to
`<body>`.
`<body>`. Its width (drag the left edge, double-click to reset) and the
code's text size (A−/A+, or Ctrl/Cmd +/−/0 in the editor) are kept per
browser in localStorage by `editorPrefs.js`; the canvas pads itself by the
same width so it rescales beside the panel.
Image and video files dropped onto the canvas in edit mode are uploaded and
each becomes an unframed box at the drop point. "Insert upload" stores a
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
tag for it at the cursor. Starter HTML is in `templates.js`; links in a box
tag for it at the cursor; "Choose upload" does the same with a file already
stored, and "+ From uploads…" in the admin bar makes a box from one, as a
drop would (`UploadPicker`). Built-in starter HTML is in `templates.js` (imported as components, above); links in a box
need `target="_top"` or `_blank` (the Link templates set it), or they open
inside the frame. A canvas given a `starter` has an import button in edit
mode (it confirms first if the page isn't empty): 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.
mode (it confirms first if the page isn't empty): only `/` has one, "Import
old landing page", which recreates the old bio and links. The old `Home.vue`
grid (`defaultLayout.js`) is the "Old /stp grid" starter for a new page.
- **Phones (≤700px)** get no canvas: boxes stack full-width in `(y, x)` order at
their saved height, skipping any with `hideOnMobile`. There is no separate
mobile layout. To change the order, move boxes on the desktop canvas.
@@ -325,7 +372,7 @@ in its header comment; the summary:
| File | Status |
| --- | --- |
| `views/home3/Home3.vue` | live (`/stp`) — the box canvas; its widget boxes use **Intro3** and **Gym2** |
| `views/home3/Home3.vue` | legacy: `/stp`'s old route, before it became a canvas `Page`; no route. The rest of `views/home3/` (`BoxCanvas.vue` and friends) is live |
| `views/home/shrines/{Shrines,Demoman,GTO,Evangelion,Skipskipbenben}.vue` | the old `/shrines` index and hand-written shrines (Demoman a video wall, the rest `<Wip />`), unrouted; shrines are canvas pages now |
| `views/home/Home.vue` | legacy fixed grid that `/stp` used to be; no route. Its widgets are still live through `home3/widgetRegistry.js` |
| `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported |
@@ -334,7 +381,7 @@ in its header comment; the summary:
| `views/home/BadApple.vue` | unfinished ASCII video player; not imported |
| `views/CV/CVProgramming.vue` | live — the only CV template listed in `CV.vue` |
| `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable |
| `views/unused/CoverLetters.vue` | **live** despite the directory — it is the "Cover Letter" tab on `/cv` |
| `views/CV/CoverLetters.vue` (+ `CoverSnippetBank.vue`, `coverLetter.js`) | live — the "Cover Letter" tab on `/cv`. Sections of draggable paragraphs; an admin also gets saved letters (`CoverLetter`) and a paragraph bank (`CoverSnippet`), both `@admin` |
| `views/unused/Notes.vue` | no route points at it; not imported |
| `components/util/{MusicPlayer,ObjectTable}.vue` | not imported |
| `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported |
@@ -382,6 +429,8 @@ Note that Tailwind's spacing unit is set to **3px** (not the default 4px), so `p
- Never hard-code a colour in a component; use a token. The one exception is `<canvas>` drawing (MobileAutomata), which can't read CSS variables.
- Home widgets: wrap the title in `<Header>`; admin-only create forms use `<CreateToggle v-model="showCreate">` in the header's `#action` slot and render the form inside a `<Modal v-model="showCreate">` so it pops up over the page instead of replacing the widget.
- Crossfading content in place: `<Transition name="fade">` inside a `position: relative` parent. Route changes use `<Transition name="slide">`.
- Keyboard focus and reduced motion are handled globally in `styles.css`: every focusable element gets a pink `:focus-visible` ring (text fields a pink border instead), and `prefers-reduced-motion` collapses transitions and CSS animations. Both are low-specificity, so a component's own focus or outline style wins. A JS animation loop has to check `matchMedia("(prefers-reduced-motion: reduce)")` itself, as `Headline.vue` does.
- Forms are real `<form @submit.prevent>` elements with `type="submit"` / `type="button"` on their buttons, not `@keyup.enter` on each input: Enter then submits from any field and password managers recognise the login. A form that saves shows its error inline and disables its button while the request is out (`useCreateForm` returns `error` and `submitting` for this).
## Production Build
+38 -2
View File
@@ -6,9 +6,11 @@
* every token is BOTH a utility class in templates
* (text-primary, bg-surface, font-heading) AND a CSS variable
* in component <style> blocks (var(--color-primary)).
* 3. Base default look of plain HTML elements (the dark theme)
* 3. Base default look of plain HTML elements (the dark theme),
* including the keyboard focus ring
* 4. Components reusable classes: gif borders, A4 sheet, halftone background
* 5. Transitions <Transition name="slide"> and <Transition name="fade">
* 5. Transitions <Transition name="slide"> and <Transition name="fade">,
* and the reduced-motion override
* 6. Print
*
* The CV pages are a light theme: src/layouts/CVLayout.vue re-points the colour
@@ -150,6 +152,26 @@ textarea::placeholder {
opacity: 0.5;
}
/* Keyboard focus. Nothing on the site had a visible focus ring, so tabbing
through it was blind. Text fields get the border treatment the login form
had; everything else an outline. The selectors are wrapped in :where() to
keep their specificity just above the bare `input` rule above, so any
component with its own focus or outline style (BoxFrame, the hotels and
automata forms) still wins. Not in an @layer: unlayered rules such as
`input` above would then beat it whatever its specificity. */
:where(*):focus-visible {
outline: 2px solid var(--color-tertiary);
outline-offset: 2px;
}
:where(
input:not([type="checkbox"], [type="radio"], [type="range"], [type="file"]),
textarea
):focus-visible {
outline: none;
border-color: var(--color-tertiary);
box-shadow: 0 0 0 2px var(--color-quaternary);
}
table {
color: var(--color-primary);
border: 1px solid var(--color-primary);
@@ -255,6 +277,20 @@ th {
opacity: 0;
}
/* Visitors who ask the OS for less motion get instant route changes and
crossfades. The JS animation loops check the same query themselves
(Headline.vue for the navbar marquee). */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* ------------------------------------------------------------------ */
/* 6. Print */
/* ------------------------------------------------------------------ */
+3 -1
View File
@@ -1,12 +1,14 @@
<!--
The site's standard button. Wraps a native <button>, so all attributes and
listeners (including @click) fall through to it via Vue's attribute inheritance.
A disabled button is dimmed and stops reacting to hover and press, so a form
that is busy saving looks it.
-->
<script setup></script>
<template>
<button
class="text-primary bg-link-bg text-center border cursor-pointer transition-colors duration-150 ease-in-out hover:bg-surface active:scale-95"
class="px-2 text-primary bg-link-bg text-center border cursor-pointer transition-colors duration-150 ease-in-out hover:bg-surface active:scale-95 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-link-bg disabled:active:scale-100"
>
<slot />
</button>
+5
View File
@@ -51,6 +51,11 @@ function animate() {
let resizeObserver;
onMounted(() => {
// A visitor who asked the OS for less motion gets the text standing still.
// The CSS reduced-motion override in styles.css can't reach this: the
// movement is a transform written every frame, not a transition.
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
measureWidth();
rafId = requestAnimationFrame(animate);
+5 -329
View File
@@ -1,336 +1,12 @@
<script setup>
/**
* The chat widget: message list, composer, file attach, admin delete and an
* admins-only "private" channel. Drives stores/messages.js and is mounted in
* the right-hand sidebar of views/home/Home.vue.
*
* Admins see two tabs. The socket carries both channels in one stream (the
* server only sends private messages to admin connections), so the tab is a
* view over `messages` and also decides whether what you send is private —
* you cannot post to a channel you are not looking at.
*
* Owns the socket lifecycle — connect() on mount, disconnect() on unmount — so
* the socket exists only while the widget is on screen.
* The public chat widget. All of it is ChatPanel.vue; the admins-only channel
* is the separate PrivateChat.vue widget. This file keeps the name the canvas
* stores ("Chat" in widgetRegistry.js) pointing at the public channel.
*/
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import Button from "@/components/input/Button.vue";
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();
const messageInput = ref("");
const messagesContainer = ref(null);
const messagesInner = ref(null);
const fileInput = ref(null);
const isAdmin = computed(() => !!authStore.user.admin);
const activeTab = ref("public");
const isPrivateTab = computed(
() => isAdmin.value && activeTab.value === "private",
);
// The private tab is the only place private messages are shown, so the public
// tab stays public even for an admin.
const messages = computed(() =>
messagesStore.messages.filter((m) => !!m.private === isPrivateTab.value),
);
// Autoscroll only when the reader is already at the bottom: scrolling up to
// read history must not be yanked back down by an incoming message.
const isNearBottom = ref(true);
const SCROLL_THRESHOLD = 100;
let resizeObserver = null;
function scrollToBottom() {
if (messagesContainer.value) {
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
}
}
function scrollToBottomIfNear() {
if (isNearBottom.value) {
scrollToBottom();
}
}
function onScroll() {
if (!messagesContainer.value) return;
const { scrollHeight, scrollTop, clientHeight } = messagesContainer.value;
isNearBottom.value =
scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD;
}
function goToBottom() {
isNearBottom.value = true;
scrollToBottom();
}
// nextTick: scrollHeight is only correct once Vue has patched the new row in.
watch(
() => messages.value.length,
() => {
nextTick(scrollToBottomIfNear);
},
);
// A tab switch swaps the whole list, so start the new one at its newest message
// rather than at whatever scroll offset the old one left behind.
watch(activeTab, () => {
isNearBottom.value = true;
nextTick(scrollToBottom);
});
function sendMessage() {
const text = messageInput.value.trim();
if (!text) return;
isNearBottom.value = true;
messagesStore.sendMessage(text, isPrivateTab.value);
messageInput.value = "";
}
function deleteMessage(id) {
messagesStore.deleteMessage(id);
}
// Admin status is fixed when the socket connects (from the auth cookies), so
// reconnect after a login/logout to pick up or drop private messages. A
// demoted admin must also be moved off the private tab, which no longer has
// anything to show.
watch(isAdmin, (admin) => {
if (!admin) activeTab.value = "public";
if (!messagesStore.isConnected) return;
messagesStore.disconnect();
messagesStore.connect();
});
async function onFileSelected(e) {
const file = e.target.files[0];
if (!file) return;
isNearBottom.value = true;
// The private flag both routes the upload to /uploads/private/ and marks the
// message itself private; the two must agree.
await messagesStore.uploadAndSendFile(file, isPrivateTab.value);
fileInput.value.value = "";
}
// 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
// (exec returns null, resetting lastIndex) before returning. An early return
// from that loop would make the next message parse from the wrong offset.
const urlRegex = /(https?:\/\/[^\s<]+)/g;
/** Split message text into alternating {type:'text'|'link', value} parts so
* URLs can be rendered as anchors without using v-html. */
function parseMessageParts(text) {
const parts = [];
let lastIndex = 0;
let match;
while ((match = urlRegex.exec(text)) !== null) {
if (match.index > lastIndex) {
parts.push({
type: "text",
value: text.slice(lastIndex, match.index),
});
}
parts.push({ type: "link", value: match[1] });
lastIndex = urlRegex.lastIndex;
}
if (lastIndex < text.length) {
parts.push({ type: "text", value: text.slice(lastIndex) });
}
return parts;
}
onMounted(() => {
messagesStore.connect();
if (messagesContainer.value) {
messagesContainer.value.addEventListener("scroll", onScroll, {
passive: true,
});
}
// Images and videos load after their row is inserted and change its height,
// which the length watcher above has already missed. Observing the inner
// wrapper catches those late reflows.
if (messagesInner.value) {
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
resizeObserver.observe(messagesInner.value);
}
scrollToBottom();
});
onUnmounted(() => {
messagesStore.disconnect();
if (messagesContainer.value) {
messagesContainer.value.removeEventListener("scroll", onScroll);
}
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
});
import ChatPanel from "./ChatPanel.vue";
</script>
<template>
<div class="chat-root flex-col flex min-h-0">
<Header>{{ isPrivateTab ? "Private Chat" : "Chat" }}</Header>
<div v-if="isAdmin" class="flex gap-1 pt-1" role="tablist">
<button
type="button"
class="chat-tab flex-1"
role="tab"
:aria-selected="activeTab === 'public'"
:class="{ 'is-active': activeTab === 'public' }"
@click="activeTab = 'public'"
>
Public
</button>
<button
type="button"
class="chat-tab flex-1"
role="tab"
:aria-selected="activeTab === 'private'"
:class="{ 'is-active': activeTab === 'private' }"
@click="activeTab = 'private'"
>
🔒 Private
</button>
</div>
<div
ref="messagesContainer"
class="flex flex-col flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-2 min-w-0"
>
<div ref="messagesInner">
<p
v-for="message in messages"
:key="message.id"
class="break-words min-w-0 w-full"
:class="{ 'text-secondary italic': message.private }"
>
<button
v-if="isAdmin && message.id"
type="button"
class="text-tertiary hover:text-primary cursor-pointer mr-1"
aria-label="Delete message"
title="Delete message"
@click="deleteMessage(message.id)"
>
×
</button>
<span class="text-tertiary">{{ message.authorId }}:</span>
<template
v-for="(part, i) in parseMessageParts(message.text || '')"
:key="i"
>
<Link
v-if="part.type === 'link'"
bare
:href="part.value"
target="_blank"
class="text-primary underline break-all"
>{{ part.value }}</Link
>
<span v-else>{{ part.value }}</span>
</template>
<template v-if="isUploadUrl(message.fileUrl)">
<img
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="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
:href="message.fileUrl"
target="_blank"
class="underline break-all"
>{{ message.fileUrl.split("/").pop() }}</Link
>
</template>
</p>
</div>
</div>
<div>
<input
v-model="messageInput"
@keyup.enter="sendMessage"
:aria-label="isPrivateTab ? 'Private chat message' : 'Chat message'"
:placeholder="isPrivateTab ? 'Admins only' : ''"
/>
<input
ref="fileInput"
type="file"
:accept="ACCEPT.any"
class="hidden"
@change="onFileSelected"
/>
<div class="flex gap-2">
<Button class="flex-1" @click="sendMessage">Send</Button>
<Button v-if="isAdmin" class="flex-1" @click="fileInput.click()"
>Attach</Button
>
<Button v-if="!isNearBottom" class="flex-1" @click="goToBottom"
>Bottom</Button
>
</div>
</div>
</div>
<ChatPanel />
</template>
<style scoped>
.chat-tab {
padding: 2px 6px;
color: var(--color-primary);
background-color: var(--color-link-bg);
border: 1px solid transparent;
font-family: var(--font-heading);
font-size: 0.875rem;
cursor: pointer;
transition:
background-color 120ms ease,
border-color 120ms ease,
color 120ms ease;
}
.chat-tab:hover {
border-color: var(--color-primary);
}
.chat-tab.is-active {
border-color: var(--color-primary);
color: var(--color-tertiary);
background-color: var(--color-surface-tint);
}
@media (max-width: 850px) {
.chat-root {
max-height: none;
height: 100%;
}
}
</style>
+275
View File
@@ -0,0 +1,275 @@
<script setup>
/**
* One chat channel: message list, composer, file attach and admin delete.
* Drives stores/messages.js. Not a widget itself — Chat.vue shows the public
* channel and PrivateChat.vue the admins-only one.
*
* The socket carries both channels in one stream (the server only sends
* private messages to admin connections), so `isPrivate` picks which half of
* `messages` to show and also marks what you send — you cannot post to a
* channel you are not looking at.
*
* Holds the socket while mounted — connect() on mount, disconnect() on
* unmount; the store counts them, so two panels share one socket and it
* exists only while a chat is on screen.
*/
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import Button from "@/components/input/Button.vue";
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();
const messageInput = ref("");
const messagesContainer = ref(null);
const messagesInner = ref(null);
const fileInput = ref(null);
const isAdmin = computed(() => !!authStore.user.admin);
const props = defineProps({
// Only PrivateChat.vue sets this, and it mounts the panel for admins only.
isPrivate: { type: Boolean, default: false },
});
// The private panel is the only place private messages are shown, so the
// public one stays public even for an admin.
const messages = computed(() =>
messagesStore.messages.filter((m) => !!m.private === props.isPrivate),
);
// Autoscroll only when the reader is already at the bottom: scrolling up to
// read history must not be yanked back down by an incoming message.
const isNearBottom = ref(true);
const SCROLL_THRESHOLD = 100;
let resizeObserver = null;
function scrollToBottom() {
if (messagesContainer.value) {
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
}
}
function scrollToBottomIfNear() {
if (isNearBottom.value) {
scrollToBottom();
}
}
function onScroll() {
if (!messagesContainer.value) return;
const { scrollHeight, scrollTop, clientHeight } = messagesContainer.value;
isNearBottom.value =
scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD;
}
function goToBottom() {
isNearBottom.value = true;
scrollToBottom();
}
// nextTick: scrollHeight is only correct once Vue has patched the new row in.
watch(
() => messages.value.length,
() => {
nextTick(scrollToBottomIfNear);
},
);
function sendMessage() {
const text = messageInput.value.trim();
if (!text) return;
isNearBottom.value = true;
messagesStore.sendMessage(text, props.isPrivate);
messageInput.value = "";
}
function deleteMessage(id) {
messagesStore.deleteMessage(id);
}
async function onFileSelected(e) {
const file = e.target.files[0];
if (!file) return;
isNearBottom.value = true;
// The private flag both routes the upload to /uploads/private/ and marks the
// message itself private; the two must agree.
await messagesStore.uploadAndSendFile(file, props.isPrivate);
fileInput.value.value = "";
}
// 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
// (exec returns null, resetting lastIndex) before returning. An early return
// from that loop would make the next message parse from the wrong offset.
const urlRegex = /(https?:\/\/[^\s<]+)/g;
/** Split message text into alternating {type:'text'|'link', value} parts so
* URLs can be rendered as anchors without using v-html. */
function parseMessageParts(text) {
const parts = [];
let lastIndex = 0;
let match;
while ((match = urlRegex.exec(text)) !== null) {
if (match.index > lastIndex) {
parts.push({
type: "text",
value: text.slice(lastIndex, match.index),
});
}
parts.push({ type: "link", value: match[1] });
lastIndex = urlRegex.lastIndex;
}
if (lastIndex < text.length) {
parts.push({ type: "text", value: text.slice(lastIndex) });
}
return parts;
}
onMounted(() => {
messagesStore.connect();
if (messagesContainer.value) {
messagesContainer.value.addEventListener("scroll", onScroll, {
passive: true,
});
}
// Images and videos load after their row is inserted and change its height,
// which the length watcher above has already missed. Observing the inner
// wrapper catches those late reflows.
if (messagesInner.value) {
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
resizeObserver.observe(messagesInner.value);
}
scrollToBottom();
});
onUnmounted(() => {
messagesStore.disconnect();
if (messagesContainer.value) {
messagesContainer.value.removeEventListener("scroll", onScroll);
}
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
});
</script>
<template>
<div class="chat-root flex-col flex min-h-0">
<Header>{{ isPrivate ? "🔒 Private Chat" : "Chat" }}</Header>
<div
ref="messagesContainer"
class="flex flex-col flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-2 min-w-0"
>
<div ref="messagesInner">
<p
v-for="message in messages"
:key="message.id"
class="break-words min-w-0 w-full"
:class="{ 'text-secondary italic': message.private }"
>
<button
v-if="isAdmin && message.id"
type="button"
class="text-tertiary hover:text-primary cursor-pointer mr-1"
aria-label="Delete message"
title="Delete message"
@click="deleteMessage(message.id)"
>
×
</button>
<span class="text-tertiary">{{ message.authorId }}:</span>
<template
v-for="(part, i) in parseMessageParts(message.text || '')"
:key="i"
>
<Link
v-if="part.type === 'link'"
bare
:href="part.value"
target="_blank"
class="text-primary underline break-all"
>{{ part.value }}</Link
>
<span v-else>{{ part.value }}</span>
</template>
<template v-if="isUploadUrl(message.fileUrl)">
<img
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="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
:href="message.fileUrl"
target="_blank"
class="underline break-all"
>{{ message.fileUrl.split("/").pop() }}</Link
>
</template>
</p>
</div>
</div>
<div>
<input
v-model="messageInput"
@keyup.enter="sendMessage"
:aria-label="isPrivate ? 'Private chat message' : 'Chat message'"
:placeholder="isPrivate ? 'Admins only' : ''"
/>
<input
ref="fileInput"
type="file"
:accept="ACCEPT.any"
class="hidden"
@change="onFileSelected"
/>
<div class="flex gap-2">
<Button class="flex-1" @click="sendMessage">Send</Button>
<Button v-if="isAdmin" class="flex-1" @click="fileInput.click()"
>Attach</Button
>
<Button v-if="!isNearBottom" class="flex-1" @click="goToBottom"
>Bottom</Button
>
</div>
</div>
</div>
</template>
<style scoped>
@media (max-width: 850px) {
.chat-root {
max-height: none;
height: 100%;
}
}
</style>
+10 -1
View File
@@ -7,9 +7,12 @@ defineProps({
title: { type: String, default: "Are you sure?" },
message: { type: String, required: true },
confirmLabel: { type: String, default: "Confirm" },
// A second, milder choice beside the confirm button, e.g. "Add on top"
// next to "Replace". Omitted, there are only Confirm and Cancel.
secondaryLabel: { type: String, default: "" },
});
const emit = defineEmits(["confirm", "cancel"]);
const emit = defineEmits(["confirm", "secondary", "cancel"]);
function cancel() {
open.value = false;
@@ -20,6 +23,11 @@ function confirm() {
open.value = false;
emit("confirm");
}
function secondary() {
open.value = false;
emit("secondary");
}
</script>
<template>
@@ -29,6 +37,7 @@ function confirm() {
<p>{{ message }}</p>
<div class="actions">
<button type="button" class="confirm-button" @click="confirm">{{ confirmLabel }}</button>
<button v-if="secondaryLabel" type="button" @click="secondary">{{ secondaryLabel }}</button>
<button type="button" class="cancel-button" @click="cancel">Cancel</button>
</div>
</div>
+24
View File
@@ -0,0 +1,24 @@
<script setup>
/**
* The admins-only chat widget: ChatPanel.vue on the private channel.
*
* The panel is mounted for admins only, so a non-admin never holds the socket
* on its account. The box itself is not hidden: a canvas box shows to everyone
* unless it is marked admin-only, and an empty box would look broken.
*/
import { computed } from "vue";
import ChatPanel from "./ChatPanel.vue";
import Header from "@/components/text/Header.vue";
import { useAuthStore } from "@/stores/auth";
const auth = useAuthStore();
const isAdmin = computed(() => !!auth.user.admin);
</script>
<template>
<ChatPanel v-if="isAdmin" is-private />
<div v-else>
<Header>🔒 Private Chat</Header>
<p class="p-2 text-tertiary">Admins only.</p>
</div>
</template>
+147
View File
@@ -0,0 +1,147 @@
<script setup>
/**
* Choose a file that is already uploaded, instead of uploading it again: a
* modal grid of every public upload (listUploads in @/uploads), newest first.
* Admin only, because the listing is. Used by the canvas's Background panel,
* Box editor and "+ From uploads" button.
*
* <UploadPicker v-if="picking" v-model="picking" :kinds="['image']" @pick="use" />
*
* `kinds` filters by kindOf(url). The bucket holds hundreds of megabytes, so
* thumbnails load lazily and videos fetch only their metadata.
*/
import { computed, ref } from "vue";
import { kindOf, listUploads } from "@/uploads";
import OverlayShell from "./OverlayShell.vue";
const open = defineModel({ type: Boolean, default: false });
const props = defineProps({
kinds: { type: Array, default: () => ["image"] },
title: { type: String, default: "Choose an upload" },
});
const emit = defineEmits(["pick", "close"]);
const files = ref([]);
const loading = ref(true);
const error = ref("");
const filter = ref("");
listUploads()
.then((all) => (files.value = all.filter((f) => props.kinds.includes(kindOf(f.url)))))
.catch((err) => (error.value = err?.message || "Couldn't list uploads"))
.finally(() => (loading.value = false));
const shown = computed(() => {
const q = filter.value.trim().toLowerCase();
return q ? files.value.filter((f) => f.name.toLowerCase().includes(q)) : files.value;
});
function describe(f) {
const kb = f.size / 1024;
const size = kb < 1024 ? `${Math.round(kb)} KB` : `${(kb / 1024).toFixed(1)} MB`;
return `${f.name} · ${size} · ${new Date(f.modified).toLocaleString()}`;
}
function close() {
open.value = false;
emit("close");
}
function pick(f) {
emit("pick", f.url);
close();
}
</script>
<template>
<OverlayShell v-model="open" :title="title" backdrop close-on-backdrop @close="close">
<div class="picker bdr-2 bg-surface">
<header class="flex items-center gap-2">
<h3 class="m-0 flex-1">{{ title }}</h3>
<input v-model="filter" type="search" placeholder="Filter by name" class="filter" />
<button type="button" class="close" title="Close" @click="close">✕</button>
</header>
<p v-if="loading" class="state">Loading…</p>
<p v-else-if="error" class="state text-tertiary">{{ error }}</p>
<p v-else-if="!shown.length" class="state">
{{ files.length ? "Nothing matches." : "No uploads yet." }}
</p>
<div v-else class="grid">
<button v-for="f in shown" :key="f.name" type="button" class="tile" :title="describe(f)" @click="pick(f)">
<img v-if="kindOf(f.url) === 'image'" :src="f.url" alt="" loading="lazy" />
<video v-else-if="kindOf(f.url) === 'video'" :src="f.url" preload="metadata" muted></video>
<span v-else class="name">{{ f.name }}</span>
</button>
</div>
</div>
</OverlayShell>
</template>
<style scoped>
.picker {
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 0.6rem;
width: min(760px, calc(100vw - 24px));
height: min(600px, calc(100vh - 24px));
padding: 0.75rem;
color: var(--color-secondary);
}
.filter {
min-width: 0;
width: 12rem;
padding: 3px 5px;
color: var(--color-secondary);
background: var(--color-surface-deep);
border: 1px solid var(--color-quaternary);
}
.close {
color: var(--color-primary);
background: var(--color-link-bg);
border: 1px solid var(--color-primary);
padding: 0 0.5rem;
cursor: pointer;
}
.state {
color: var(--color-muted);
}
.grid {
flex: 1;
overflow-y: auto;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
grid-auto-rows: 120px;
gap: 0.5rem;
}
.tile {
display: flex;
align-items: center;
justify-content: center;
padding: 0;
overflow: hidden;
background: var(--color-surface-deep);
border: 2px solid var(--color-quaternary);
cursor: pointer;
}
.tile:hover,
.tile:focus-visible {
border-color: var(--color-primary);
}
.tile img,
.tile video {
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
.name {
padding: 0.25rem;
font-size: 0.75rem;
word-break: break-all;
color: var(--color-muted);
}
</style>
+20 -4
View File
@@ -1,8 +1,11 @@
// The shared body of the admin "create X" forms (CreatePost, CreateFavorite,
// CreateActivity, CreateBookmark): a ref per field, a GraphQL mutation taking a
// single `input`, clear the fields on success, then emit "done" so the host
// modal can close. Failures are logged and leave the fields alone, exactly as
// the hand-written versions did.
// modal can close. A failure leaves the fields alone and its message on
// `error` for the form to show — it used to go only to the console, so a
// refused save looked exactly like a button that did nothing. `submitting`
// disables the button while the request is out, and a second submit in that
// window is ignored, so a double click cannot create the row twice.
import { ref } from "vue";
import { gql } from "@/graphql";
@@ -15,7 +18,12 @@ import { gql } from "@/graphql";
* @param {string[]} [options.optional] fields sent as undefined when blank,
* so the backend sees "not set" rather than an empty string
* @param {string} [options.resultKey] mutation field to log on success
* @returns {{ values: Record<string, import("vue").Ref<string>>, submit: () => Promise<void> }}
* @returns {{
* values: Record<string, import("vue").Ref<string>>,
* submit: () => Promise<void>,
* error: import("vue").Ref<string>,
* submitting: import("vue").Ref<boolean>,
* }}
*/
export function useCreateForm({
mutation,
@@ -25,8 +33,13 @@ export function useCreateForm({
resultKey,
}) {
const values = Object.fromEntries(fields.map((name) => [name, ref("")]));
const error = ref("");
const submitting = ref(false);
async function submit() {
if (submitting.value) return;
submitting.value = true;
error.value = "";
try {
const input = {};
for (const name of fields) {
@@ -39,8 +52,11 @@ export function useCreateForm({
emit("done");
} catch (err) {
console.error(err);
error.value = err?.message || "Failed to save";
} finally {
submitting.value = false;
}
}
return { values, submit };
return { values, submit, error, submitting };
}
+31 -12
View File
@@ -1,5 +1,5 @@
/**
* Route table and the single admin route guard.
* Route table and the single sign-in/admin route guard.
*
* Structure: two layout shells. `/` mounts DefaultLayout (navbar + footer, dark
* theme) and holds most routes; `/cv` mounts CVLayout (light print theme).
@@ -33,11 +33,6 @@ const router = createRouter({
name: "landing",
component: Landing,
},
{
path: "stp",
name: "home",
component: () => import("@/views/home3/Home3.vue"),
},
{
path: "admin/login",
name: "admin-login",
@@ -49,6 +44,21 @@ const router = createRouter({
component: () => import("@/views/admin/Admin.vue"),
meta: { requiresAdmin: true },
},
// A signed-in user's own page: the gated services they have
// been granted. /no-access is the same page with a notice,
// where nginx's permission gate sends a refused visitor.
{
path: "account",
name: "account",
component: () => import("@/views/account/Account.vue"),
meta: { requiresSignIn: true },
},
{
path: "no-access",
name: "no-access",
component: () => import("@/views/account/Account.vue"),
meta: { requiresSignIn: true },
},
{
path: "automata",
name: "mobile-automata",
@@ -60,9 +70,16 @@ const router = createRouter({
name: "cheap-hotels",
component: () => import("@/views/hotels/CheapHotels.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
{
path: "architecture",
name: "architecture",
component: () =>
import("@/views/architecture/Architecture.vue"),
},
// /stp, /shrines and the shrines under it are canvas pages,
// made from the admin panel's Pages tab and served by the
// catch-all below. /stp's old route (views/home3/Home3.vue)
// and the hand-written shrines (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.
@@ -94,7 +111,8 @@ const router = createRouter({
],
});
// Guard for routes marked `meta: { requiresAdmin: true }`.
// Guard for routes marked `meta: { requiresAdmin: true }` or
// `meta: { requiresSignIn: true }` (any account, admin or not).
//
// The admin flag arrives asynchronously, so navigating straight to /admin on a
// cold load would otherwise read an empty user and bounce a legitimate admin to
@@ -107,10 +125,11 @@ const router = createRouter({
// as "not signed in" — and `user` is re-read on every navigation, so a login or
// logout during the session is honoured.
router.beforeEach(async (to) => {
if (!to.meta.requiresAdmin) return;
if (!to.meta.requiresAdmin && !to.meta.requiresSignIn) return;
const auth = useAuthStore();
await auth.ensureLoaded();
if (!auth.user.admin)
const allowed = to.meta.requiresAdmin ? auth.user.admin : auth.loggedIn;
if (!allowed)
return { path: "/admin/login", query: { redirect: to.fullPath } };
});
+41 -5
View File
@@ -23,6 +23,11 @@ import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { gql } from "@/graphql";
// The user fields every query here selects, so `user` has the same shape
// whichever one filled it. `permissions` is the list of gated services
// (/receipt/ and so on) a non-admin may open; see views/Account.vue.
export const USER_FIELDS = "id username admin permissions";
export const useAuthStore = defineStore("auth", () => {
const user = ref({});
const loggedIn = computed(() => !!user.value.username);
@@ -71,7 +76,7 @@ export const useAuthStore = defineStore("auth", () => {
if (resolved.value) return Promise.resolve();
if (!pending) {
const requestedAt = epoch;
pending = gql(`query Me { me { id username admin } }`)
pending = gql(`query Me { me { ${USER_FIELDS} } }`)
.then((data) => adoptSession(data.me, requestedAt))
.catch((err) => console.error("me query failed:", err))
.finally(() => {
@@ -98,7 +103,7 @@ export const useAuthStore = defineStore("auth", () => {
async function logIn(username, password) {
try {
const data = await gql(
`mutation Login($input: LoginInput!) { login(input: $input) { user { id username admin } } }`,
`mutation Login($input: LoginInput!) { login(input: $input) { user { ${USER_FIELDS} } } }`,
{ input: { username, password } },
);
user.value = data.login.user;
@@ -113,7 +118,7 @@ export const useAuthStore = defineStore("auth", () => {
async function createUser(username, password) {
try {
const data = await gql(
`mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id username admin } }`,
`mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { ${USER_FIELDS} } }`,
{ input: { username, password } },
);
return data.createUser;
@@ -128,7 +133,7 @@ export const useAuthStore = defineStore("auth", () => {
async function refreshToken() {
try {
const data = await gql(
`mutation { refreshToken { user { id username admin } } }`,
`mutation { refreshToken { user { ${USER_FIELDS} } } }`,
);
user.value = data.refreshToken.user;
markSessionChanged();
@@ -141,7 +146,7 @@ export const useAuthStore = defineStore("auth", () => {
async function setUserAdmin(userId, admin) {
try {
const data = await gql(
`mutation SetUserAdmin($id: ID!, $admin: Boolean!) { setUserAdmin(id: $id, admin: $admin) { id username admin } }`,
`mutation SetUserAdmin($id: ID!, $admin: Boolean!) { setUserAdmin(id: $id, admin: $admin) { ${USER_FIELDS} } }`,
{ id: userId, admin },
);
return data.setUserAdmin;
@@ -151,6 +156,34 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: replace a user's permission list. Returns the updated user;
* re-throws. */
async function setUserPermissions(userId, permissions) {
try {
const data = await gql(
`mutation SetUserPermissions($id: ID!, $permissions: [String!]!) { setUserPermissions(id: $id, permissions: $permissions) { ${USER_FIELDS} } }`,
{ id: userId, permissions },
);
return data.setUserPermissions;
} catch (err) {
console.error(err);
throw err;
}
}
/** Signed-in only: every grantable service, as [{ key, label, path }].
* Re-throws. */
async function fetchPermissionTypes() {
const data = await gql(`query { permissionTypes { key label path } }`);
return data.permissionTypes;
}
/** Whether the signed-in user may open the service gated on `key`. Admins
* may open them all, as on the server. */
function can(key) {
return !!user.value.admin || (user.value.permissions ?? []).includes(key);
}
return {
user,
@@ -165,5 +198,8 @@ export const useAuthStore = defineStore("auth", () => {
logOut,
createUser,
setUserAdmin,
setUserPermissions,
fetchPermissionTypes,
can,
};
});
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* Page backgrounds (the `Background` GraphQL type), one per canvas page key —
* "index" for the landing page, "stp", or a Page slug such as
* "index" for the landing page, or a Page slug such as "stp" or
* "shrines/evangelion" — and which one is on screen.
*
* DefaultLayout paints `style` behind everything, navbar included, so a
+31 -4
View File
@@ -2,8 +2,8 @@
* 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
* `useBoxesStore(page)` returns the store for that page key: "index" for the
* landing page, or a Page slug ("stp" for the home page). 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.
*
@@ -14,6 +14,11 @@
* 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.
*
* A box with a `componentId` is linked to that component (stores/components.js):
* the server answers with the component's html in `html`, and editing it goes
* to the component. patchLinked() keeps every page already loaded in step when
* a component changes, without refetching them.
*/
import { createCrudStore } from "@/stores/createCrudStore";
@@ -31,13 +36,18 @@ const BOX_FIELDS = `
h
z
framed
shadow
hideOnMobile
adminOnly
componentId
`;
// 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"];
// same box — or componentId, which keeps a copy of a linked box linked;
// geometry is offset so the copy is visibly separate.
const COPIED = [
"page", "kind", "widget", "html", "title", "w", "h", "framed", "shadow", "hideOnMobile", "adminOnly", "componentId",
];
const stores = new Map();
@@ -64,6 +74,11 @@ function defineFor(page) {
const input = Object.fromEntries(COPIED.map((k) => [k, box[k]]));
return create({ ...input, x: box.x + 20, y: box.y + 20, z: topZ() });
},
/** Swap in a box the server answered with from outside this store. */
replaceLocal: (box) => {
const idx = items.value.findIndex((b) => b.id === box.id);
if (idx >= 0) items.value[idx] = box;
},
};
},
});
@@ -74,3 +89,15 @@ export function useBoxesStore(page) {
if (!stores.has(page)) stores.set(page, defineFor(page));
return stores.get(page)();
}
/**
* Apply `patch` to every loaded box linked to component `componentId`, on
* every page visited so far.
*/
export function patchLinked(componentId, patch) {
for (const use of stores.values()) {
for (const box of use().boxes) {
if (box.componentId === componentId) Object.assign(box, patch);
}
}
}
+151
View File
@@ -0,0 +1,151 @@
/**
* Saved components (the `Component` GraphQL type): named HTML boxes that can
* be placed on any canvas page as a copy or linked — full CRUD, built on
* createCrudStore(), plus the box-side actions.
*
* A linked box shows its component's html, so `update` is wrapped to push a
* new html into every loaded page's boxes (stores/boxes.js patchLinked), and
* `remove` unlinks them locally the way the server just did (each keeps the
* html it showed). `uses` is kept roughly right locally (countUse) as this
* tab places, detaches and deletes linked boxes, and the panel refetches the
* list when it opens for the true figure.
*
* Admin only, so nothing fetches it until an admin opens the canvas's
* Components panel or "+ New box" menu (views/home3/ComponentPanel.vue,
* BoxCanvas.vue).
*/
import { createCrudStore } from "@/stores/createCrudStore";
import { gql } from "@/graphql";
import { patchLinked, useBoxesStore } from "@/stores/boxes";
import { TEMPLATES } from "@/views/home3/templates";
const COMPONENT_FIELDS = `
id
name
title
html
w
h
framed
shadow
adminOnly
uses
`;
// Matches BOX_FIELDS in stores/boxes.js, for the mutations that answer with
// a box.
const BOX_FIELDS = `
id page kind widget html title x y w h z framed shadow hideOnMobile adminOnly componentId
`;
export const useComponentsStore = createCrudStore("components", {
type: "Component",
list: "components",
fields: COMPONENT_FIELDS,
// Created ones are put back in name order by sort() below.
insert: "append",
deleteReturns: "object",
extend: ({ items, fetch, create, update, remove }) => {
const sort = () => items.value.sort((a, b) => a.name.localeCompare(b.name));
const countUse = (id, delta) => {
const c = items.value.find((c) => c.id === id);
if (c) c.uses = Math.max(0, c.uses + delta);
};
return {
countUse,
async create(input) {
const created = await create(input);
sort();
return created;
},
async update(id, input) {
const updated = await update(id, input);
if ("html" in input) patchLinked(id, { html: updated.html });
sort();
return updated;
},
async remove(id) {
await remove(id);
patchLinked(id, { componentId: null });
},
/**
* Make html box `box` into a component named `name` and link it.
* Throws on failure.
*/
async saveFromBox(box, name) {
const data = await gql(
`mutation SaveBoxAsComponent($id: ID!, $name: String!) {
saveBoxAsComponent(id: $id, name: $name) { ${BOX_FIELDS} }
}`,
{ id: box.id, name },
);
useBoxesStore(box.page).replaceLocal(data.saveBoxAsComponent);
await fetch();
},
/** Give linked box `box` its own copy of the html. Throws on failure. */
async detach(box) {
const data = await gql(
`mutation DetachBox($id: ID!) { detachBox(id: $id) { ${BOX_FIELDS} } }`,
{ id: box.id },
);
useBoxesStore(box.page).replaceLocal(data.detachBox);
countUse(box.componentId, -1);
},
/**
* Put `component` on page key `page` at `at` ({ x, y, z }): linked, or
* as an ordinary box with a copy of its html. Answers with the new box.
* Throws on failure.
*/
async place(component, page, at, linked) {
const input = {
kind: "html",
title: component.title,
w: component.w,
h: component.h,
framed: component.framed,
shadow: component.shadow,
adminOnly: component.adminOnly,
...at,
};
if (linked) input.componentId = component.id;
else input.html = component.html;
const created = await useBoxesStore(page).create(input);
if (linked) countUse(component.id, 1);
return created;
},
/**
* Create a component from each built-in starter in templates.js whose
* name is free, and answer with how many were added. Deleted ones come
* back; ones still there are left as they are. Throws on failure.
*/
async importBuiltins() {
const taken = new Set(items.value.map((c) => c.name));
let added = 0;
for (const t of TEMPLATES) {
if (taken.has(t.label)) continue;
await create({
name: t.label,
title: t.title,
html: t.html,
w: t.size[0],
h: t.size[1],
framed: t.framed ?? true,
adminOnly: t.adminOnly ?? false,
});
added++;
}
sort();
return added;
},
};
},
});
+28
View File
@@ -0,0 +1,28 @@
/**
* Saved cover letters (the `CoverLetter` GraphQL type) for the /cv Cover
* Letter tab — full CRUD, built on createCrudStore().
*
* `body` is the whole letter as a JSON string; views/CV/coverLetter.js owns
* its shape (parseBody / serialize), the server only checks it is an object.
*
* Admin only, so nothing fetches it until views/CV/CoverLetters.vue sees an
* admin signed in.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const COVER_LETTER_FIELDS = `
id
name
body
updatedAt
`;
export const useCoverLettersStore = createCrudStore("coverLetters", {
type: "CoverLetter",
list: "coverLetters",
fields: COVER_LETTER_FIELDS,
// The list query is most recently updated first, so a new letter goes on top.
insert: "prepend",
deleteReturns: "object",
});
+29
View File
@@ -0,0 +1,29 @@
/**
* The cover-letter paragraph bank (the `CoverSnippet` GraphQL type): reusable
* paragraphs dragged into a letter as copies — full CRUD, built on
* createCrudStore().
*
* `section` is the title of the section a snippet was written for and only
* groups the bank (views/CV/CoverSnippetBank.vue); editing a snippet never
* changes letters it was already dropped into.
*
* Admin only, like stores/coverLetters.js.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const COVER_SNIPPET_FIELDS = `
id
text
section
createdAt
`;
export const useCoverSnippetsStore = createCrudStore("coverSnippets", {
type: "CoverSnippet",
list: "coverSnippets",
fields: COVER_SNIPPET_FIELDS,
// The bank groups by section itself, so where a new one lands doesn't matter.
insert: "prepend",
deleteReturns: "object",
});
+2 -2
View File
@@ -25,7 +25,7 @@ import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
import axios from "axios";
import { useAuthStore } from "@/stores/auth";
import { useAuthStore, USER_FIELDS } from "@/stores/auth";
export const useHomeDataStore = defineStore("homeData", () => {
const loaded = ref(false);
@@ -66,7 +66,7 @@ export const useHomeDataStore = defineStore("homeData", () => {
bookmarks { id category name link }
giteaFeed { avatarUrl repoUrl repoName opType commitMessage createdAt }
steamStatus { online recentGames { appId name playtime2Weeks playtimeForever headerImageUrl } }
me { id username admin }
me { ${USER_FIELDS} }
}
`),
fetchRadioStatus(),
+57
View File
@@ -0,0 +1,57 @@
/**
* Saved layouts (the `Layout` GraphQL type): named copies of a canvas page's
* boxes and background — full CRUD, built on createCrudStore(), plus apply().
*
* `create({ name, page })` saves that page as it is now; `update` only
* renames. What a layout holds never reaches the browser, only its size: the
* server does both the copying in and the copying out.
*
* Admin only, so nothing fetches it until an admin opens a layouts list
* (views/home3/LayoutPanel.vue, the admin panel's Pages tab).
*/
import { createCrudStore } from "@/stores/createCrudStore";
import { gql } from "@/graphql";
import { useBoxesStore } from "@/stores/boxes";
import { useBackgroundStore } from "@/stores/background";
const LAYOUT_FIELDS = `
id
name
sourcePage
boxCount
hasBackground
createdAt
`;
export const useLayoutsStore = createCrudStore("layouts", {
type: "Layout",
list: "layouts",
fields: LAYOUT_FIELDS,
// The list query is newest first.
insert: "prepend",
deleteReturns: "object",
extend: ({ fetch }) => ({
/**
* Copy layout `id` onto page key `page`, replacing what is there or
* adding on top. Throws on failure.
*/
async apply(id, page, replace) {
await gql(
`mutation ApplyLayout($id: ID!, $page: String!, $replace: Boolean!) {
applyLayout(id: $id, page: $page, replace: $replace) { id }
}`,
{ id, page, replace },
);
// The page's own stores are refetched rather than patched from the
// answer, so they stay in the shape their list query gives. A replace
// also saved the old page as a new layout, hence the list too.
await Promise.all([useBoxesStore(page).fetch(), useBackgroundStore().load(page), replace && fetch()]);
},
}),
});
/** How a page key reads to a person: "/" for the landing page. */
export function pagePath(page) {
return page === "index" ? "/" : `/${page}`;
}
+40 -7
View File
@@ -1,14 +1,20 @@
/**
* WebSocket-backed chat, used by components/util/Chat.vue.
* WebSocket-backed chat, used by components/util/ChatPanel.vue (behind both the
* public Chat and the admins-only PrivateChat widgets).
*
* Owns one socket at a time, auto-reconnects with exponential backoff (1s
* doubling to a 30s ceiling, reset on a successful open) and refuses to reconnect
* after an intentional disconnect().
* after an intentional close.
*
* Both chat widgets can be on screen at once and share the socket (it carries
* both channels), so connect()/disconnect() are counted: the socket opens with
* the first widget and closes with the last.
*/
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { ref, computed, watch } from "vue";
import { uploadFile } from "@/uploads";
import { useAuthStore } from "@/stores/auth";
/**
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
@@ -32,11 +38,25 @@ export const useMessagesStore = defineStore("messages", () => {
let intentionalClose = false;
let reconnectDelay = INITIAL_RECONNECT_DELAY_MS;
let reconnectTimer = null;
// How many mounted widgets want the socket open.
let users = 0;
const messagesCount = computed(() => messages.value.length);
/** Open the socket (no-op if one already exists) and arm auto-reconnect. */
/** Register a widget that needs the socket, opening it if it is the first. */
function connect() {
users++;
open();
}
/** Release a connect(); the socket closes once no widget holds it. */
function disconnect() {
users = Math.max(0, users - 1);
if (users === 0) close();
}
/** Open the socket (no-op if one already exists) and arm auto-reconnect. */
function open() {
if (socket.value) return;
intentionalClose = false;
clearTimeout(reconnectTimer);
@@ -93,7 +113,7 @@ export const useMessagesStore = defineStore("messages", () => {
socket.value = null;
if (!intentionalClose) {
reconnectTimer = setTimeout(() => {
connect();
open();
}, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
}
@@ -103,9 +123,9 @@ export const useMessagesStore = defineStore("messages", () => {
/**
* Close the socket and suppress auto-reconnect. Clearing `socket.value`
* *before* calling close() is what makes the onclose guard above see a stale
* socket, so a later connect() is not fought over by the dying one.
* socket, so a later open() is not fought over by the dying one.
*/
function disconnect() {
function close() {
intentionalClose = true;
clearTimeout(reconnectTimer);
if (!socket.value) return;
@@ -115,6 +135,19 @@ export const useMessagesStore = defineStore("messages", () => {
ws.close();
}
// Admin status is fixed when the socket connects (from the auth cookies), so
// reopen after a login/logout to pick up or drop private messages. Here
// rather than in the widgets so two mounted chats reconnect once, not twice.
const auth = useAuthStore();
watch(
() => !!auth.user.admin,
() => {
if (users === 0) return;
close();
open();
},
);
/** Send a chat line. Silently drops it if the socket is not open. */
function sendMessage(text, isPrivate = false) {
if (!socket.value || !isConnected.value) return;
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Places-to-go list (the "Places" tab inside the Collage widget) — full CRUD,
* Places-to-go list (the Places widget, views/home/Places.vue) — full CRUD,
* built on createCrudStore().
*
* Not part of the homeData query because it is sign-in-only; PlacesTable.vue
+22 -4
View File
@@ -18,6 +18,10 @@
*
* A refused file (wrong type, too large) rejects with an ApiError whose
* `message` is the backend's sentence, ready to show the user.
*
* listUploads() lists what is already stored, for reusing a file instead of
* uploading it again (components/util/UploadPicker.vue). It is admin-only:
* the listing is what would turn every unguessable URL into a known one.
*/
import { api } from "@/api";
@@ -50,6 +54,16 @@ export async function uploadFile(file, { private: isPrivate = false } = {}) {
return url;
}
/**
* Every public upload, newest first. Admin only.
*
* @returns {Promise<Array<{name: string, url: string, size: number, modified: string}>>}
*/
export async function listUploads() {
const { files } = await api.get("/uploads", { fallback: "Couldn't list uploads" });
return files;
}
/** 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";
@@ -86,15 +100,19 @@ export function tagFor(url) {
}
}
/** Natural size of an image or video File, or null if it can't be read. */
/**
* Natural size of an image or video — a File, or the URL of one already
* stored — or null if it can't be read.
*/
export function mediaSize(file) {
return new Promise((resolve) => {
const src = URL.createObjectURL(file);
const isFile = typeof file !== "string";
const src = isFile ? URL.createObjectURL(file) : file;
const done = (size) => {
URL.revokeObjectURL(src);
if (isFile) URL.revokeObjectURL(src);
resolve(size);
};
if (file.type.startsWith("video/")) {
if (isFile ? file.type.startsWith("video/") : isVideo(file)) {
const v = document.createElement("video");
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
v.onerror = () => done(null);
+3 -3
View File
@@ -4,11 +4,11 @@
<template>
<main class="flex flex-col items-center">
<div
class="page-a4 items-center bdr-1 flex flex-col relative overflow-scroll"
class="page-a4 items-center bdr-1 flex flex-col relative overflow-auto"
>
<h1>404</h1>
<RouterLink to="/" class="bdr-2">
<img src="/img/memes/epic.jpeg" loading="lazy" />
<RouterLink to="/" class="bdr-2" aria-label="Back to the home page">
<img src="/img/memes/epic.jpeg" alt="" class="block max-w-full" />
</RouterLink>
<h1>Click her, she will take you home</h1>
</div>
+213 -184
View File
@@ -1,6 +1,10 @@
<script setup>
/**
* The live CV template — the only one currently listed in CV.vue.
*
* Both sheets are fixed A4 with overflow hidden (cv-shared.css), so anything
* added here has to be checked in print preview: text that doesn't fit is
* silently clipped, not pushed onto another page.
*/
import Project from "./Project.vue";
</script>
@@ -33,41 +37,42 @@ import Project from "./Project.vue";
<section>
<h2>Profile</h2>
<p>
Software developer with a First Class BSc in Computer
Science with Mathematics. Designs, builds and operates
full-stack software end to end, from Go APIs and Vue
frontends to the self-hosted infrastructure they run on.
<a href="/pdf/dissertation.pdf">Dissertation</a> proved
<a href="/automata">Mobile Automata</a> are computationally
equivalent to Turing Machines. Integrates AI tooling (Claude
Code) into everyday development.
Software engineer with a First Class BSc in Computer
Science with Mathematics. I build and run full-stack systems
end to end, from Go services and Vue frontends to the
Docker, Nginx and CI/CD infrastructure beneath them: around
twenty services in production at
<a href="https://www.adam-french.co.uk/architecture">
adam-french.co.uk</a
>. My <a href="/pdf/dissertation.pdf">dissertation</a>
proved <a href="/automata">Mobile Automata</a> are
computationally equivalent to Turing Machines. I use AI in
my workflow (Claude Code) and in what I ship (the Claude
API).
</p>
</section>
<section>
<h2>Technical Skills</h2>
<div class="skills-grid">
<div>
<strong>Languages</strong><br />
<small>
Go, Rust, Python, JavaScript / TypeScript, SQL
</small>
</div>
<div>
<strong>Web</strong><br />
<small>
Vue 3, GraphQL, REST APIs, JWT Auth, WebSockets,
Tailwind CSS
</small>
</div>
<div>
<strong>Infrastructure</strong><br />
<small>
Docker, Nginx, PostgreSQL, Linux, Git, CI/CD (Gitea
Actions)
</small>
</div>
</div>
<p>
<strong>Languages:</strong>
Go, Python, Rust, C++, JavaScript / TypeScript, SQL, Bash
</p>
<p>
<strong>Backend & Web:</strong>
GraphQL (gqlgen), REST, FastAPI, WebSockets, JWT, Vue 3,
Pinia, Tailwind CSS
</p>
<p>
<strong>Infrastructure:</strong>
Docker Compose, Nginx, Linux, PostgreSQL, S3, CI/CD (Gitea
Actions)
</p>
<p>
<strong>AI / ML:</strong>
Claude API (structured output), PyTorch, OpenCV, Tesseract
OCR, Optuna
</p>
</section>
<section>
@@ -89,12 +94,9 @@ import Project from "./Project.vue";
</div>
<ul class="list-disc list-inside pt-1">
<li>Algorithms & Data Structures I & II</li>
<li>Compiler Design and Construction</li>
<li>Formal Languages & Finite Automata</li>
<li>Compilers; Formal Languages & Automata</li>
<li>Graph Algorithms & Complexity Theory</li>
<li>
Machine Learning, Databases, Computer Processors
</li>
<li>Machine Learning, Databases, Processors</li>
</ul>
</div>
<div class="flex-1">
@@ -125,27 +127,6 @@ import Project from "./Project.vue";
<section>
<h2>Projects</h2>
<Project class="border-b border-dotted">
<template #left>
<h4>
<a
href="https://github.com/SteveThePug/tour"
>
tour.git
</a>
</h4>
</template>
<template #top>
<strong>Rust</strong>
<small>Aug 2025 – Present</small>
</template>
<p contenteditable="true">
Rust CLI for building and navigating interactive,
step-by-step code tutorials, with version-traversal
semantics inspired by Git.
</p>
</Project>
<Project class="border-b border-dotted">
<template #left>
<h4>
@@ -158,19 +139,135 @@ import Project from "./Project.vue";
</template>
<template #top>
<strong>
Nginx, Vue, Postgres, Docker, Go, Python, Gitea
Actions
Go, Vue, PostgreSQL, Docker, Nginx, Gitea Actions
</strong>
<small>2025</small>
<small>Nov 2025 – Present</small>
</template>
<p contenteditable="true">
Self-hosted personal website with a fully automated
CI/CD pipeline: Go GraphQL (gqlgen) API with JWT
authentication and WebSockets, Vue 3 + Pinia frontend,
and PostgreSQL, containerised behind Nginx on a
Raspberry Pi. A git push builds, tests, and releases to
production with no manual steps; the Nginx layer adds
per-route rate limiting and automated TLS renewal.
Self-hosted platform behind my website: ~20 Docker
Compose services on a Linux VM: a Go GraphQL
API, Vue 3 SPA, FastAPI, PostgreSQL, S3 storage, Gitea
with CI, and the apps below.
</p>
<ul contenteditable="true">
<li>
Push-to-deploy CI/CD: tests gate releases; apps roll
out on healthchecks.
</li>
<li>
Schema-declared GraphQL auth; tests fail any
unguarded mutation.
</li>
<li>
Rate limiting, request logging, self-healing
restarts; migrated from a Raspberry Pi to a VM.
</li>
</ul>
</Project>
<Project>
<template #left>
<h4>
<a
href="https://www.adam-french.co.uk/gitea/adamf/usaco"
>
usaco.git
</a>
</h4>
</template>
<template #top>
<strong>Go, Vue, C++, Docker, Claude API</strong>
<small>Aug 2026 – Present</small>
</template>
<p contenteditable="true">
Bash CLI and site for my USACO, LeetCode and Codeforces
solutions, live at
<a href="https://www.adam-french.co.uk/usaco/">
adam-french.co.uk/usaco</a
>.
</p>
<ul contenteditable="true">
<li>
Git as the database: Go service indexes a clone,
commits edits back.
</li>
<li>
Sandboxed runner judges untrusted C++ and Python: no
network, read-only root, CPU and memory limits.
</li>
<li>
Claude API (JSON-schema output) explains problems,
and reviews my code and recorded explanations.
</li>
</ul>
</Project>
</section>
</div>
<div class="no-print w-full h-20"></div>
<div class="cv-page justify-around">
<section>
<h2>More Projects</h2>
<Project class="border-b border-dotted">
<template #left>
<h4>
<a
href="https://www.adam-french.co.uk/gitea/adamf/job-tracker"
>
job-tracker.git
</a>
</h4>
</template>
<template #top>
<strong>Go, GraphQL, Vue, PostgreSQL, Claude API</strong>
<small>Apr 2026 – Present</small>
</template>
<p contenteditable="true">
Application tracker with a leads inbox: pulls postings
from Greenhouse, Lever, Ashby, Adzuna and Reed, scores
them with Claude, and captures pages via a userscript.
Split from the main site into its own service and
database.
</p>
</Project>
<Project class="border-b border-dotted">
<template #left>
<h4>
<a
href="https://www.adam-french.co.uk/gitea/adamf/rowing_stats"
>
rowing_stats.git
</a>
</h4>
</template>
<template #top>
<strong>Python, OpenCV, PyTorch, Tesseract, Optuna</strong>
<small>Jan 2026 – Oct 2026</small>
</template>
<p contenteditable="true">
Turns phone photos of a rowing machine's monitor into a
workout log: contour detection, a CNN filter and OCR
that votes across six preprocessings, tuned with Optuna.
Replaced a paid vision API, matching it on 91% of times.
</p>
</Project>
<Project class="border-b border-dotted">
<template #left>
<h4>
<a href="https://github.com/SteveThePug/tour">
tour.git
</a>
</h4>
</template>
<template #top>
<strong>Rust</strong>
<small>Feb 2026 – Sep 2026</small>
</template>
<p contenteditable="true">
CLI for authoring and stepping through code tutorials as
file snapshots, with Git-style staging and commits.
</p>
</Project>
<Project class="border-b border-dotted">
@@ -215,42 +312,6 @@ import Project from "./Project.vue";
</p>
</Project>
</section>
</div>
<div class="no-print w-full h-20"></div>
<div class="cv-page justify-around">
<section>
<h2>Secondary Education</h2>
<div
class="flex-row flex place-content-between m-auto place-items-center"
>
<h3>University Academy of Engineering Southbank</h3>
<small>Sep 2014 – Jun 2021</small>
</div>
<div class="w-full flex flex-col sm:flex-row gap-5">
<div class="flex-1">
<strong>A-Levels</strong>
<div class="grid grid-cols-[1fr_auto] gap-x-4">
<span>Mathematics</span><span>A*</span>
<span>Further Mathematics</span><span>A*</span>
<span>Physics</span><span>A*</span>
</div>
</div>
<div class="flex-1">
<strong>GCSEs</strong>
<div class="grid grid-cols-[1fr_auto] gap-x-4">
<span>Mathematics</span><span>9</span>
<span>English Literature</span><span>9</span>
<span>Physics</span><span>9</span>
<span>English Language</span><span>8</span>
<span>Biology</span><span>8</span>
<span>Chemistry</span><span>8</span>
<span>Computer Science</span><span>7</span>
</div>
</div>
</div>
</section>
<section>
<h2>Work Experience</h2>
@@ -270,8 +331,8 @@ import Project from "./Project.vue";
<small>May 2026 – Present</small>
</template>
<p contenteditable="true">
Working at an all-day café in Holland Park, preparing
coffee and serving food in a fast-paced environment.
Coffee and table service at a busy all-day café in
Holland Park.
</p>
</Project>
<Project class="border-b border-dotted">
@@ -287,97 +348,65 @@ import Project from "./Project.vue";
<small>Sep 2022 – May 2026</small>
</template>
<p contenteditable="true">
Served food and drinks across Belgrave Music Hall and The
Montpelier (Rose Pubs Group) in Leeds while studying.
Handled busy weekend shifts in a high-volume live-music
venue, managed multiple tables simultaneously, and
maintained a calm, friendly demeanour during peak
hours.
</p>
</Project>
<Project class="border-b border-dotted">
<template #left>
<h4>
<a href="https://crownandanchoreastbourne.co.uk/">
The Crown and Anchor
</a>
</h4>
</template>
<template #top>
<small>Bartender & Waiter</small>
<small>Jul 2022 – Sep 2022</small>
</template>
<p contenteditable="true">
Worked front-of-house at a Greene King family pub in
Eastbourne, pulling pints, taking orders, and ensuring a
welcoming atmosphere. Built rapport with regulars and
with a close-knit team during service.
</p>
</Project>
<Project class="border-b border-dotted">
<template #left>
<h4>
<a href="https://www.totherisebakery.com/">
To The Rise Bakery
</a>
</h4>
</template>
<template #top>
<small>Barista & Front of House</small>
<small>Jun 2022 – Sep 2022</small>
</template>
<p contenteditable="true">
Worked alongside the bakers at a bakery in Eastbourne,
handling freshly baked goods for display, operating the
coffee machine, and keeping equipment spotless. Built
rapport with regulars and provided attentive, friendly
service.
Through university at Belgrave Music Hall and The
Montpelier (Rose Pubs Group), Leeds: high-volume weekend
service at a live-music venue.
</p>
</Project>
<Project>
<template #left>
<h4>
<a
href="https://www.benugo.com/sites/restaurants/bfi-riverfront/"
>
BFI Riverfront Kitchen
</a>
</h4>
<h4>Earlier Roles</h4>
</template>
<template #top>
<small>Cashier & Waiter</small>
<small>Jun 2021 – Sep 2021</small>
<small>Bar, Barista & Cashier</small>
<small>Jun 2021 – Sep 2022</small>
</template>
<p contenteditable="true">
Operated the till, served customers, and helped
coordinate table service at the BFI Southbank riverfront
bar and kitchen (Benugo) on London's South Bank. Developed strong cash-handling accuracy and
customer interaction skills in a fast-paced environment.
<a href="https://crownandanchoreastbourne.co.uk/">
The Crown and Anchor</a
>
and
<a href="https://www.totherisebakery.com/">
To The Rise Bakery</a
>
in Eastbourne (2022);
<a
href="https://www.benugo.com/sites/restaurants/bfi-riverfront/"
>
BFI Riverfront Kitchen</a
>
in London (2021).
</p>
</Project>
</section>
<div class="w-full flex flex-col sm:flex-row gap-5">
<section class="flex-1">
<h2>Soft Skills</h2>
<ul class="list-disc list-inside">
<li>Communication & collaboration</li>
<li>Attention to detail</li>
<li>Problem solving</li>
<li>Adaptability</li>
<li>Time management</li>
</ul>
</section>
<section class="flex-1">
<h2>Interests</h2>
<ul class="list-disc list-inside">
<li>Competitive programming (LeetCode, USACO)</li>
<li>Learning Mandarin</li>
<li>Rhythm Games</li>
<li>Climbing, Gym</li>
<li>Board games, Meetup.com</li>
</ul>
</section>
</div>
<section>
<h2>Secondary Education</h2>
<div
class="flex-row flex place-content-between m-auto place-items-center"
>
<h3>University Academy of Engineering Southbank</h3>
<small>Sep 2014 – Jun 2021</small>
</div>
<p>
<strong>A-Levels:</strong> Mathematics A*, Further
Mathematics A*, Physics A*
</p>
<p>
<strong>GCSEs:</strong> Mathematics 9, English Literature 9,
Physics 9, English Language 8, Biology 8, Chemistry 8,
Computer Science 7
</p>
</section>
<section>
<h2>Interests</h2>
<p>
Competitive programming (USACO, LeetCode, Codeforces) ·
Learning Mandarin · Rowing, climbing and the gym · Rhythm
games · Board games and Meetup.com
</p>
</section>
</div>
<div class="no-print w-full h-20"></div>
+655 -75
View File
@@ -1,92 +1,547 @@
<script setup>
/**
* Editable cover-letter template (contenteditable paragraphs, print to PDF).
* Editable cover letter (contenteditable fields, print to PDF), split into
* named sections whose paragraphs can be dragged within and between them.
* STATUS: live — CV.vue imports it as the "Cover Letter" tab on /cv.
*
* Everyone gets the editor; /cv is public and nothing here needs the server
* until something is saved. An admin also gets the toolbar (saved letters,
* stores/coverLetters.js) and the paragraph bank (CoverSnippetBank.vue,
* stores/coverSnippets.js). The letter's data shape and the moves live in
* ./coverLetter.js.
*
* Section titles are editor furniture: they are `no-print`, so the printed
* letter is one run of paragraphs, as it was before sections existed.
*
* Editing: contenteditable elements are filled with v-text and read back on
* blur. v-text, not {{ }}, because it replaces the element's whole content —
* an interpolated text node would sit alongside the <div>s a browser adds on
* Enter and duplicate the text when Vue patched it.
*
* Dragging is native HTML5 DnD. `drag` holds what is in flight (dataTransfer
* can't be read until the drop) and `dropAt` where it would land, which is
* what draws the indicator line. Only the ⋮⋮ handle is draggable, so text in
* a paragraph stays selectable.
*/
import { ref } from "vue";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useAuthStore } from "@/stores/auth";
import { useCoverLettersStore } from "@/stores/coverLetters";
import { useCoverSnippetsStore } from "@/stores/coverSnippets";
import CoverSnippetBank from "./CoverSnippetBank.vue";
import {
insertParagraph,
moveParagraph,
newLetter,
newParagraph,
newSection,
parseBody,
serialize,
} from "./coverLetter";
const name = ref("Adam French");
const phone = ref("+447563266931");
const email = ref("[email protected]");
const role = ref("Job title / role");
const paragraphs = ref([
"Why I'm interested in the company...",
"Why I'm a strong fit for the role...",
"Relevant experience and background...",
]);
const signoff = ref("Thank you for reading - Adam F");
const auth = useAuthStore();
const letters = useCoverLettersStore();
const snippets = useCoverSnippetsStore();
const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
function addParagraph() {
paragraphs.value.push("New paragraph...");
const letter = ref(newLetter());
// The open saved letter's id, or null for one never saved (or deleted).
const currentId = ref(null);
// The body as last saved or loaded; the letter is unsaved when it differs.
// Starts as the blank template so an untouched page doesn't nag.
const savedBody = ref(serialize(letter.value));
const dirty = computed(() => serialize(letter.value) !== savedBody.value);
const current = computed(() =>
letters.coverLetters.find((l) => l.id === currentId.value),
);
const busy = ref(false);
const error = ref("");
onMounted(() => auth.ensureLoaded());
// The stores are admin only, so they are fetched once an admin is known,
// which can be after mount on a cold load.
watch(
isAdmin,
(admin) => {
if (!admin) return;
if (!letters.loaded) letters.fetch();
if (!snippets.loaded) snippets.fetch();
},
{ immediate: true },
);
// Closing the tab with unsaved changes asks first. Only for an admin, who
// can save; a visitor's letter is throwaway by design.
function onBeforeUnload(event) {
if (isAdmin.value && dirty.value) event.preventDefault();
}
onMounted(() => window.addEventListener("beforeunload", onBeforeUnload));
onBeforeUnmount(() =>
window.removeEventListener("beforeunload", onBeforeUnload),
);
// ── Saving ──────────────────────────────────────────────────────────────
async function run(fn) {
error.value = "";
busy.value = true;
try {
await fn();
} catch (err) {
error.value = err.message;
} finally {
busy.value = false;
}
}
function removeParagraph(index) {
paragraphs.value.splice(index, 1);
function discardOk() {
return !dirty.value || confirm("Discard the unsaved changes?");
}
function updateParagraph(index, event) {
paragraphs.value[index] = event.target.innerText;
function open(letterRow) {
letter.value = parseBody(letterRow.body);
currentId.value = letterRow.id;
// The normalised form, not the raw body, so an older row doesn't open
// already marked unsaved.
savedBody.value = serialize(letter.value);
}
function onPick(event) {
const id = event.target.value;
const row = letters.coverLetters.find((l) => l.id === id);
if (row && discardOk()) open(row);
// Put the select back if the switch was refused or "New" was picked.
event.target.value = currentId.value ?? "";
}
function startNew() {
if (!discardOk()) return;
letter.value = newLetter();
currentId.value = null;
savedBody.value = serialize(letter.value);
}
function save() {
if (!currentId.value) return saveAs();
const body = serialize(letter.value);
run(async () => {
await letters.update(currentId.value, { body });
savedBody.value = body;
});
}
function saveAs() {
const suggestion = current.value
? `${current.value.name} (copy)`
: letter.value.role.trim();
const name = prompt("Name this cover letter", suggestion);
if (name === null) return;
const body = serialize(letter.value);
run(async () => {
const created = await letters.create({ name, body });
currentId.value = created.id;
savedBody.value = body;
});
}
function rename() {
if (!current.value) return;
const name = prompt("Rename cover letter", current.value.name);
if (name === null || name === current.value.name) return;
run(() => letters.update(currentId.value, { name }));
}
function removeLetter() {
if (!current.value) return;
if (!confirm(`Delete "${current.value.name}"? This can't be undone.`))
return;
run(async () => {
await letters.remove(currentId.value);
// The text stays on the page, now unsaved, in case it was a misclick.
currentId.value = null;
savedBody.value = "";
});
}
// ── Editing ─────────────────────────────────────────────────────────────
function addParagraph(section) {
section.paragraphs.push(newParagraph());
}
function removeParagraph(section, index) {
section.paragraphs.splice(index, 1);
}
function addSection() {
letter.value.sections.push(newSection("New section", ["New paragraph..."]));
}
function removeSection(index) {
const section = letter.value.sections[index];
if (
section.paragraphs.some((p) => p.text.trim()) &&
!confirm(`Remove "${section.title || "this section"}" and its text?`)
)
return;
letter.value.sections.splice(index, 1);
}
const sectionTitles = computed(() =>
[...new Set(letter.value.sections.map((s) => s.title.trim()))].filter(
Boolean,
),
);
function saveToBank(section, para) {
run(() =>
snippets.create({ text: para.text, section: section.title.trim() }),
);
}
// ── Dragging ────────────────────────────────────────────────────────────
// { kind: "para", from: { section, index } } | { kind: "snippet", text } | null
const drag = ref(null);
// { section, index } — where a drop would land, or null.
const dropAt = ref(null);
function onParaDragStart(si, pi, event) {
drag.value = { kind: "para", from: { section: si, index: pi } };
event.dataTransfer.effectAllowed = "copyMove";
// Firefox won't start a drag without some data set.
event.dataTransfer.setData(
"text/plain",
letter.value.sections[si].paragraphs[pi].text,
);
event.dataTransfer.setDragImage(
event.target.closest(".paragraph-wrapper"),
16,
16,
);
}
function onSnippetDrag(snippet) {
drag.value = { kind: "snippet", text: snippet.text };
}
function endDrag() {
drag.value = null;
dropAt.value = null;
}
function accept(event) {
if (!drag.value) return false;
event.preventDefault();
event.dataTransfer.dropEffect = drag.value.kind === "para" ? "move" : "copy";
return true;
}
/** Over a paragraph: before it if the pointer is in its top half, else after. */
function onParaDragOver(si, pi, event) {
if (!accept(event)) return;
const rect = event.currentTarget.getBoundingClientRect();
const after = event.clientY > rect.top + rect.height / 2;
dropAt.value = { section: si, index: after ? pi + 1 : pi };
}
/** Over a section's end zone, or its title row: the end of that section. */
function onSectionEndDragOver(si, event) {
if (!accept(event)) return;
dropAt.value = {
section: si,
index: letter.value.sections[si].paragraphs.length,
};
}
function onDrop(event) {
if (!drag.value || !dropAt.value) return endDrag();
event.preventDefault();
if (drag.value.kind === "para")
moveParagraph(letter.value, drag.value.from, dropAt.value);
else insertParagraph(letter.value, dropAt.value, drag.value.text);
endDrag();
}
/** A letter paragraph dropped on the bank: save a copy there. */
function onBankDrop() {
const from = drag.value?.from;
endDrag();
if (!from) return;
const section = letter.value.sections[from.section];
saveToBank(section, section.paragraphs[from.index]);
}
const indicatorAt = (si, index) =>
dropAt.value?.section === si && dropAt.value?.index === index;
</script>
<template>
<main>
<div class="a5page">
<div class="contact">
<h1
contenteditable="true"
@blur="name = $event.target.innerText"
<main :class="['cl-wrap', { 'with-bank': isAdmin }]">
<div class="cl-letter">
<div v-if="isAdmin" class="no-print toolbar">
<select
class="letter-pick"
:value="currentId ?? ''"
:disabled="busy"
@change="onPick"
>
{{ name }}
</h1>
<div class="contact-details">
<p
contenteditable="true"
@blur="phone = $event.target.innerText"
<option value="" disabled>
{{
letters.coverLetters.length
? "Open a saved letter…"
: "No saved letters"
}}
</option>
<option
v-for="l in letters.coverLetters"
:key="l.id"
:value="l.id"
>
{{ phone }}
</p>
<p
contenteditable="true"
@blur="email = $event.target.innerText"
>
{{ email }}
</p>
</div>
</div>
<h2 contenteditable="true" @blur="role = $event.target.innerText">
{{ role }}
</h2>
<div
v-for="(p, i) in paragraphs"
:key="i"
class="paragraph-wrapper"
>
<p contenteditable="true" @blur="updateParagraph(i, $event)">
{{ p }}
</p>
{{ l.name }}
</option>
</select>
<button
class="no-print remove-btn"
title="Remove paragraph"
@click="removeParagraph(i)"
class="cv-btn cv-btn-sm"
:disabled="busy"
@click="startNew"
>
×
New
</button>
<button
class="cv-btn cv-btn-sm cv-btn-primary"
:disabled="busy || (currentId && !dirty)"
@click="save"
>
Save
</button>
<button
class="cv-btn cv-btn-sm"
:disabled="busy"
@click="saveAs"
>
Save as…
</button>
<button
class="cv-btn cv-btn-sm"
:disabled="busy || !current"
@click="rename"
>
Rename
</button>
<button
class="cv-btn cv-btn-sm cv-btn-danger"
:disabled="busy || !current"
@click="removeLetter"
>
Delete
</button>
<span v-if="dirty" class="unsaved">● unsaved</span>
<span v-else-if="current" class="saved">saved</span>
<p v-if="error" class="toolbar-error">{{ error }}</p>
<p v-else-if="letters.error" class="toolbar-error">
Couldn't load saved letters: {{ letters.error.message }}
</p>
</div>
<div class="a5page" @dragend="endDrag">
<div class="contact">
<h1
contenteditable="true"
v-text="letter.name"
@blur="letter.name = $event.target.innerText"
></h1>
<div class="contact-details">
<p
contenteditable="true"
v-text="letter.phone"
@blur="letter.phone = $event.target.innerText"
></p>
<p
contenteditable="true"
v-text="letter.email"
@blur="letter.email = $event.target.innerText"
></p>
</div>
</div>
<h2
contenteditable="true"
v-text="letter.role"
@blur="letter.role = $event.target.innerText"
></h2>
<section
v-for="(section, si) in letter.sections"
:key="section.id"
class="letter-section"
>
<div
class="no-print section-head"
@dragover="onSectionEndDragOver(si, $event)"
@drop="onDrop"
>
<input
v-model="section.title"
class="section-title"
placeholder="Section title"
aria-label="Section title"
/>
<button
class="section-btn"
title="Add a paragraph to this section"
@click="addParagraph(section)"
>
+ paragraph
</button>
<button
class="section-btn danger"
title="Remove this section"
@click="removeSection(si)"
>
remove
</button>
</div>
<div
v-for="(p, pi) in section.paragraphs"
:key="p.id"
:class="[
'paragraph-wrapper',
{
'drop-before': indicatorAt(si, pi),
dragging:
drag?.kind === 'para' &&
drag.from.section === si &&
drag.from.index === pi,
},
]"
@dragover="onParaDragOver(si, pi, $event)"
@drop="onDrop"
>
<span
class="no-print drag-handle"
draggable="true"
title="Drag to move"
@dragstart="onParaDragStart(si, pi, $event)"
>⋮⋮</span
>
<p
contenteditable="true"
v-text="p.text"
@blur="p.text = $event.target.innerText"
></p>
<div class="no-print para-actions">
<button
v-if="isAdmin"
class="bank-btn"
title="Save to the paragraph bank"
@click="saveToBank(section, p)"
>
☆
</button>
<button
class="remove-btn"
title="Remove paragraph"
@click="removeParagraph(section, pi)"
>
×
</button>
</div>
</div>
<div
:class="[
'no-print',
'section-end',
{
'drop-before': indicatorAt(
si,
section.paragraphs.length,
),
empty: !section.paragraphs.length,
},
]"
@dragover="onSectionEndDragOver(si, $event)"
@drop="onDrop"
>
<span v-if="!section.paragraphs.length">
Empty — drop a paragraph here
</span>
</div>
</section>
<p
contenteditable="true"
v-text="letter.signoff"
@blur="letter.signoff = $event.target.innerText"
></p>
<button class="no-print add-btn" @click="addSection()">
+ Add section
</button>
</div>
<p
contenteditable="true"
@blur="signoff = $event.target.innerText"
>
{{ signoff }}
</p>
<button class="no-print add-btn" @click="addParagraph()">
+ Add paragraph
</button>
</div>
<CoverSnippetBank
v-if="isAdmin"
:accepting="drag?.kind === 'para'"
:section-titles="sectionTitles"
@drag-snippet="onSnippetDrag"
@drag-end="endDrag"
@drop-paragraph="onBankDrop"
/>
</main>
</template>
<style scoped>
.cl-wrap.with-bank {
display: grid;
grid-template-columns: minmax(0, 210mm) 18rem;
justify-content: center;
gap: 1.5rem;
padding: 0 1rem;
}
/* Narrow screens: the bank goes under the letter. */
@media (max-width: 1100px) {
.cl-wrap.with-bank {
grid-template-columns: minmax(0, 210mm);
}
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
max-width: 210mm;
margin: 1rem auto 0;
}
.letter-pick {
min-width: 12rem;
padding: 0.2rem 0.4rem;
border: 1px solid var(--color-ink-soft);
border-radius: 4px;
font-size: 0.85rem;
}
.unsaved {
color: var(--color-ink-danger);
font-size: 0.8rem;
}
.saved {
color: var(--color-ink-muted);
font-size: 0.8rem;
}
.toolbar-error {
flex-basis: 100%;
color: var(--color-ink-danger);
font-size: 0.85rem;
}
.a5page {
max-width: 210mm;
min-height: 148mm;
@@ -130,32 +585,153 @@ function updateParagraph(index, event) {
margin: 0;
}
/* innerText turns a line break typed into a paragraph into "\n"; this keeps
it showing as one once v-text writes it back. */
[contenteditable="true"] {
white-space: pre-wrap;
}
[contenteditable="true"]:hover,
[contenteditable="true"]:focus {
outline: 1px dashed #999;
outline-offset: 2px;
}
.section-head {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0.25rem 0 0.35rem;
font-size: 0.75rem;
}
.section-title {
flex: 1;
padding: 0;
border: none;
border-bottom: 1px dashed transparent;
background: transparent;
color: #888;
font: inherit;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.section-title:hover,
.section-title:focus {
border-bottom-color: #bbb;
outline: none;
color: #555;
}
.section-btn {
border: none;
background: none;
color: #888;
cursor: pointer;
font-size: 0.75rem;
opacity: 0;
transition: opacity 0.15s;
}
.section-btn:hover {
color: #333;
}
.section-btn.danger:hover {
color: #c00;
}
.letter-section:hover .section-btn,
.section-btn:focus-visible {
opacity: 1;
}
.paragraph-wrapper {
position: relative;
}
.paragraph-wrapper .remove-btn {
position: absolute;
top: 0;
right: -1.5rem;
border: none;
background: none;
color: #c00;
cursor: pointer;
font-size: 1rem;
opacity: 0;
.paragraph-wrapper.dragging {
opacity: 0.4;
}
.paragraph-wrapper:hover .remove-btn {
/* The drop indicator: a line just above the paragraph (or end zone) the
dragged one would land before. */
.drop-before::before {
content: "";
position: absolute;
left: 0;
right: 0;
top: -0.45rem;
height: 2px;
border-radius: 1px;
background: #2563eb;
}
.drag-handle {
position: absolute;
top: 0.1rem;
left: -1.6rem;
padding: 0 0.25rem;
color: #aaa;
cursor: grab;
font-size: 0.85rem;
letter-spacing: -0.15em;
user-select: none;
opacity: 0;
transition: opacity 0.15s;
}
.para-actions {
position: absolute;
top: 0;
right: -2.6rem;
display: flex;
gap: 0.1rem;
opacity: 0;
transition: opacity 0.15s;
}
.paragraph-wrapper:hover .drag-handle,
.paragraph-wrapper:hover .para-actions,
.para-actions:focus-within {
opacity: 1;
}
.para-actions button {
border: none;
background: none;
cursor: pointer;
font-size: 1rem;
line-height: 1.5;
}
.remove-btn {
color: #c00;
}
.bank-btn {
color: #b8860b;
}
.section-end {
position: relative;
min-height: 0.5rem;
}
.section-end.empty {
display: flex;
align-items: center;
justify-content: center;
min-height: 2.5rem;
margin-bottom: 0.75rem;
border: 1px dashed #ccc;
border-radius: 4px;
color: #999;
font-size: 0.8rem;
}
.add-btn {
margin-top: 0.5rem;
padding: 0.3rem 0.8rem;
@@ -179,5 +755,9 @@ function updateParagraph(index, event) {
.no-print {
display: none !important;
}
.cl-wrap.with-bank {
display: block;
padding: 0;
}
}
</style>
+324
View File
@@ -0,0 +1,324 @@
<script setup>
/**
* The paragraph bank beside the cover letter (admin only, never printed):
* reusable paragraphs from stores/coverSnippets.js, grouped by the section
* they were written for.
*
* Dragging works through the parent, which owns the one drag in progress:
* dragging a snippet out emits `drag-snippet` so CoverLetters.vue can drop a
* copy into the letter, and a letter paragraph dropped here (`accepting` is
* true while one is being dragged) emits `drop-paragraph` for the parent to
* save. Snippets are edited in place and saved on blur.
*/
import { computed, ref } from "vue";
import { useCoverSnippetsStore } from "@/stores/coverSnippets";
const props = defineProps({
// True while a letter paragraph is being dragged, so the bank can light up.
accepting: { type: Boolean, default: false },
// The letter's section titles, offered when adding a snippet.
sectionTitles: { type: Array, default: () => [] },
});
const emit = defineEmits(["drag-snippet", "drag-end", "drop-paragraph"]);
const store = useCoverSnippetsStore();
const filter = ref("");
const error = ref("");
const over = ref(false);
const newText = ref("");
const newSection = ref("");
/** [{ section, snippets }] in the store's order (section, then newest),
* narrowed by the filter, which matches text or section. */
const groups = computed(() => {
const q = filter.value.trim().toLowerCase();
const out = [];
for (const s of store.coverSnippets) {
if (
q &&
!s.text.toLowerCase().includes(q) &&
!s.section.toLowerCase().includes(q)
)
continue;
let group = out.find((g) => g.section === s.section);
if (!group) out.push((group = { section: s.section, snippets: [] }));
group.snippets.push(s);
}
return out;
});
async function run(fn) {
error.value = "";
try {
await fn();
} catch (err) {
error.value = err.message;
}
}
function add() {
run(async () => {
await store.create({ text: newText.value, section: newSection.value });
newText.value = "";
});
}
function save(snippet, field, value) {
if (snippet[field] === value) return;
run(() => store.update(snippet.id, { [field]: value }));
}
function remove(snippet) {
if (!confirm("Delete this paragraph from the bank?")) return;
run(() => store.remove(snippet.id));
}
function onDragStart(snippet, event) {
event.dataTransfer.effectAllowed = "copy";
// Firefox won't start a drag without some data set.
event.dataTransfer.setData("text/plain", snippet.text);
// Only the grip is draggable, so text in the textareas stays selectable
// (Firefox can't place a caret inside a draggable element); show the
// whole card moving rather than the grip.
event.dataTransfer.setDragImage(event.target.closest(".snippet"), 12, 12);
emit("drag-snippet", snippet);
}
function onDragOver(event) {
if (!props.accepting) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
over.value = true;
}
function onDrop(event) {
over.value = false;
if (!props.accepting) return;
event.preventDefault();
emit("drop-paragraph");
}
</script>
<template>
<aside
:class="['bank', 'no-print', { accepting, over }]"
@dragover="onDragOver"
@dragleave="over = false"
@drop="onDrop"
>
<div class="bank-head">
<h3>Paragraph bank</h3>
<span class="hint">drag into the letter</span>
</div>
<input
v-model="filter"
class="bank-filter"
type="search"
placeholder="Filter…"
/>
<p v-if="accepting" class="drop-hint">Drop here to save to the bank</p>
<p v-if="error" class="bank-error">{{ error }}</p>
<p v-if="store.error" class="bank-error">
Couldn't load the bank: {{ store.error.message }}
</p>
<p
v-else-if="store.loaded && !store.coverSnippets.length"
class="empty"
>
Nothing saved yet. Drag a paragraph here, or use ☆ on one.
</p>
<section v-for="g in groups" :key="g.section" class="group">
<h4>{{ g.section || "Unsorted" }}</h4>
<div v-for="s in g.snippets" :key="s.id" class="snippet">
<span
class="grip"
draggable="true"
title="Drag into the letter"
@dragstart="onDragStart(s, $event)"
@dragend="emit('drag-end')"
>⋮⋮</span
>
<textarea
:value="s.text"
rows="3"
@blur="save(s, 'text', $event.target.value.trim())"
></textarea>
<div class="snippet-foot">
<input
:value="s.section"
class="snippet-section"
placeholder="Section"
@change="save(s, 'section', $event.target.value.trim())"
/>
<button
class="cv-btn cv-btn-sm cv-btn-danger"
title="Delete from the bank"
@click="remove(s)"
>
×
</button>
</div>
</div>
</section>
<form class="add" @submit.prevent="add">
<textarea
v-model="newText"
rows="3"
placeholder="New reusable paragraph…"
></textarea>
<div class="snippet-foot">
<input
v-model="newSection"
class="snippet-section"
list="cover-section-titles"
placeholder="Section"
/>
<datalist id="cover-section-titles">
<option v-for="t in sectionTitles" :key="t" :value="t" />
</datalist>
<button
class="cv-btn cv-btn-sm"
type="submit"
:disabled="!newText.trim()"
>
Add
</button>
</div>
</form>
</aside>
</template>
<style scoped>
.bank {
align-self: start;
position: sticky;
top: 3.5rem;
max-height: calc(100vh - 4.5rem);
overflow-y: auto;
margin: 1rem 0;
padding: 0.75rem;
border: 1px solid var(--color-line);
border-radius: 6px;
background: var(--color-paper-tint);
font-size: 0.85rem;
transition:
border-color 0.15s,
background 0.15s;
}
.bank.accepting {
border-style: dashed;
border-color: var(--color-ink-muted);
}
.bank.over {
background: var(--color-paper-shade);
}
.bank-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 0.5rem;
}
.bank-head h3 {
font-size: 0.95rem;
font-weight: 600;
}
.hint,
.empty,
.drop-hint {
color: var(--color-ink-muted);
font-size: 0.8rem;
}
.drop-hint {
margin: 0.5rem 0;
text-align: center;
}
.bank-error {
color: var(--color-ink-danger);
margin: 0.5rem 0;
}
.bank-filter,
.bank textarea,
.snippet-section {
width: 100%;
padding: 0.25rem 0.4rem;
border: 1px solid var(--color-line);
border-radius: 4px;
font: inherit;
}
.bank textarea {
resize: vertical;
line-height: 1.4;
}
.group {
margin-top: 0.75rem;
}
.group h4 {
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-ink-muted);
margin-bottom: 0.3rem;
}
.snippet {
position: relative;
margin-bottom: 0.5rem;
padding: 0.4rem 0.4rem 0.4rem 1.3rem;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
background: var(--color-paper);
}
/* A full-height strip down the left edge, so it is easy to grab. */
.grip {
position: absolute;
inset: 0 auto 0 0;
width: 1.1rem;
padding-top: 0.45rem;
text-align: center;
color: var(--color-ink-faint);
font-size: 0.75rem;
letter-spacing: -0.15em;
cursor: grab;
user-select: none;
}
.grip:hover {
color: var(--color-ink-soft);
background: var(--color-paper-tint);
}
.snippet-foot {
display: flex;
gap: 0.4rem;
margin-top: 0.3rem;
}
.snippet-section {
flex: 1;
font-size: 0.8rem;
}
.add {
margin-top: 1rem;
padding-top: 0.75rem;
border-top: 1px solid var(--color-line);
}
</style>
+133
View File
@@ -0,0 +1,133 @@
/**
* The cover letter as data, with no Vue in it: the default letter, the JSON
* body stored in a CoverLetter row (stores/coverLetters.js), and the moves
* the drag and drop in CoverLetters.vue makes.
*
* Body shape (v: 1):
* { v, name, phone, email, role, signoff,
* sections: [{ id, title, paragraphs: [{ id, text }] }] }
*
* Every section and paragraph carries an id because the template keys its
* v-for on it. Keying on the index would leave a contenteditable showing the
* old text after a reorder, since Vue would reuse the element in place.
*
* A position is `{ section, index }`: a section's index and a paragraph's
* index inside it. `index` may equal the paragraph count, meaning "at the end".
*/
export const BODY_VERSION = 1;
/** A short id, unique enough within one letter. crypto.randomUUID would do,
* but it is missing outside a secure context (the dev stack over a LAN IP). */
export function newId() {
return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}
export function newParagraph(text = "New paragraph...") {
return { id: newId(), text };
}
export function newSection(title = "New section", texts = []) {
return { id: newId(), title, paragraphs: texts.map(newParagraph) };
}
/** The blank template a visitor sees, and what "New" starts from. */
export function newLetter() {
return {
v: BODY_VERSION,
name: "Adam French",
phone: "+447563266931",
email: "[email protected]",
role: "Job title / role",
signoff: "Thank you for reading - Adam F",
sections: [
newSection("Why the company", ["Why I'm interested in the company..."]),
newSection("Why I fit", ["Why I'm a strong fit for the role..."]),
newSection("Experience", ["Relevant experience and background..."]),
],
};
}
const str = (v, fallback) => (typeof v === "string" ? v : fallback);
/**
* Read a stored body back into a letter. Anything missing or malformed
* falls back to the default field by field, so a hand-edited or older row
* still opens rather than blanking the page; ids are regenerated if absent.
*/
export function parseBody(json) {
const base = newLetter();
let raw;
try {
raw = JSON.parse(json);
} catch {
return base;
}
if (!raw || typeof raw !== "object") return base;
const sections = Array.isArray(raw.sections)
? raw.sections
.filter((s) => s && typeof s === "object")
.map((s) => ({
id: str(s.id, newId()),
title: str(s.title, ""),
paragraphs: Array.isArray(s.paragraphs)
? s.paragraphs
.filter((p) => p && typeof p.text === "string")
.map((p) => ({ id: str(p.id, newId()), text: p.text }))
: [],
}))
: base.sections;
return {
v: BODY_VERSION,
name: str(raw.name, base.name),
phone: str(raw.phone, base.phone),
email: str(raw.email, base.email),
role: str(raw.role, base.role),
signoff: str(raw.signoff, base.signoff),
sections,
};
}
/** The JSON stored as a CoverLetter's body. Also what the "unsaved" marker
* compares, so the key order here must stay fixed. */
export function serialize(letter) {
return JSON.stringify({
v: BODY_VERSION,
name: letter.name,
phone: letter.phone,
email: letter.email,
role: letter.role,
signoff: letter.signoff,
sections: letter.sections.map((s) => ({
id: s.id,
title: s.title,
paragraphs: s.paragraphs.map((p) => ({ id: p.id, text: p.text })),
})),
});
}
/**
* Move the paragraph at `from` to `to`, both positions as they are before the
* move. Moving down within one section shifts the target up by one once the
* paragraph has been taken out, which is corrected here so a drop lands where
* the indicator showed.
*/
export function moveParagraph(letter, from, to) {
const src = letter.sections[from.section];
const dst = letter.sections[to.section];
if (!src || !dst || !src.paragraphs[from.index]) return;
let index = to.index;
if (from.section === to.section) {
if (index === from.index || index === from.index + 1) return;
if (index > from.index) index -= 1;
}
const [para] = src.paragraphs.splice(from.index, 1);
dst.paragraphs.splice(index, 0, para);
}
/** Put a new paragraph holding `text` at `to`. */
export function insertParagraph(letter, to, text) {
const dst = letter.sections[to.section];
if (!dst) return;
dst.paragraphs.splice(to.index, 0, newParagraph(text));
}
+125
View File
@@ -0,0 +1,125 @@
<script setup>
/**
* Routes `/account` and `/no-access` (both `meta.requiresSignIn`): the landing
* page for a signed-in account that is not an admin, listing the gated
* services it has been granted (backend/services/permissions.go) as links.
*
* `/no-access` is where nginx's permission gate sends a signed-in visitor who
* lacks the permission (`@auth_forbidden`, with the refused address in
* `?path=`). It is this same page with a notice on top, since "what can I
* open instead" is the useful answer to "you can't open that".
*
* The links are plain <a href>, not RouterLinks: every service lives in
* another container behind nginx, so it needs a real page load.
*/
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import Button from "@/components/input/Button.vue";
const auth = useAuthStore();
const route = useRoute();
const router = useRouter();
const permissionTypes = ref([]);
const loaded = ref(false);
const error = ref("");
const services = computed(() =>
permissionTypes.value.filter((p) => auth.can(p.key)),
);
// Only shown on /no-access, and only as text, so an odd value is harmless.
const refused = computed(() =>
route.name === "no-access" && typeof route.query.path === "string"
? route.query.path
: "",
);
onMounted(async () => {
try {
permissionTypes.value = await auth.fetchPermissionTypes();
} catch (err) {
console.error(err);
error.value = err.message || "Couldn't load your services";
} finally {
loaded.value = true;
}
});
// The guard only runs on navigation, so logging out in place would leave the
// page up for a signed-out visitor; leave it instead.
async function handleLogout() {
await auth.logOut();
router.push("/admin/login");
}
</script>
<template>
<main class="account-page">
<div class="account-card bdr-1">
<p v-if="refused" class="account-refused" role="alert">
You don't have access to <code>{{ refused }}</code>.
</p>
<h1>Your services</h1>
<small>Signed in as <code>{{ auth.user.username }}</code>.</small>
<p v-if="error" class="text-tertiary" role="alert">{{ error }}</p>
<p v-else-if="!loaded" class="text-muted">Loading…</p>
<ul v-else-if="services.length" class="account-services">
<li v-for="s in services" :key="s.key">
<a :href="s.path">{{ s.label }}</a>
</li>
</ul>
<p v-else class="text-muted">Nothing has been shared with you yet.</p>
<div class="account-actions">
<Button v-if="auth.user.admin" @click="router.push('/admin')">
Open Admin
</Button>
<Button @click="handleLogout">Log Out</Button>
</div>
</div>
</main>
</template>
<style scoped>
.account-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 70vh;
padding: 16px;
}
.account-card {
width: 100%;
max-width: 380px;
background-color: var(--color-surface);
padding: 18px 20px 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.account-refused {
color: var(--color-tertiary);
border: 1px dashed var(--color-tertiary);
padding: 4px 8px;
}
.account-services {
display: flex;
flex-direction: column;
gap: 4px;
padding-left: 1.2rem;
list-style: square;
}
.account-actions {
display: flex;
gap: 6px;
margin-top: 4px;
}
</style>
+67 -5
View File
@@ -6,6 +6,7 @@
* imported, since reaching this page means you want them.
*/
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import Button from "@/components/input/Button.vue";
@@ -21,6 +22,7 @@ import ManageUsers from "./ManageUsers.vue";
import ManageRadio from "./ManageRadio.vue";
const auth = useAuthStore();
const router = useRouter();
const sections = [
{ id: "user", label: "User", component: CreateUser },
@@ -40,8 +42,32 @@ const activeSection = computed(() =>
sections.find((s) => s.id === active.value),
);
function handleLogout() {
auth.logOut();
// The create forms emit "done"/"cancel" and leave it to the host to react
// (the Feed widget's modal closes on them). Here the form stays open, so
// "done" needs a visible confirmation, and "cancel" remounts the form via
// formKey, which is the only way to clear fields the form keeps to itself.
const notice = ref("");
const formKey = ref(0);
function selectSection(id) {
active.value = id;
notice.value = "";
}
function onDone() {
notice.value = "Saved.";
}
function onCancel() {
notice.value = "";
formKey.value++;
}
// The requiresAdmin guard only runs on navigation, so logging out in place
// would leave the panel on screen for a signed-out visitor; leave it instead.
async function handleLogout() {
await auth.logOut();
router.push("/admin/login");
}
</script>
@@ -59,13 +85,15 @@ function handleLogout() {
</header>
<div class="admin-body">
<nav class="admin-nav">
<nav class="admin-nav" aria-label="Admin sections">
<button
v-for="section in sections"
:key="section.id"
type="button"
class="admin-nav-link"
:class="{ 'is-active': active === section.id }"
@click="active = section.id"
:aria-current="active === section.id ? 'page' : undefined"
@click="selectSection(section.id)"
>
{{ section.label }}
</button>
@@ -79,10 +107,29 @@ function handleLogout() {
>
Logs ↗
</a>
<!-- The receipt printer's page is served from stppi, which reaches
the printer on the home LAN; nginx proxies /receipt/ there over
Tailscale behind the `receipt` permission gate. -->
<a
class="admin-nav-link no-underline"
href="/receipt/"
target="_blank"
rel="noopener"
>
Receipt printer ↗
</a>
</nav>
<section class="admin-panel bdr-2 bg-surface">
<component :is="activeSection.component" />
<component
:is="activeSection.component"
:key="formKey"
@done="onDone"
@cancel="onCancel"
/>
<small v-if="notice" class="admin-notice" role="status">
{{ notice }}
</small>
</section>
</div>
</div>
@@ -157,9 +204,24 @@ function handleLogout() {
margin-top: 0;
}
.admin-notice {
display: block;
margin-top: 8px;
color: var(--color-secondary);
}
/* On a phone the section list would be eleven full-width rows above the
form; as wrapping chips it takes three or four lines. */
@media (max-width: 700px) {
.admin-body {
grid-template-columns: 1fr;
}
.admin-nav {
flex-direction: row;
flex-wrap: wrap;
}
.admin-nav-link {
padding: 4px 8px;
}
}
</style>
+11 -8
View File
@@ -8,7 +8,7 @@ import { useCreateForm } from "@/js/useCreateForm";
const emit = defineEmits(["done", "cancel"]);
const { values, submit: post } = useCreateForm({
const { values, submit: post, error, submitting } = useCreateForm({
mutation: `mutation CreateActivity($input: CreateActivityInput!) { createActivity(input: $input) { id } }`,
fields: ["type", "name", "link"],
optional: ["link"],
@@ -19,12 +19,15 @@ const { type, name, link } = values;
</script>
<template>
<div class="flex flex-col">
<form class="flex flex-col" @submit.prevent="post">
<h1>Create Activity</h1>
<input type="text" v-model="type" placeholder="Type" @keyup.enter="post" />
<input type="text" v-model="name" placeholder="Name" @keyup.enter="post" />
<input type="text" v-model="link" placeholder="Link" @keyup.enter="post" />
<Button @click="post">Upload</Button>
<Button @click="emit('cancel')">Cancel</Button>
</div>
<input type="text" v-model="type" placeholder="Type" />
<input type="text" v-model="name" placeholder="Name" />
<input type="text" v-model="link" placeholder="Link" />
<small v-if="error" class="p-1" role="alert">{{ error }}</small>
<Button type="submit" :disabled="submitting">
{{ submitting ? "Uploading…" : "Upload" }}
</Button>
<Button type="button" @click="emit('cancel')">Cancel</Button>
</form>
</template>
+10 -17
View File
@@ -8,7 +8,7 @@ import { useCreateForm } from "@/js/useCreateForm";
const emit = defineEmits(["done", "cancel"]);
const { values, submit } = useCreateForm({
const { values, submit, error, submitting } = useCreateForm({
mutation: `mutation CreateBookmark($input: CreateBookmarkInput!) { createBookmark(input: $input) { id } }`,
fields: ["category", "name", "link"],
emit,
@@ -17,22 +17,15 @@ const { category, name, link } = values;
</script>
<template>
<div class="flex flex-col">
<form class="flex flex-col" @submit.prevent="submit">
<h1>Create Bookmark</h1>
<input type="text" v-model="category" placeholder="Category" />
<input
type="text"
v-model="name"
placeholder="Name"
@keyup.enter="submit"
/>
<input
type="text"
v-model="link"
placeholder="Link"
@keyup.enter="submit"
/>
<Button @click="submit">Upload</Button>
<Button @click="emit('cancel')">Cancel</Button>
</div>
<input type="text" v-model="name" placeholder="Name" />
<input type="text" v-model="link" placeholder="Link" />
<small v-if="error" class="p-1" role="alert">{{ error }}</small>
<Button type="submit" :disabled="submitting">
{{ submitting ? "Uploading…" : "Upload" }}
</Button>
<Button type="button" @click="emit('cancel')">Cancel</Button>
</form>
</template>
+11 -8
View File
@@ -8,7 +8,7 @@ import { useCreateForm } from "@/js/useCreateForm";
const emit = defineEmits(["done", "cancel"]);
const { values, submit: post } = useCreateForm({
const { values, submit: post, error, submitting } = useCreateForm({
mutation: `mutation CreateFavorite($input: CreateFavoriteInput!) { createFavorite(input: $input) { id } }`,
fields: ["type", "name", "link"],
optional: ["link"],
@@ -19,12 +19,15 @@ const { type, name, link } = values;
</script>
<template>
<div class="flex flex-col">
<form class="flex flex-col" @submit.prevent="post">
<h1>Create Favorite</h1>
<input type="text" v-model="type" placeholder="Type" @keyup.enter="post" />
<input type="text" v-model="name" placeholder="Name" @keyup.enter="post" />
<input type="text" v-model="link" placeholder="Link" @keyup.enter="post" />
<Button @click="post">Upload</Button>
<Button @click="emit('cancel')">Cancel</Button>
</div>
<input type="text" v-model="type" placeholder="Type" />
<input type="text" v-model="name" placeholder="Name" />
<input type="text" v-model="link" placeholder="Link" />
<small v-if="error" class="p-1" role="alert">{{ error }}</small>
<Button type="submit" :disabled="submitting">
{{ submitting ? "Uploading…" : "Upload" }}
</Button>
<Button type="button" @click="emit('cancel')">Cancel</Button>
</form>
</template>
+16 -31
View File
@@ -19,13 +19,16 @@ const imageUrl = ref("");
const notes = ref("");
const done = ref(false);
const error = ref("");
const submitting = ref(false);
async function submit() {
if (submitting.value) return;
if (!title.value.trim()) {
error.value = "Title is required";
return;
}
error.value = "";
submitting.value = true;
try {
await places.create({
title: title.value.trim(),
@@ -48,56 +51,38 @@ async function submit() {
emit("done");
} catch (err) {
error.value = err?.message || "Failed to save";
} finally {
submitting.value = false;
}
}
</script>
<template>
<div class="flex flex-col">
<form class="flex flex-col" @submit.prevent="submit">
<h1>Add Place / Thing To Do</h1>
<input
type="text"
v-model="title"
placeholder="Title (required)"
@keyup.enter="submit"
/>
<input
type="text"
v-model="location"
placeholder="Location"
@keyup.enter="submit"
/>
<input type="text" v-model="title" placeholder="Title (required)" />
<input type="text" v-model="location" placeholder="Location" />
<input
type="text"
v-model="category"
placeholder="Category (place, activity, food…)"
@keyup.enter="submit"
/>
<input
type="text"
v-model="cost"
placeholder="Cost (e.g. £20 pp)"
@keyup.enter="submit"
/>
<input type="text" v-model="cost" placeholder="Cost (e.g. £20 pp)" />
<input
type="number"
v-model="priority"
placeholder="Priority (higher = sooner)"
@keyup.enter="submit"
/>
<input
type="text"
v-model="imageUrl"
placeholder="Image URL"
@keyup.enter="submit"
/>
<input type="text" v-model="imageUrl" placeholder="Image URL" />
<textarea class="h-25" v-model="notes" placeholder="Notes"></textarea>
<label class="flex flex-row items-center gap-2 p-2 text-primary">
<input type="checkbox" v-model="done" class="w-auto" />
Already done
</label>
<small v-if="error" class="p-1">{{ error }}</small>
<Button @click="submit">Upload</Button>
<Button @click="emit('cancel')">Cancel</Button>
</div>
<small v-if="error" class="p-1" role="alert">{{ error }}</small>
<Button type="submit" :disabled="submitting">
{{ submitting ? "Uploading…" : "Upload" }}
</Button>
<Button type="button" @click="emit('cancel')">Cancel</Button>
</form>
</template>
+9 -11
View File
@@ -10,7 +10,7 @@ import { useCreateForm } from "@/js/useCreateForm";
const emit = defineEmits(["done", "cancel"]);
const { values, submit: post } = useCreateForm({
const { values, submit: post, error, submitting } = useCreateForm({
mutation: `mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id } }`,
fields: ["title", "content"],
resultKey: "createPost",
@@ -20,16 +20,14 @@ const { title, content } = values;
</script>
<template>
<div class="flex flex-col">
<form class="flex flex-col" @submit.prevent="post">
<h1>Create Post</h1>
<input
type="text"
v-model="title"
placeholder="Title"
@keyup.enter="post"
/>
<input type="text" v-model="title" placeholder="Title" />
<textarea class="h-50" v-model="content" placeholder="Content"></textarea>
<Button @click="post">Upload</Button>
<Button @click="emit('cancel')">Cancel</Button>
</div>
<small v-if="error" class="p-1" role="alert">{{ error }}</small>
<Button type="submit" :disabled="submitting">
{{ submitting ? "Uploading…" : "Upload" }}
</Button>
<Button type="button" @click="emit('cancel')">Cancel</Button>
</form>
</template>
+11 -4
View File
@@ -16,6 +16,7 @@ const emit = defineEmits(["done", "cancel"]);
const images = ref([]);
const results = ref([]);
const uploading = ref(false);
function onFileChange(e) {
images.value = Array.from(e.target.files);
@@ -23,7 +24,8 @@ function onFileChange(e) {
}
async function submit() {
if (!images.value.length) return;
if (!images.value.length || uploading.value) return;
uploading.value = true;
results.value = images.value.map((f) => ({
name: f.name,
status: "Uploading...",
@@ -54,7 +56,10 @@ async function submit() {
);
images.value = [];
emit("done");
uploading.value = false;
// Only a clean run counts as done: hosts close or confirm on "done", which
// would hide or contradict the per-file failure rows above.
if (results.value.every((r) => r.ok)) emit("done");
}
</script>
@@ -67,11 +72,13 @@ async function submit() {
multiple
@change="onFileChange"
/>
<Button @click="submit">Upload</Button>
<Button @click="submit" :disabled="uploading || !images.length">
{{ uploading ? "Reading…" : "Upload" }}
</Button>
<Button @click="emit('cancel')">Cancel</Button>
<div v-for="r in results" :key="r.name">
<span class="text-primary">{{ r.name }}: </span>
<span :class="r.ok ? 'text-secondary' : 'text-red-500'">{{
<span :class="r.ok ? 'text-secondary' : 'text-tertiary'">{{
r.status
}}</span>
</div>
+18 -7
View File
@@ -12,10 +12,13 @@ const username = ref("");
const password = ref("");
const message = ref("");
const error = ref("");
const submitting = ref(false);
async function handleCreate() {
if (submitting.value) return;
message.value = "";
error.value = "";
submitting.value = true;
try {
const data = await gql(
`mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id username } }`,
@@ -26,29 +29,37 @@ async function handleCreate() {
password.value = "";
} catch (err) {
error.value = err.message || "Failed to create user.";
} finally {
submitting.value = false;
}
}
</script>
<template>
<div v-if="auth.loggedIn && auth.user.admin" class="flex flex-col">
<form
v-if="auth.loggedIn && auth.user.admin"
class="flex flex-col"
@submit.prevent="handleCreate"
>
<h1>Create User</h1>
<p v-if="message" class="text-green-500">{{ message }}</p>
<p v-if="error" class="text-red-500">{{ error }}</p>
<p v-if="message" class="text-secondary" role="status">{{ message }}</p>
<p v-if="error" class="text-tertiary" role="alert">{{ error }}</p>
<input
type="text"
v-model="username"
placeholder="Username"
@keyup.enter="handleCreate"
autocomplete="off"
/>
<input
type="password"
v-model="password"
placeholder="Password"
@keyup.enter="handleCreate"
autocomplete="new-password"
/>
<Button @click="handleCreate">Create Account</Button>
</div>
<Button type="submit" :disabled="submitting">
{{ submitting ? "Creating…" : "Create Account" }}
</Button>
</form>
<div v-else-if="auth.loggedIn" class="flex flex-col">
<p>You do not have permission to create users.</p>
</div>
+28 -14
View File
@@ -1,10 +1,13 @@
<script setup>
/**
* Route `/admin/login`. On success redirects to `?redirect=` or to /admin.
* Route `/admin/login`, the one login page for everyone: admins and accounts
* granted a gated service (the receipt printer, say). On success redirects to
* `?redirect=`, or else to /admin for an admin and /account for anyone else
* (a non-admin would only bounce off /admin's guard back to here).
*
* The `?redirect=` is set by two different gates: the SPA router guard
* (`meta.requiresAdmin`) and nginx's `auth_request` gate in front of the
* proxied containers (/notes/, /sb/). The latter means the
* proxied containers (/notes/, /sb/, /receipt/). The latter means the
* destination is frequently NOT a Vue route, so see goTo() below.
*
* auth.logIn() never throws — it swallows the error — so success is detected by
@@ -31,8 +34,8 @@ const errorMsg = ref("");
// Send the browser to `dest`, choosing SPA navigation vs. a real page load.
//
// nginx bounces /notes/ and /sb/ here when the admin cookie is
// missing; those paths belong to other containers, so router.push() would just
// nginx bounces /notes/, /sb/, /receipt/ and the like here when the session
// is missing; those paths belong to other containers, so router.push() would just
// match the catch-all 404 route and never leave the SPA. Resolving the path
// first tells us which it is: the catch-all matches everything, so landing on
// the route named "404" means no real Vue route exists and the browser needs a
@@ -42,7 +45,7 @@ const errorMsg = ref("");
// site-relative path — a leading "//" or a scheme would be an open redirect.
function goTo(dest) {
if (typeof dest !== "string" || !dest.startsWith("/") || dest.startsWith("//")) {
router.push("/admin");
router.push(home());
return;
}
if (router.resolve(dest).name !== "404") {
@@ -52,6 +55,11 @@ function goTo(dest) {
}
}
// Where a signed-in user lands when nothing asked for anywhere in particular.
function home() {
return auth.user.admin ? "/admin" : "/account";
}
async function handleLogin() {
if (submitting.value) return;
submitting.value = true;
@@ -61,7 +69,7 @@ async function handleLogin() {
// `loggedIn` rather than by catching.
await auth.logIn(username.value, password.value);
if (auth.loggedIn) {
goTo(route.query.redirect || "/admin");
goTo(route.query.redirect || home());
} else {
errorMsg.value = "Invalid username or password";
}
@@ -81,15 +89,19 @@ function handleLogout() {
<h1>Already signed in</h1>
<p>You're logged in as <code>{{ auth.user.username }}</code>.</p>
<div class="login-actions">
<Button @click="router.push('/admin')">Open Admin</Button>
<Button @click="router.push(home())">
{{ auth.user.admin ? "Open Admin" : "Your Services" }}
</Button>
<Button @click="handleLogout">Log Out</Button>
</div>
</div>
<div v-else class="login-card bdr-1">
<!-- A real <form>, so Enter submits from either field and password
managers recognise it as a sign-in. -->
<form v-else class="login-card bdr-1" @submit.prevent="handleLogin">
<h1>Login</h1>
<small class="login-hint">
Admin access is required beyond this point.
Sign in to continue.
</small>
<label class="login-field">
@@ -99,7 +111,7 @@ function handleLogout() {
v-model="username"
autocomplete="username"
placeholder="Username"
@keyup.enter="handleLogin"
required
/>
</label>
@@ -110,16 +122,18 @@ function handleLogout() {
v-model="password"
autocomplete="current-password"
placeholder="Password"
@keyup.enter="handleLogin"
required
/>
</label>
<small v-if="errorMsg" class="login-error">{{ errorMsg }}</small>
<small v-if="errorMsg" class="login-error" role="alert">
{{ errorMsg }}
</small>
<Button @click="handleLogin" :disabled="submitting">
<Button type="submit" class="mt-1 py-2" :disabled="submitting">
{{ submitting ? "Signing in…" : "Log In" }}
</Button>
</div>
</form>
</main>
</template>
+115 -3
View File
@@ -7,8 +7,13 @@
* "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.
*
* "Layouts" lists the saved layouts (stores/layouts.js) and copies one onto
* any page without opening it — the same as "Load here" in that page's
* Layouts panel, where layouts are also saved and renamed.
*/
import { usePagesStore } from "@/stores/pages";
import { pagePath, useLayoutsStore } from "@/stores/layouts";
import PageForm from "@/views/canvas/PageForm.vue";
import { ref } from "vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
@@ -17,6 +22,47 @@ const pages = usePagesStore();
pages.fetch();
const removeTarget = ref(null);
const confirmationOpen = ref(false);
const removeError = ref("");
const layouts = useLayoutsStore();
layouts.fetch();
const layoutError = ref("");
const layoutNotice = ref("");
// { layout, page } waiting on "replace or add?", and the layout to delete.
const copyRequest = ref(null);
const deleteLayoutTarget = ref(null);
function askCopy(layout, event) {
const page = event.target.value;
event.target.value = "";
if (page) copyRequest.value = { layout, page };
}
async function layoutAction(action, done) {
layoutError.value = "";
layoutNotice.value = "";
try {
await action();
layoutNotice.value = done;
} catch (err) {
layoutError.value = err?.message || "Failed";
}
}
function copy(replace) {
const { layout, page } = copyRequest.value;
copyRequest.value = null;
layoutAction(
() => layouts.apply(layout.id, page, replace),
`“${layout.name}” ${replace ? "now fills" : "was added to"} ${pagePath(page)}.`,
);
}
function confirmDeleteLayout() {
const layout = deleteLayoutTarget.value;
deleteLayoutTarget.value = null;
layoutAction(() => layouts.remove(layout.id), `Deleted “${layout.name}”.`);
}
async function remove(page) {
removeTarget.value = page;
@@ -27,10 +73,11 @@ async function confirmRemove() {
const page = removeTarget.value;
removeTarget.value = null;
if (!page) return;
removeError.value = "";
try {
await pages.remove(page.id);
} catch (err) {
alert(err?.message || "Failed to delete");
removeError.value = err?.message || "Failed to delete";
}
}
</script>
@@ -40,8 +87,11 @@ async function confirmRemove() {
<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.
The landing page (/) is a canvas too, but not listed here — edit it on
the page itself.
</p>
<p v-if="removeError" class="text-tertiary" role="alert">
{{ removeError }}
</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">
@@ -59,6 +109,39 @@ async function confirmRemove() {
<p v-else-if="pages.loaded" class="text-muted">No pages yet.</p>
</section>
<section>
<h1>Layouts</h1>
<p class="text-muted">
Saved copies of a page's boxes and background. Save one from a page's
Layouts button; copy it onto another page here or from that page.
Replacing a page's contents saves them as a layout first.
</p>
<p v-if="layoutError" class="text-tertiary" role="alert">{{ layoutError }}</p>
<p v-else-if="layoutNotice" class="text-muted" role="status">{{ layoutNotice }}</p>
<p v-if="layouts.error" class="text-tertiary">Couldn't load the layouts.</p>
<table v-else-if="layouts.layouts.length" class="w-full">
<tr v-for="layout in layouts.layouts" :key="layout.id">
<td>{{ layout.name }}</td>
<td class="text-muted">
from {{ pagePath(layout.sourcePage) }} · {{ layout.boxCount }} box{{ layout.boxCount === 1 ? "" : "es" }}
</td>
<td>
<select class="copy-select" aria-label="Copy onto page" @change="askCopy(layout, $event)">
<option value="">Copy onto…</option>
<option value="index">/ (landing)</option>
<option v-for="page in pages.pages" :key="page.id" :value="page.slug">/{{ page.slug }}</option>
</select>
</td>
<td class="text-right">
<button type="button" class="text-tertiary cursor-pointer" @click="deleteLayoutTarget = layout">
Delete
</button>
</td>
</tr>
</table>
<p v-else-if="layouts.loaded" class="text-muted">No saved layouts yet.</p>
</section>
<section>
<h1>New shrine</h1>
<p class="text-muted">
@@ -82,5 +165,34 @@ async function confirmRemove() {
@confirm="confirmRemove"
@cancel="removeTarget = null"
/>
<ConfirmDialog
v-if="copyRequest"
:model-value="true"
title="Copy layout"
:message="`Replace everything on ${pagePath(copyRequest.page)} with “${copyRequest.layout.name}”, or add it on top? Replacing saves the page as a layout first.`"
confirm-label="Replace"
secondary-label="Add on top"
@confirm="copy(true)"
@secondary="copy(false)"
@cancel="copyRequest = null"
/>
<ConfirmDialog
v-if="deleteLayoutTarget"
:model-value="true"
title="Delete layout"
:message="`Delete the layout “${deleteLayoutTarget.name}”? Pages it was copied onto keep their boxes.`"
confirm-label="Delete"
@confirm="confirmDeleteLayout"
@cancel="deleteLayoutTarget = null"
/>
</div>
</template>
<style scoped>
.copy-select {
padding: 0.25rem;
color: var(--color-primary);
background: var(--color-surface-deep);
border: 1px solid var(--color-primary);
}
</style>
+52 -10
View File
@@ -2,8 +2,11 @@
/**
* Admin panel: list and upload tracks for the Icecast radio. REST
* (multipart/form-data) rather than GraphQL because it moves files.
* Deleting removes the file from the radio's library for good, so it asks
* first; a failed list, enable/disable or delete is shown above the list.
*/
import Button from "@/components/input/Button.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
import { ref, onMounted } from "vue";
import { api } from "@/api";
@@ -11,13 +14,19 @@ const songs = ref([]);
const files = ref([]);
const results = ref([]);
const loading = ref(false);
const error = ref("");
const deleteTarget = ref(null);
const confirmOpen = ref(false);
async function fetchSongs() {
try {
const res = await api.get("/radio/songs");
const res = await api.get("/radio/songs", {
fallback: "Couldn't load the songs",
});
songs.value = res.songs;
} catch (err) {
console.error(err);
error.value = err.message;
}
}
@@ -57,22 +66,40 @@ async function upload() {
await fetchSongs();
}
async function deleteSong(name) {
function askDelete(song) {
deleteTarget.value = song;
confirmOpen.value = true;
}
async function deleteSong() {
const song = deleteTarget.value;
deleteTarget.value = null;
if (!song) return;
error.value = "";
try {
await api.delete(`/radio/songs/${encodeURIComponent(name)}`);
await api.delete(`/radio/songs/${encodeURIComponent(song.name)}`, {
fallback: "Delete failed",
});
await fetchSongs();
} catch (err) {
console.error(err);
error.value = err.message;
}
}
async function toggleSong(song) {
const action = song.disabled ? "enable" : "disable";
error.value = "";
try {
await api.patch(`/radio/songs/${encodeURIComponent(song.name)}/${action}`);
await api.patch(
`/radio/songs/${encodeURIComponent(song.name)}/${action}`,
undefined,
{ fallback: `Couldn't ${action} the song` },
);
await fetchSongs();
} catch (err) {
console.error(err);
error.value = err.message;
}
}
@@ -94,26 +121,41 @@ onMounted(fetchSongs);
multiple
@change="onFileChange"
/>
<Button @click="upload" :disabled="loading">Upload</Button>
<Button @click="upload" :disabled="loading || !files.length">
{{ loading ? "Uploading…" : "Upload" }}
</Button>
<p v-if="error" class="text-tertiary" role="alert">{{ error }}</p>
<div v-for="r in results" :key="r.name">
<span class="text-primary">{{ r.name }}: </span>
<span :class="r.ok ? 'text-secondary' : 'text-red-500'">{{
<span :class="r.ok ? 'text-secondary' : 'text-tertiary'">{{
r.status
}}</span>
</div>
<div
v-for="song in songs"
:key="song.name"
class="flex flex-row items-center gap-2"
class="flex flex-row flex-wrap items-center gap-2"
:class="{ 'opacity-50': song.disabled }"
>
<span :class="{ 'line-through': song.disabled }">{{ song.name }}</span>
<span class="text-primary" :class="{ 'line-through': song.disabled }">
{{ song.name }}
</span>
<span class="text-secondary text-sm">{{ formatSize(song.size) }}</span>
<span v-if="song.disabled" class="text-red-400 text-xs">disabled</span>
<span v-if="song.disabled" class="text-tertiary text-xs">disabled</span>
<Button @click="toggleSong(song)">{{
song.disabled ? "Enable" : "Disable"
}}</Button>
<Button @click="deleteSong(song.name)">Delete</Button>
<Button @click="askDelete(song)">Delete</Button>
</div>
<ConfirmDialog
v-if="deleteTarget"
v-model="confirmOpen"
title="Delete song"
:message="`Delete “${deleteTarget.name}” from the radio? The file is removed for good.`"
confirm-label="Delete"
@confirm="deleteSong"
@cancel="deleteTarget = null"
/>
</div>
</template>
+104 -20
View File
@@ -1,51 +1,135 @@
<script setup>
/**
* Admin panel: list users and toggle their admin flag. Mutates the local `user`
* object in place from the mutation's response, so the row updates without a
* refetch.
* Admin panel: list users, toggle their admin flag, and grant non-admins the
* gated services in `permissionTypes` (the receipt printer and so on; see
* backend/services/permissions.go). Mutates the local `user` object in place
* from each mutation's response, so the row updates without a refetch. A
* failed load or change is shown above the table rather than only logged, and
* a row's controls are disabled while a change to it is in flight.
*
* Admins pass every permission check on the server, so their checkboxes are
* replaced with "all" rather than shown with grants that would mean nothing.
* A grant or revoke applies on the user's next request (the gate reads the
* database, not their token), so there is nothing to tell them to do.
*/
import Button from "@/components/input/Button.vue";
import { ref, onMounted } from "vue";
import { useAuthStore } from "@/stores/auth";
import { useAuthStore, USER_FIELDS } from "@/stores/auth";
import { gql } from "@/graphql";
const auth = useAuthStore();
const users = ref([]);
const permissionTypes = ref([]);
const loaded = ref(false);
const error = ref("");
const pending = ref(null);
async function fetchUsers() {
try {
const data = await gql(`query { users { id username admin } }`);
const data = await gql(
`query { users { ${USER_FIELDS} } permissionTypes { key label path } }`,
);
users.value = data.users;
permissionTypes.value = data.permissionTypes;
} catch (err) {
console.error(err);
error.value = err.message || "Couldn't load the users";
} finally {
loaded.value = true;
}
}
async function toggleAdmin(user) {
// Shared by both kinds of change: one in flight per row, the row replaced
// from the server's answer, failures shown above the table.
async function change(user, mutate) {
error.value = "";
pending.value = user.id;
try {
const data = await auth.setUserAdmin(user.id, !user.admin);
user.admin = data.admin;
Object.assign(user, await mutate());
} catch (err) {
console.error(err);
error.value = err.message || `Couldn't change ${user.username}`;
} finally {
pending.value = null;
}
}
function toggleAdmin(user) {
return change(user, () => auth.setUserAdmin(user.id, !user.admin));
}
// The mutation replaces the whole list, so send the row's list with this one
// key flipped. Afterwards the box is set from the row: on a failure the row
// is unchanged, so Vue sees nothing to patch and would leave the box showing
// the click that did not take.
async function togglePermission(user, key, event) {
const current = user.permissions ?? [];
const next = current.includes(key)
? current.filter((k) => k !== key)
: [...current, key];
await change(user, () => auth.setUserPermissions(user.id, next));
event.target.checked = (user.permissions ?? []).includes(key);
}
onMounted(fetchUsers);
</script>
<template>
<div class="flex flex-col">
<div class="flex flex-col gap-2">
<h1>Manage Users</h1>
<div
v-for="user in users"
:key="user.id"
class="flex flex-row items-center gap-2"
>
<span>{{ user.username }}</span>
<span v-if="user.admin">(admin)</span>
<Button v-if="user.id !== auth.user.id" @click="toggleAdmin(user)">
{{ user.admin ? "Demote" : "Promote" }}
</Button>
</div>
<p v-if="error" class="text-tertiary" role="alert">{{ error }}</p>
<p v-if="!loaded" class="text-muted">Loading…</p>
<table v-else-if="users.length" class="w-full">
<tr v-for="user in users" :key="user.id">
<td class="py-1">{{ user.username }}</td>
<td class="py-1">{{ user.admin ? "admin" : "user" }}</td>
<td class="py-1">
<span v-if="user.admin" class="text-muted">all services</span>
<div v-else class="grants">
<label
v-for="p in permissionTypes"
:key="p.key"
class="grant"
:title="p.path"
>
<input
type="checkbox"
:checked="(user.permissions ?? []).includes(p.key)"
:disabled="pending === user.id"
@change="togglePermission(user, p.key, $event)"
/>
{{ p.label }}
</label>
</div>
</td>
<td class="py-1 text-right">
<span v-if="user.id === auth.user.id" class="text-muted">you</span>
<Button
v-else
:disabled="pending === user.id"
@click="toggleAdmin(user)"
>
{{ user.admin ? "Demote" : "Promote" }}
</Button>
</td>
</tr>
</table>
<p v-else-if="!error" class="text-muted">No users.</p>
</div>
</template>
<style scoped>
.grants {
display: flex;
flex-wrap: wrap;
gap: 0.2rem 0.8rem;
}
.grant {
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.grant input {
width: auto;
}
</style>
@@ -0,0 +1,83 @@
<script setup>
/**
* Route `/architecture` — how the whole site fits together, drawn.
*
* One long page of hand-written SVG diagrams, grouped into five sections
* (sections/*Section.vue), each of which lists its diagrams
* (diagrams/<section>/*.vue). Every diagram sits in a <DiagramFigure> and draws
* with the `dg-` classes in diagram.css; DiagramDefs supplies the shared
* arrowheads. No chart or graph library: the diagrams are static pictures of
* the code, so plain SVG is the smallest thing that does the job.
*
* The diagrams describe the code as it was when they were drawn. When a
* behaviour they show changes, redraw the diagram in the same commit.
*/
import "./diagram.css";
import Header from "@/components/text/Header.vue";
import Paragraph from "@/components/text/Paragraph.vue";
import DiagramDefs from "./DiagramDefs.vue";
import InfraSection from "./sections/InfraSection.vue";
import EdgeSection from "./sections/EdgeSection.vue";
import BackendSection from "./sections/BackendSection.vue";
import FrontendSection from "./sections/FrontendSection.vue";
import ServicesSection from "./sections/ServicesSection.vue";
const SECTIONS = [
{ id: "infra", label: "Infrastructure & deployment" },
{ id: "edge", label: "The edge: nginx" },
{ id: "backend", label: "Go backend" },
{ id: "frontend", label: "Vue frontend" },
{ id: "services", label: "Python & the other services" },
];
</script>
<template>
<main class="architecture flex justify-center px-4 py-10">
<DiagramDefs />
<div class="max-w-6xl w-full flex flex-col gap-10">
<section>
<Header>How this site works</Header>
<Paragraph>
Everything behind this website, drawn. It is a couple of
dozen Docker containers on one Ubuntu VM: nginx in front, a
Go GraphQL backend, a Vue single-page app, a Python API that
holds the Claude call and the scrapers, and a ring of
self-hosted services (Gitea, SilverBullet notes, Garage
object storage, Icecast radio, a job tracker) around them.
Each diagram can be expanded to full screen.
</Paragraph>
<nav class="toc">
<a v-for="s in SECTIONS" :key="s.id" :href="`#${s.id}`">
{{ s.label }}
</a>
</nav>
</section>
<InfraSection />
<EdgeSection />
<BackendSection />
<FrontendSection />
<ServicesSection />
</div>
</main>
</template>
<style scoped>
.toc {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
padding: 0.5rem 0.25rem;
}
.toc a {
padding: 0.2rem 0.75rem;
border: 1px solid var(--color-quaternary);
text-decoration: none;
}
.toc a:hover {
border-color: var(--color-primary);
}
.architecture :deep(section) {
scroll-margin-top: 4rem;
}
</style>
@@ -0,0 +1,51 @@
<!--
The arrowhead markers every diagram on /architecture uses, declared once.
diagram.css points the .dg-edge classes at these ids, so a diagram never
declares its own <defs> (fifty inline SVGs repeating the same ids would
collide).
Hidden by size rather than display:none — Firefox won't render markers
that live in a display:none SVG.
-->
<template>
<svg class="defs" aria-hidden="true" focusable="false">
<defs>
<marker
v-for="m in markers"
:id="m.id"
:key="m.id"
viewBox="0 0 10 10"
refX="9"
refY="5"
markerWidth="7"
markerHeight="7"
:orient="m.start ? 'auto-start-reverse' : 'auto'"
>
<path d="M0,0 L10,5 L0,10 z" :style="{ fill: m.colour }" />
</marker>
</defs>
</svg>
</template>
<script setup>
const colours = {
"": "var(--color-primary)",
"-pink": "var(--color-tertiary)",
"-green": "var(--color-secondary)",
"-muted": "var(--color-muted)",
};
const markers = Object.entries(colours).flatMap(([suffix, colour]) => [
{ id: `dg-arrow${suffix}`, colour, start: false },
{ id: `dg-arrow-start${suffix}`, colour, start: true },
]);
</script>
<style scoped>
.defs {
position: absolute;
width: 0;
height: 0;
overflow: hidden;
}
</style>
@@ -0,0 +1,132 @@
<!--
Frame for one diagram on /architecture: numbered title, the SVG (default
slot), and a caption (#caption slot).
The SVG scales to the column; below `minWidth` it stops shrinking and the
frame scrolls sideways instead, so small text stays readable on a phone.
Clicking "expand" lifts the figure into a full-screen overlay for the big
ones. Escape or the button closes it.
-->
<template>
<figure :id="id" class="figure" :class="{ expanded }">
<figcaption class="head">
<span class="title">
<a v-if="id" :href="`#${id}`" class="anchor">#</a>
{{ title }}
</span>
<button type="button" class="expand" @click="expanded = !expanded">
{{ expanded ? "close ✕" : "expand ⤢" }}
</button>
</figcaption>
<div class="canvas">
<div class="inner" :style="{ minWidth: `${minWidth}px` }">
<slot />
</div>
</div>
<div v-if="$slots.caption" class="caption">
<slot name="caption" />
</div>
</figure>
</template>
<script setup>
import { ref, watch, onBeforeUnmount } from "vue";
defineProps({
title: { type: String, required: true },
// Anchor id, so a figure can be linked to directly.
id: { type: String, default: "" },
minWidth: { type: Number, default: 640 },
});
const expanded = ref(false);
function onKey(e) {
if (e.key === "Escape") expanded.value = false;
}
watch(expanded, (open) => {
if (open) window.addEventListener("keydown", onKey);
else window.removeEventListener("keydown", onKey);
});
onBeforeUnmount(() => window.removeEventListener("keydown", onKey));
</script>
<style scoped>
.figure {
margin: 0;
border: 1px solid var(--color-quaternary);
background: var(--color-surface-deep);
scroll-margin-top: 4rem;
}
.head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.4rem 0.75rem;
border-bottom: 1px solid var(--color-quaternary);
background: var(--color-surface);
}
.title {
font-family: var(--font-heading);
font-size: 1.15rem;
letter-spacing: 0.04em;
color: var(--color-primary);
}
.anchor {
background: none;
color: var(--color-tertiary);
text-decoration: none;
margin-right: 0.25rem;
}
.expand {
font-family: var(--font-heading);
letter-spacing: 0.05em;
color: var(--color-tertiary);
background: var(--color-link-bg);
border: 1px solid var(--color-quaternary);
padding: 0.1rem 0.5rem;
cursor: pointer;
white-space: nowrap;
}
.expand:hover {
border-color: var(--color-tertiary);
}
.canvas {
overflow-x: auto;
padding: 0.75rem;
}
.caption {
padding: 0.5rem 0.75rem 0.75rem;
border-top: 1px dotted var(--color-quaternary);
color: var(--color-secondary);
font-size: 0.9rem;
line-height: 1.5;
}
.caption :deep(code) {
font-size: 0.85em;
}
.expanded {
position: fixed;
inset: 0;
z-index: 100;
display: flex;
flex-direction: column;
overflow: hidden;
}
.expanded .canvas {
flex: 1;
overflow: auto;
display: flex;
align-items: flex-start;
justify-content: center;
}
.expanded .inner {
width: min(100%, 1600px);
}
.expanded .caption {
max-height: 25vh;
overflow-y: auto;
}
</style>
+256
View File
@@ -0,0 +1,256 @@
/*
* The diagram kit: every SVG on /architecture draws with these classes, so
* fifty-odd diagrams written separately still read as one set. Colours come
* from the site's design tokens (assets/styles.css), never literals.
*
* Not scoped: the classes are applied to elements inside each diagram
* component's own template, and a scoped block would only reach its own file.
* Everything is prefixed `dg-` so nothing leaks into the rest of the site.
*
* Arrowheads are <marker>s defined once on the page by DiagramDefs.vue and
* referenced by the edge classes below, so diagrams never declare their own
* (duplicate ids across many inline SVGs would collide).
*/
.dg {
display: block;
width: 100%;
height: auto;
font-family: var(--font-body);
font-size: 12px;
}
/* ---- Boxes -------------------------------------------------------- */
.dg-box {
fill: var(--color-surface);
stroke: var(--color-primary);
stroke-width: 1.5;
}
.dg-box--pink {
stroke: var(--color-tertiary);
}
.dg-box--green {
stroke: var(--color-secondary);
}
.dg-box--teal {
stroke: var(--color-quaternary);
stroke-width: 2;
}
.dg-box--muted {
stroke: var(--color-muted);
stroke-dasharray: 4 3;
opacity: 0.85;
}
.dg-box--tint {
fill: var(--color-surface-tint);
}
.dg-box--deep {
fill: var(--color-surface-deep);
}
/* Solid accent fill: a highlighted node. Pair with .dg-text--ink. */
.dg-box--solid {
fill: var(--color-primary);
}
.dg-box--solid-pink {
fill: var(--color-tertiary);
stroke: var(--color-tertiary);
}
/* A dashed container drawn around a set of boxes (a network, a container, a
layer). Put it before its children so it sits underneath. */
.dg-group {
fill: none;
stroke: var(--color-quaternary);
stroke-width: 1.5;
stroke-dasharray: 6 4;
}
.dg-group--pink {
stroke: var(--color-tertiary);
opacity: 0.7;
}
.dg-group--fill {
fill: var(--color-surface-tint);
fill-opacity: 0.5;
}
/* ---- Text --------------------------------------------------------- */
/* Box / node titles: the condensed heading face, uppercase by nature. */
.dg-title {
font-family: var(--font-heading);
font-size: 16px;
letter-spacing: 0.04em;
fill: var(--color-primary);
}
.dg-title--pink {
fill: var(--color-tertiary);
}
.dg-title--lg {
font-size: 20px;
}
.dg-title--sm {
font-size: 13px;
}
.dg-text {
fill: var(--color-secondary);
font-size: 12px;
}
.dg-text--muted {
fill: var(--color-muted);
}
.dg-text--pink {
fill: var(--color-tertiary);
}
.dg-text--mint {
fill: var(--color-primary);
}
/* Dark text for use on .dg-box--solid / --solid-pink */
.dg-text--ink {
fill: var(--color-surface-deep);
}
.dg-small {
fill: var(--color-muted);
font-size: 10.5px;
}
.dg-code {
font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
font-size: 11px;
fill: var(--color-tertiary);
}
.dg-group-label {
font-family: var(--font-heading);
font-size: 13px;
letter-spacing: 0.06em;
fill: var(--color-quaternary);
filter: brightness(2.2);
}
/* Label sitting on a line: a halo in the page colour keeps it legible where
it crosses an edge. */
.dg-edge-label {
font-size: 10.5px;
fill: var(--color-muted);
paint-order: stroke;
stroke: var(--color-surface-deep);
stroke-width: 4px;
stroke-linejoin: round;
}
.dg-edge-label--pink {
fill: var(--color-tertiary);
}
.dg-edge-label--mint {
fill: var(--color-primary);
}
/* ---- Edges -------------------------------------------------------- */
.dg-edge {
fill: none;
stroke: var(--color-primary);
stroke-width: 1.5;
marker-end: url(#dg-arrow);
}
.dg-edge--pink {
stroke: var(--color-tertiary);
marker-end: url(#dg-arrow-pink);
}
.dg-edge--green {
stroke: var(--color-secondary);
marker-end: url(#dg-arrow-green);
}
.dg-edge--muted {
stroke: var(--color-muted);
marker-end: url(#dg-arrow-muted);
}
.dg-edge--dashed {
stroke-dasharray: 5 4;
}
/* Two-way: add an arrowhead at the start too. Combine with a colour class
and the matching --both-* class, e.g. "dg-edge dg-edge--pink dg-edge--both-pink". */
.dg-edge--both {
marker-start: url(#dg-arrow-start);
}
.dg-edge--both-pink {
marker-start: url(#dg-arrow-start-pink);
}
.dg-edge--both-green {
marker-start: url(#dg-arrow-start-green);
}
.dg-edge--both-muted {
marker-start: url(#dg-arrow-start-muted);
}
/* A line with no arrowhead: connectors, ER relationships, axes. */
.dg-edge--plain {
marker-end: none;
}
/* Marching ants for a live flow. Combine with any colour; motion stops for
people who asked for less. */
.dg-edge--flow {
stroke-dasharray: 6 5;
animation: dg-march 1.2s linear infinite;
}
@keyframes dg-march {
to {
stroke-dashoffset: -22;
}
}
@media (prefers-reduced-motion: reduce) {
.dg-edge--flow {
animation: none;
}
}
/* ---- Sequence diagrams ------------------------------------------- */
.dg-lifeline {
stroke: var(--color-quaternary);
stroke-width: 1.5;
stroke-dasharray: 3 4;
filter: brightness(1.8);
}
.dg-activation {
fill: var(--color-quaternary);
stroke: var(--color-primary);
stroke-width: 1;
}
/* ---- Small marks -------------------------------------------------- */
.dg-dot {
fill: var(--color-primary);
}
.dg-dot--pink {
fill: var(--color-tertiary);
}
.dg-dot--green {
fill: var(--color-secondary);
}
.dg-dot--muted {
fill: var(--color-muted);
}
/* Numbered step badge: a circle with .dg-badge-text centred on it. */
.dg-badge {
fill: var(--color-tertiary);
}
.dg-badge-text {
font-family: var(--font-heading);
font-size: 13px;
fill: var(--color-surface-deep);
text-anchor: middle;
dominant-baseline: central;
}
/* Divider / separator lines inside a box (table rows in an ER box, etc.) */
.dg-rule {
stroke: var(--color-quaternary);
stroke-width: 1;
filter: brightness(1.8);
}
/* Shaded band, e.g. a highlighted lane or a time window */
.dg-band {
fill: var(--color-quaternary);
opacity: 0.25;
}
.dg-band--pink {
fill: var(--color-tertiary);
opacity: 0.12;
}
@@ -0,0 +1,160 @@
<!--
Request lifecycle through the Go backend: nginx strips /api, Gin matches the
route, every chain starts with the traffic logger and Recovery, then the
route group's middleware (open / protected / admin) or, for /graphql,
AuthContextMiddleware -> gqlgen -> directive -> resolver. Everything ends at
handlers.Store.
Reflects: backend/main.go (r.Use, route groups, gqlSrv setup),
handlers/handle_auth.go (AuthMiddlewear, AdminMiddleware),
graph/middleware.go, graph/directives.go, nginx/nginx_routes.conf.template.
-->
<template>
<DiagramFigure id="backend-request-lifecycle" title="Request lifecycle: from nginx to a handler" :min-width="770">
<svg class="dg" viewBox="0 0 1100 660" role="img" aria-labelledby="backend-request-lifecycle-t">
<title id="backend-request-lifecycle-t">
A request passes nginx, the Gin router, the logger and Recovery, then one of four
middleware chains: open routes, the protected group, the admin group, or GraphQL.
</title>
<!-- Top row: into the engine -->
<rect class="dg-box dg-box--pink" x="20" y="50" width="100" height="75" rx="4" />
<text class="dg-title dg-title--pink" x="70" y="82" text-anchor="middle">BROWSER</text>
<text class="dg-small" x="70" y="102" text-anchor="middle">+ cookies</text>
<rect class="dg-box" x="150" y="50" width="200" height="75" rx="4" />
<text class="dg-title" x="250" y="74" text-anchor="middle">NGINX</text>
<text class="dg-code" x="250" y="94" text-anchor="middle">/api/graphql → /graphql</text>
<text class="dg-small" x="250" y="112" text-anchor="middle">TLS · limit_req · strips /api</text>
<rect class="dg-group dg-group--fill" x="370" y="20" width="720" height="120" rx="6" />
<text class="dg-group-label" x="384" y="38">GIN ENGINE · EVERY CHAIN STARTS LOGGER → RECOVERY</text>
<rect class="dg-box dg-box--tint" x="385" y="50" width="270" height="75" rx="4" />
<text class="dg-title" x="520" y="74" text-anchor="middle">ROUTER</text>
<text class="dg-code" x="520" y="94" text-anchor="middle">SetTrustedProxies(172.28.0.0/16)</text>
<text class="dg-small" x="520" y="112" text-anchor="middle">match route → pick its handler chain</text>
<rect class="dg-box" x="685" y="50" width="190" height="75" rx="4" />
<text class="dg-title" x="780" y="74" text-anchor="middle">LOGGER</text>
<text class="dg-code" x="780" y="94" text-anchor="middle">TrafficLogFormatter</text>
<text class="dg-small" x="780" y="112" text-anchor="middle">stdout + /backend/logs/go.log</text>
<rect class="dg-box" x="905" y="50" width="170" height="75" rx="4" />
<text class="dg-title" x="990" y="74" text-anchor="middle">RECOVERY</text>
<text class="dg-code" x="990" y="94" text-anchor="middle">gin.Recovery()</text>
<text class="dg-small" x="990" y="112" text-anchor="middle">panic → 500</text>
<path class="dg-edge dg-edge--pink" d="M120,88 H146" />
<path class="dg-edge" d="M350,88 H381" />
<path class="dg-edge" d="M655,88 H681" />
<path class="dg-edge" d="M875,88 H901" />
<!-- Trunk down to the four chains -->
<path class="dg-edge dg-edge--plain" d="M990,125 V158 H60 V600" />
<path class="dg-edge" d="M60,240 H96" />
<path class="dg-edge" d="M60,360 H96" />
<path class="dg-edge" d="M60,480 H96" />
<path class="dg-edge dg-edge--flow" d="M60,600 H96" />
<!-- Lane 1: open -->
<text class="dg-group-label" x="100" y="186">OPEN ROUTES · r.GET / r.POST</text>
<rect class="dg-box dg-box--muted" x="100" y="210" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm" x="195" y="236" text-anchor="middle">NO MIDDLEWARE</text>
<text class="dg-small" x="195" y="254" text-anchor="middle">handler checks cookies itself</text>
<path class="dg-edge" d="M290,240 H316" />
<rect class="dg-box" x="320" y="195" width="610" height="90" rx="4" />
<text class="dg-title dg-title--sm" x="340" y="216">HANDLER</text>
<text class="dg-code" x="340" y="237">GET /rowing · POST /auth/login · POST /auth/refresh · POST /auth/logout</text>
<text class="dg-code" x="340" y="256">GET /auth/check · GET /auth/validate-admin · GET /spotify/callback</text>
<text class="dg-code" x="340" y="275">GET /spotify/listening · GET /spotify/recent · GET /ws · GET /</text>
<!-- Lane 2: protected -->
<text class="dg-group-label" x="100" y="316">PROTECTED GROUP · r.Group("/", AuthMiddlewear)</text>
<rect class="dg-box dg-box--pink" x="100" y="330" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm dg-title--pink" x="195" y="354" text-anchor="middle">AUTHMIDDLEWEAR</text>
<text class="dg-text dg-text--pink" x="195" y="374" text-anchor="middle">bad token → 401</text>
<path class="dg-edge" d="M290,360 H536" />
<text class="dg-edge-label" x="415" y="352" text-anchor="middle">no admin check</text>
<rect class="dg-box" x="540" y="325" width="390" height="70" rx="4" />
<text class="dg-title dg-title--sm" x="560" y="346">HANDLER</text>
<text class="dg-code" x="560" y="366">POST /uploads</text>
<text class="dg-small" x="560" y="384">private=true checks the admin claim itself (requestIsAdmin)</text>
<!-- Lane 3: admin -->
<text class="dg-group-label" x="100" y="426">ADMIN GROUP · AuthMiddlewear, AdminMiddleware</text>
<rect class="dg-box dg-box--pink" x="100" y="450" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm dg-title--pink" x="195" y="474" text-anchor="middle">AUTHMIDDLEWEAR</text>
<text class="dg-text dg-text--pink" x="195" y="494" text-anchor="middle">bad token → 401</text>
<path class="dg-edge" d="M290,480 H316" />
<rect class="dg-box dg-box--pink" x="320" y="450" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm dg-title--pink" x="415" y="474" text-anchor="middle">ADMINMIDDLEWARE</text>
<text class="dg-text dg-text--pink" x="415" y="494" text-anchor="middle">admin ≠ true → 403</text>
<path class="dg-edge" d="M510,480 H536" />
<rect class="dg-box" x="540" y="435" width="390" height="90" rx="4" />
<text class="dg-title dg-title--sm" x="560" y="456">HANDLER</text>
<text class="dg-code" x="560" y="477">POST /rowing · GET /spotify/auth · GET /notes/*path</text>
<text class="dg-code" x="560" y="496">POST /radio/upload · GET /radio/songs</text>
<text class="dg-code" x="560" y="515">DELETE /radio/songs/:f · PATCH …/disable|enable</text>
<!-- Lane 4: GraphQL -->
<text class="dg-group-label" x="100" y="556">POST /graphql · NO GUARDING MIDDLEWARE</text>
<rect class="dg-box dg-box--tint" x="100" y="570" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm" x="195" y="594" text-anchor="middle">AUTHCONTEXTMIDDLEWARE</text>
<text class="dg-small" x="195" y="614" text-anchor="middle">never rejects; adds claims</text>
<path class="dg-edge dg-edge--flow" d="M290,600 H316" />
<rect class="dg-box" x="320" y="570" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm" x="415" y="594" text-anchor="middle">GQLGEN SERVER</text>
<text class="dg-small" x="415" y="614" text-anchor="middle">complexity ≤ 200 · LRU 1000</text>
<path class="dg-edge dg-edge--flow" d="M510,600 H536" />
<rect class="dg-box dg-box--pink" x="540" y="570" width="170" height="60" rx="4" />
<text class="dg-title dg-title--sm dg-title--pink" x="625" y="594" text-anchor="middle">DIRECTIVE</text>
<text class="dg-code" x="625" y="614" text-anchor="middle">@admin @signedIn</text>
<path class="dg-edge dg-edge--flow" d="M710,600 H736" />
<rect class="dg-box" x="740" y="570" width="190" height="60" rx="4" />
<text class="dg-title dg-title--sm" x="835" y="594" text-anchor="middle">RESOLVER</text>
<text class="dg-code" x="835" y="614" text-anchor="middle">graph/*.resolvers.go</text>
<!-- Store -->
<rect class="dg-box dg-box--teal dg-box--deep" x="960" y="195" width="120" height="435" rx="4" />
<text class="dg-title" x="1020" y="225" text-anchor="middle">STORE</text>
<text class="dg-code" x="1020" y="245" text-anchor="middle">handlers.Store</text>
<line class="dg-rule" x1="972" y1="258" x2="1068" y2="258" />
<text class="dg-small" x="1020" y="280" text-anchor="middle">DB *gorm.DB</text>
<text class="dg-small" x="1020" y="298" text-anchor="middle">Auth · Notes</text>
<text class="dg-small" x="1020" y="316" text-anchor="middle">Uploads</text>
<text class="dg-small" x="1020" y="334" text-anchor="middle">LoginLimiter</text>
<text class="dg-small" x="1020" y="352" text-anchor="middle">SpotifyClient</text>
<text class="dg-small" x="1020" y="370" text-anchor="middle">PythonURL</text>
<text class="dg-small" x="1020" y="388" text-anchor="middle">TTL caches</text>
<text class="dg-small" x="1020" y="406" text-anchor="middle">(cacheMu)</text>
<path class="dg-edge" d="M930,240 H956" />
<path class="dg-edge" d="M930,360 H956" />
<path class="dg-edge" d="M930,480 H956" />
<path class="dg-edge dg-edge--flow" d="M930,600 H956" />
<circle class="dg-badge" cx="100" cy="210" r="10" />
<text class="dg-badge-text" x="100" y="210">1</text>
<circle class="dg-badge" cx="100" cy="330" r="10" />
<text class="dg-badge-text" x="100" y="330">2</text>
<circle class="dg-badge" cx="100" cy="450" r="10" />
<text class="dg-badge-text" x="100" y="450">3</text>
<circle class="dg-badge" cx="100" cy="570" r="10" />
<text class="dg-badge-text" x="100" y="570">4</text>
</svg>
<template #caption>
nginx strips <code>/api</code>, so the backend's routes are written from <code>/</code>.
Gin matches the route first, then runs its chain, which always begins with
<code>TrafficLogFormatter</code> and <code>Recovery</code>. After that there are four kinds of chain:
open routes ① that check cookies themselves if they need to, the <code>protected</code> group ②,
the <code>admin</code> group ③ (whose <code>AdminMiddleware</code> reads the claims
<code>AuthMiddlewear</code> stored, so the order matters), and GraphQL ④ (the animated path),
which has no guard in front of it at all: each field's directive decides. Pink marks the auth
checks. <code>SetTrustedProxies</code> pins the Docker network so <code>ClientIP()</code>, which
the login rate limiter keys on, can't be spoofed with <code>X-Forwarded-For</code>.
</template>
</DiagramFigure>
</template>
<script setup>
import DiagramFigure from "../../DiagramFigure.vue";
</script>
@@ -0,0 +1,130 @@
<!--
How nginx/entrypoint.sh picks one of three configs at container start, then
waits for the Vue build, starts the certificate watcher and execs nginx.
Reflects nginx/entrypoint.sh, nginx/Dockerfile and the DEV_MODE switch in
docker-compose.dev.yml. Re-check when the entrypoint's branches change.
-->
<template>
<DiagramFigure id="edge-entrypoint-flow" title="Container start: which nginx.conf gets written" :min-width="770">
<svg class="dg" viewBox="0 0 1100 960" role="img" aria-labelledby="edge-entrypoint-flow-t">
<title id="edge-entrypoint-flow-t">Flowchart of nginx/entrypoint.sh choosing the dev, production or setup config</title>
<!-- start -->
<rect class="dg-box dg-box--solid" x="390" y="16" width="320" height="40" rx="20" />
<text class="dg-title dg-text--ink" x="550" y="42" text-anchor="middle" style="fill: var(--color-surface-deep)">/ENTRYPOINT.SH STARTS</text>
<path class="dg-edge" d="M550,56 V76" />
<!-- 1: routes partial -->
<rect class="dg-box dg-box--tint" x="250" y="80" width="600" height="58" rx="4" />
<text class="dg-code" x="550" y="104" text-anchor="middle">envsubst "$ENVSUBST_VARS" &lt; nginx_routes.conf.template &gt; /etc/nginx/nginx_routes.conf</text>
<text class="dg-small" x="550" y="124" text-anchor="middle">done once, before the choice: dev and production include it, and the watcher's nginx -t needs it later</text>
<circle class="dg-badge" cx="250" cy="80" r="10" />
<text class="dg-badge-text" x="250" y="80">1</text>
<path class="dg-edge" d="M550,138 V156" />
<!-- diamond 1: DEV_MODE -->
<path class="dg-box" d="M550,160 L650,200 L550,240 L450,200 Z" />
<text class="dg-code" x="550" y="197" text-anchor="middle">DEV_MODE</text>
<text class="dg-code" x="550" y="212" text-anchor="middle">= "true"?</text>
<circle class="dg-badge" cx="450" cy="200" r="10" />
<text class="dg-badge-text" x="450" y="200">2</text>
<path class="dg-edge" d="M440,200 H190 V366" />
<text class="dg-edge-label dg-edge-label--mint" x="300" y="192" text-anchor="middle">yes</text>
<path class="dg-edge" d="M550,240 V266" />
<text class="dg-edge-label dg-edge-label--mint" x="566" y="257">no</text>
<!-- diamond 2: cert present -->
<path class="dg-box" d="M550,270 L680,312 L550,354 L420,312 Z" />
<text class="dg-code" x="550" y="308" text-anchor="middle">fullchain.pem + privkey.pem</text>
<text class="dg-code" x="550" y="323" text-anchor="middle">in live/$DOMAIN/ ?</text>
<path class="dg-edge" d="M550,354 V366" />
<text class="dg-edge-label dg-edge-label--mint" x="566" y="364">yes</text>
<path class="dg-edge" d="M680,312 H910 V366" />
<text class="dg-edge-label dg-edge-label--mint" x="795" y="304" text-anchor="middle">no</text>
<!-- three configs -->
<rect class="dg-box dg-box--muted" x="30" y="370" width="320" height="160" rx="4" />
<text class="dg-title" x="46" y="396">DEV · NGINX_DEV.CONF.TEMPLATE</text>
<text class="dg-small" x="46" y="416">self-signed cert, minted once, kept in certbot/conf</text>
<text class="dg-code" x="46" y="438">openssl req -x509 … -subj /CN=localhost</text>
<text class="dg-code" x="46" y="458">envsubst → nginx_dev_common.conf</text>
<text class="dg-code" x="46" y="476">envsubst → nginx.conf</text>
<text class="dg-small" x="46" y="496">:80 and :443 both serve; / → vue:5173</text>
<text class="dg-code" x="46" y="518" style="fill: var(--color-primary)">CONFIG_MODE=dev</text>
<rect class="dg-box" x="390" y="370" width="320" height="160" rx="4" />
<text class="dg-title" x="406" y="396">PRODUCTION · NGINX.CONF.TEMPLATE</text>
<text class="dg-small" x="406" y="416">steady state: the Let's Encrypt cert is on disk</text>
<text class="dg-code" x="406" y="438">envsubst "$ENVSUBST_VARS"</text>
<text class="dg-code" x="406" y="456"> &lt; nginx.conf.template &gt; nginx.conf</text>
<text class="dg-small" x="406" y="478">:80 → 301 https · apex → www · TLS on :443</text>
<text class="dg-small" x="406" y="496">includes nginx_routes.conf</text>
<text class="dg-code" x="406" y="518" style="fill: var(--color-primary)">CONFIG_MODE=prod</text>
<rect class="dg-box dg-box--pink" x="750" y="370" width="320" height="160" rx="4" />
<text class="dg-title dg-title--pink" x="766" y="396">SETUP · NGINX_SETUP.CONF.TEMPLATE</text>
<text class="dg-small" x="766" y="416">first boot on a new host: no certificate yet</text>
<text class="dg-code" x="766" y="438">envsubst '${DOMAIN}'</text>
<text class="dg-code" x="766" y="456"> &lt; nginx_setup.conf.template</text>
<text class="dg-small" x="766" y="478">:80 only: ACME webroot, /nginx-health, 404</text>
<text class="dg-small" x="766" y="496">no TLS, no upstreams: nothing can fail to load</text>
<text class="dg-code" x="766" y="518" style="fill: var(--color-primary)">CONFIG_MODE=setup</text>
<!-- merge -->
<path class="dg-edge dg-edge--plain" d="M190,530 V556 H910 V530" />
<path class="dg-edge" d="M550,530 V576" />
<rect class="dg-box" x="370" y="580" width="360" height="44" rx="4" />
<text class="dg-code" x="550" y="600" text-anchor="middle">chmod 755 /uploads</text>
<text class="dg-small" x="550" y="616" text-anchor="middle">workers must traverse the volume the backend created</text>
<path class="dg-edge" d="M550,624 V646" />
<!-- diamond 3 -->
<path class="dg-box" d="M550,650 L640,684 L550,718 L460,684 Z" />
<text class="dg-code" x="550" y="681" text-anchor="middle">DEV_MODE</text>
<text class="dg-code" x="550" y="696" text-anchor="middle">= "true"?</text>
<path class="dg-edge" d="M550,718 V746" />
<text class="dg-edge-label dg-edge-label--mint" x="566" y="738">no</text>
<path class="dg-edge dg-edge--muted dg-edge--dashed" d="M640,684 H960 V922 H734" />
<text class="dg-edge-label" x="800" y="676" text-anchor="middle">yes: Vite serves /, no watcher</text>
<rect class="dg-box" x="370" y="750" width="360" height="52" rx="4" />
<text class="dg-text" x="550" y="771" text-anchor="middle">wait up to 120 s for /etc/nginx/html/index.html</text>
<text class="dg-small" x="550" y="790" text-anchor="middle">vue_dist is filled by the one-shot vue build; then start anyway</text>
<path class="dg-edge" d="M550,802 V822" />
<rect class="dg-box" x="370" y="826" width="360" height="52" rx="4" />
<text class="dg-code" x="550" y="847" text-anchor="middle">cert_watcher &amp;</text>
<text class="dg-small" x="550" y="866" text-anchor="middle">background loop, every $CERT_WATCH_INTERVAL (60 s)</text>
<circle class="dg-badge" cx="370" cy="826" r="10" />
<text class="dg-badge-text" x="370" y="826">3</text>
<path class="dg-edge" d="M550,878 V898" />
<rect class="dg-box dg-box--solid" x="370" y="902" width="360" height="40" rx="20" />
<text class="dg-code" x="550" y="927" text-anchor="middle" style="fill: var(--color-surface-deep)">exec: nginx -g 'daemon off;' (PID 1)</text>
</svg>
<template #caption>
No <code>nginx.conf</code> is baked into the image; three templates are,
and the entrypoint writes exactly one of them on every start. Step
<strong>1</strong> renders the shared route table first, whatever happens
next. At <strong>2</strong>, <code>DEV_MODE</code> (set only by
<code>docker-compose.dev.yml</code>) wins outright; otherwise the presence
of a certificate decides, because the production config's
<code>ssl_certificate</code> lines would stop nginx from starting without
one. The <code>envsubst</code> allow-list is what keeps nginx's own
<code>$host</code> and <code>$remote_addr</code> intact: only the named
<code>${DOMAIN} ${BACKEND_HOST} …</code> variables are replaced. The
watcher at <strong>3</strong> moves a setup-mode nginx onto the
production config once certbot's first certificate lands (render to a
temp file, <code>nginx -t</code>, install, <code>nginx -s reload</code>),
and reloads after a renewal when certbot's <code>--deploy-hook</code>
touches <code>/etc/letsencrypt/.nginx-reload</code>. Grey dashed = local
dev only.
</template>
</DiagramFigure>
</template>
<script setup>
import DiagramFigure from "../../DiagramFigure.vue";
</script>
@@ -0,0 +1,229 @@
<!--
The whole production route table of the www server block: every location
nginx matches, what it does to the request, and the container:port it lands
on. Reflects nginx/nginx_routes.conf.template (shared routes),
nginx/nginx.conf.template (/api/graphql, /uploads/, static blocks, apex /v2/)
and the ports in docker-compose.yml / .env.example. Redraw when a location
is added, gated or moved.
-->
<template>
<DiagramFigure id="edge-route-map" title="Every route nginx serves, and where it goes" :min-width="770">
<svg class="dg" viewBox="0 0 1100 1086" role="img" aria-labelledby="edge-route-map-t">
<title id="edge-route-map-t">Table of nginx locations, grouped by the upstream container each one proxies to, coloured by public, admin-gated, 404 and disk-served</title>
<text class="dg-title dg-title--sm" x="36" y="46">LOCATION (MATCH TYPE)</text>
<text class="dg-title dg-title--sm" x="390" y="46">WHAT NGINX DOES ON THE WAY</text>
<text class="dg-title dg-title--sm" x="812" y="46">UPSTREAM CONTAINER:PORT</text>
<line class="dg-rule" x1="16" y1="58" x2="1084" y2="58" />
<rect class="dg-band" x="16" y="70" width="1068" height="140" opacity="0.18" />
<rect class="dg-box" x="800" y="73" width="280" height="134" rx="3" />
<text class="dg-code" x="812" y="144" style="fill: var(--color-primary)">backend:8080</text>
<text class="dg-small" x="1070" y="144" text-anchor="end">Go API</text>
<circle class="dg-dot" cx="24" cy="85" r="4" />
<text class="dg-code" x="36" y="89" style="fill: var(--color-secondary)">/api/ws</text>
<text class="dg-small" x="390" y="89">strip /api · Upgrade · no rate limit</text>
<path class="dg-edge" d="M712,85 H796" />
<circle class="dg-dot" cx="24" cy="107" r="4" />
<text class="dg-code" x="36" y="111" style="fill: var(--color-secondary)">/api/auth/login</text>
<text class="dg-small" x="390" y="111">strip /api · zone login</text>
<path class="dg-edge" d="M712,107 H796" />
<circle class="dg-dot" cx="24" cy="129" r="4" />
<text class="dg-code" x="36" y="133" style="fill: var(--color-secondary)">/api/uploads</text>
<text class="dg-small" x="390" y="133">strip /api · zone upload</text>
<path class="dg-edge" d="M712,129 H796" />
<circle class="dg-dot" cx="24" cy="151" r="4" />
<text class="dg-code" x="36" y="155" style="fill: var(--color-secondary)">/api/graphql</text>
<text class="dg-small" x="390" y="155">strip /api · zone graphql · production only</text>
<path class="dg-edge" d="M712,151 H796" />
<circle class="dg-dot" cx="24" cy="173" r="4" />
<text class="dg-code" x="36" y="177" style="fill: var(--color-secondary)">/api/</text>
<text class="dg-small" x="390" y="177">strip /api · zone api</text>
<path class="dg-edge" d="M712,173 H796" />
<circle class="dg-dot dg-dot--pink" cx="24" cy="195" r="4" />
<text class="dg-code" x="36" y="199" style="fill: var(--color-secondary)">= /internal/auth/admin-validate</text>
<text class="dg-small" x="390" y="199">internal; rewritten to /auth/validate-admin</text>
<path class="dg-edge dg-edge--pink dg-edge--dashed" d="M712,195 H796" />
<rect class="dg-box" x="800" y="223" width="280" height="46" rx="3" />
<text class="dg-code" x="812" y="250" style="fill: var(--color-primary)">icecast2:8000</text>
<text class="dg-small" x="1070" y="250" text-anchor="end">radio stream</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="235" r="4" />
<text class="dg-code" x="36" y="239" style="fill: var(--color-secondary)">/radio/admin/</text>
<text class="dg-small" x="390" y="239">strip /radio · auth_request</text>
<path class="dg-edge dg-edge--pink" d="M712,235 H796" />
<circle class="dg-dot" cx="24" cy="257" r="4" />
<text class="dg-code" x="36" y="261" style="fill: var(--color-secondary)">/radio/</text>
<text class="dg-small" x="390" y="261">strip /radio</text>
<path class="dg-edge" d="M712,257 H796" />
<rect class="dg-band" x="16" y="282" width="1068" height="74" opacity="0.18" />
<rect class="dg-box" x="800" y="285" width="280" height="68" rx="3" />
<text class="dg-code" x="812" y="323" style="fill: var(--color-primary)">gitea:3000</text>
<text class="dg-small" x="1070" y="323" text-anchor="end">git server</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="297" r="4" />
<text class="dg-code" x="36" y="301" style="fill: var(--color-secondary)">~ /gitea/&lt;o&gt;/&lt;r&gt;/(…commit/|archive/|compare/)</text>
<text class="dg-small" x="390" y="301">strip /gitea · auth_request</text>
<path class="dg-edge dg-edge--pink" d="M712,297 H796" />
<circle class="dg-dot" cx="24" cy="319" r="4" />
<text class="dg-code" x="36" y="323" style="fill: var(--color-secondary)">/gitea/</text>
<text class="dg-small" x="390" y="323">strip /gitea</text>
<path class="dg-edge" d="M712,319 H796" />
<circle class="dg-dot" cx="24" cy="341" r="4" />
<text class="dg-code" x="36" y="345" style="fill: var(--color-secondary)">/v2/ (apex server block only)</text>
<text class="dg-small" x="390" y="345">registry · no body limit · 900s</text>
<path class="dg-edge" d="M712,341 H796" />
<rect class="dg-box" x="800" y="369" width="280" height="90" rx="3" />
<text class="dg-code" x="812" y="418" style="fill: var(--color-primary)">silverbullet-public:3000</text>
<text class="dg-small" x="1070" y="418" text-anchor="end">public notes</text>
<circle class="dg-dot" cx="24" cy="381" r="4" />
<text class="dg-code" x="36" y="385" style="fill: var(--color-secondary)">/notes/</text>
<text class="dg-small" x="390" y="385">prefix kept · Upgrade</text>
<path class="dg-edge" d="M712,381 H796" />
<circle class="dg-dot dg-dot--muted" cx="24" cy="403" r="4" />
<text class="dg-code" x="36" y="407" style="fill: var(--color-secondary)">~* /notes/…/(private|templates)/</text>
<text class="dg-small" x="390" y="407">privacy boundary</text>
<path class="dg-edge dg-edge--muted dg-edge--dashed" d="M712,403 H742" />
<text class="dg-text dg-text--muted" x="750" y="407">404</text>
<circle class="dg-dot dg-dot--muted" cx="24" cy="425" r="4" />
<text class="dg-code" x="36" y="429" style="fill: var(--color-secondary)">~ /notes/&lt;x&gt;/.&lt;dot-segment&gt;</text>
<text class="dg-small" x="390" y="429">hides .git, .obsidian …</text>
<path class="dg-edge dg-edge--muted dg-edge--dashed" d="M712,425 H742" />
<text class="dg-text dg-text--muted" x="750" y="429">404</text>
<circle class="dg-dot dg-dot--muted" cx="24" cy="447" r="4" />
<text class="dg-code" x="36" y="451" style="fill: var(--color-secondary)">^~ /notes/.revisions</text>
<text class="dg-small" x="390" y="451">full history incl. private/</text>
<path class="dg-edge dg-edge--muted dg-edge--dashed" d="M712,447 H742" />
<text class="dg-text dg-text--muted" x="750" y="451">404</text>
<rect class="dg-band" x="16" y="472" width="1068" height="30" opacity="0.18" />
<rect class="dg-box" x="800" y="475" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="491" style="fill: var(--color-primary)">silverbullet:3000</text>
<text class="dg-small" x="1070" y="491" text-anchor="end">notes editor</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="487" r="4" />
<text class="dg-code" x="36" y="491" style="fill: var(--color-secondary)">/sb/</text>
<text class="dg-small" x="390" y="491">prefix kept · Upgrade · auth_request</text>
<path class="dg-edge dg-edge--pink" d="M712,487 H796" />
<rect class="dg-box" x="800" y="515" width="280" height="68" rx="3" />
<text class="dg-code" x="812" y="553" style="fill: var(--color-primary)">python:8000</text>
<text class="dg-small" x="1070" y="553" text-anchor="end">FastAPI</text>
<circle class="dg-dot" cx="24" cy="527" r="4" />
<text class="dg-code" x="36" y="531" style="fill: var(--color-secondary)">~ ^/py/hotels/(search|scan)</text>
<text class="dg-small" x="390" y="531">strip /py · zone hotel_search · unbuffered</text>
<path class="dg-edge" d="M712,527 H796" />
<circle class="dg-dot" cx="24" cy="549" r="4" />
<text class="dg-code" x="36" y="553" style="fill: var(--color-secondary)">/py/</text>
<text class="dg-small" x="390" y="553">strip /py · zone api</text>
<path class="dg-edge" d="M712,549 H796" />
<circle class="dg-dot dg-dot--muted" cx="24" cy="571" r="4" />
<text class="dg-code" x="36" y="575" style="fill: var(--color-secondary)">^~ /py/internal/</text>
<text class="dg-small" x="390" y="575">Go calls it directly instead</text>
<path class="dg-edge dg-edge--muted dg-edge--dashed" d="M712,571 H742" />
<text class="dg-text dg-text--muted" x="750" y="575">404</text>
<rect class="dg-band" x="16" y="596" width="1068" height="74" opacity="0.18" />
<rect class="dg-box" x="800" y="599" width="280" height="68" rx="3" />
<text class="dg-code" x="812" y="637" style="fill: var(--color-primary)">jobs:8080</text>
<text class="dg-small" x="1070" y="637" text-anchor="end">job tracker</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="611" r="4" />
<text class="dg-code" x="36" y="615" style="fill: var(--color-secondary)">^~ /jobs/</text>
<text class="dg-small" x="390" y="615">prefix kept · zone api · auth_request</text>
<path class="dg-edge dg-edge--pink" d="M712,611 H796" />
<circle class="dg-dot" cx="24" cy="633" r="4" />
<text class="dg-code" x="36" y="637" style="fill: var(--color-secondary)">^~ /jobs/api/capture</text>
<text class="dg-small" x="390" y="637">zone api · bearer token checked by app</text>
<path class="dg-edge" d="M712,633 H796" />
<circle class="dg-dot" cx="24" cy="655" r="4" />
<text class="dg-code" x="36" y="659" style="fill: var(--color-secondary)">= /jobs/job-capture.user.js</text>
<text class="dg-small" x="390" y="659">userscript update URL</text>
<path class="dg-edge" d="M712,655 H796" />
<rect class="dg-box" x="800" y="683" width="280" height="68" rx="3" />
<text class="dg-code" x="812" y="721" style="fill: var(--color-primary)">activity-tracker:8080</text>
<text class="dg-small" x="1070" y="721" text-anchor="end">activity tracker</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="695" r="4" />
<text class="dg-code" x="36" y="699" style="fill: var(--color-secondary)">^~ /tracker/</text>
<text class="dg-small" x="390" y="699">strip /tracker · zone api · auth_request</text>
<path class="dg-edge dg-edge--pink" d="M712,695 H796" />
<circle class="dg-dot" cx="24" cy="717" r="4" />
<text class="dg-code" x="36" y="721" style="fill: var(--color-secondary)">^~ /tracker/api/v1/</text>
<text class="dg-small" x="390" y="721">strip /tracker · device keys checked by app</text>
<path class="dg-edge" d="M712,717 H796" />
<circle class="dg-dot" cx="24" cy="739" r="4" />
<text class="dg-code" x="36" y="743" style="fill: var(--color-secondary)">= /tracker/tracker.user.js</text>
<text class="dg-small" x="390" y="743">strip /tracker</text>
<path class="dg-edge" d="M712,739 H796" />
<rect class="dg-band" x="16" y="764" width="1068" height="30" opacity="0.18" />
<rect class="dg-box" x="800" y="767" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="783" style="fill: var(--color-primary)">usaco:8080</text>
<text class="dg-small" x="1070" y="783" text-anchor="end">USACO log</text>
<circle class="dg-dot" cx="24" cy="779" r="4" />
<text class="dg-code" x="36" y="783" style="fill: var(--color-secondary)">^~ /usaco/</text>
<text class="dg-small" x="390" y="783">prefix kept · zone api · 120s</text>
<path class="dg-edge" d="M712,779 H796" />
<rect class="dg-box" x="800" y="807" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="823" style="fill: var(--color-primary)">dozzle:8080</text>
<text class="dg-small" x="1070" y="823" text-anchor="end">log viewer</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="819" r="4" />
<text class="dg-code" x="36" y="823" style="fill: var(--color-secondary)">/dozzle/</text>
<text class="dg-small" x="390" y="823">prefix kept · SSE unbuffered · 1h</text>
<path class="dg-edge dg-edge--pink" d="M712,819 H796" />
<rect class="dg-band" x="16" y="844" width="1068" height="30" opacity="0.18" />
<rect class="dg-box" x="800" y="847" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="863" style="fill: var(--color-primary)">garage-webui:3909</text>
<text class="dg-small" x="1070" y="863" text-anchor="end">bucket admin</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="859" r="4" />
<text class="dg-code" x="36" y="863" style="fill: var(--color-secondary)">/garage/</text>
<text class="dg-small" x="390" y="863">prefix kept · body up to 2G · unbuffered</text>
<path class="dg-edge dg-edge--pink" d="M712,859 H796" />
<rect class="dg-box" x="800" y="887" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="903" style="fill: var(--color-primary)">garage:3902</text>
<text class="dg-small" x="1070" y="903" text-anchor="end">S3 website endpoint</text>
<circle class="dg-dot" cx="24" cy="899" r="4" />
<text class="dg-code" x="36" y="903" style="fill: var(--color-secondary)">/uploads/</text>
<text class="dg-small" x="390" y="903">strip · Host uploads.web.garage · 2s connect</text>
<path class="dg-edge" d="M712,899 H796" />
<rect class="dg-band" x="16" y="924" width="1068" height="52" opacity="0.18" />
<rect class="dg-box dg-box--green" x="800" y="927" width="280" height="46" rx="3" />
<text class="dg-code" x="812" y="954" style="fill: var(--color-primary)">uploads volume</text>
<text class="dg-small" x="1070" y="954" text-anchor="end">/uploads on disk</text>
<circle class="dg-dot dg-dot--green" cx="24" cy="939" r="4" />
<text class="dg-code" x="36" y="943" style="fill: var(--color-secondary)">@uploads_disk</text>
<text class="dg-small" x="390" y="943">named location · Garage 404/5xx lands here</text>
<path class="dg-edge dg-edge--green" d="M712,939 H796" />
<circle class="dg-dot dg-dot--pink" cx="24" cy="961" r="4" />
<text class="dg-code" x="36" y="965" style="fill: var(--color-secondary)">/uploads/private/</text>
<text class="dg-small" x="390" y="965">alias /uploads/private/ · auth_request</text>
<path class="dg-edge dg-edge--pink" d="M712,961 H796" />
<rect class="dg-box dg-box--green" x="800" y="989" width="280" height="46" rx="3" />
<text class="dg-code" x="812" y="1016" style="fill: var(--color-primary)">vue_dist volume</text>
<text class="dg-small" x="1070" y="1016" text-anchor="end">/etc/nginx/html</text>
<circle class="dg-dot dg-dot--green" cx="24" cy="1001" r="4" />
<text class="dg-code" x="36" y="1005" style="fill: var(--color-secondary)">/</text>
<text class="dg-small" x="390" y="1005">try_files $uri $uri/ /index.html</text>
<path class="dg-edge dg-edge--green" d="M712,1001 H796" />
<circle class="dg-dot dg-dot--green" cx="24" cy="1023" r="4" />
<text class="dg-code" x="36" y="1027" style="fill: var(--color-secondary)">/assets/ /fonts/ /img/ /sound/</text>
<text class="dg-small" x="390" y="1027">expires 1y / 30d / 7d / 7d</text>
<path class="dg-edge dg-edge--green" d="M712,1023 H796" />
<circle class="dg-dot" cx="24" cy="1066" r="5" />
<text class="dg-small" x="36" y="1070">public, proxied</text>
<circle class="dg-dot dg-dot--pink" cx="169.0" cy="1066" r="5" />
<text class="dg-small" x="181.0" y="1070">admin-gated (auth_request)</text>
<circle class="dg-dot dg-dot--muted" cx="382.20000000000005" cy="1066" r="5" />
<text class="dg-small" x="394.20000000000005" y="1070">answered 404 by nginx</text>
<circle class="dg-dot dg-dot--green" cx="564.4000000000001" cy="1066" r="5" />
<text class="dg-small" x="576.4000000000001" y="1070">served by nginx from a volume</text>
</svg>
<template #caption>
Read it right to left: each box is one container on <code>app-network</code>
(or a volume nginx reads itself), and the rows beside it are the
locations that reach it. Pink rows run the admin gate first; grey rows
never leave nginx. Upstreams are written as <code>set $upstream_* …</code>
variables, so nginx resolves container names per request through Docker's
DNS (<code>resolver 127.0.0.11 valid=10s</code>) and still boots when one of
them is down. Every proxied row also gets the bare-prefix twin
(<code>/gitea</code> → 301 <code>/gitea/</code>) that is left out here; in
dev, <code>/</code> goes to <code>vue:5173</code> instead of
<code>vue_dist</code>, and <code>/api/graphql</code> falls into
<code>/api/</code>.
</template>
</DiagramFigure>
</template>
<script setup>
import DiagramFigure from "../../DiagramFigure.vue";
</script>
@@ -0,0 +1,106 @@
<!--
Sequence of a cold load of "/": index.html → main.js → router + Pinia →
Landing → BoxCanvas, and the three GraphQL requests the canvas fires
(me, boxes, background), with the home query only when a widget asks.
Reflects: vue/index.html, src/main.js, router/index.js,
views/landing/Landing.vue, views/home3/BoxCanvas.vue, stores/auth.js,
stores/boxes.js, stores/background.js, stores/homeData.js, graphql.js.
-->
<template>
<DiagramFigure id="frontend-boot-sequence" title="Cold load of the landing page" :min-width="770">
<svg class="dg" viewBox="0 0 1100 800" role="img" aria-labelledby="frontend-boot-sequence-t">
<title id="frontend-boot-sequence-t">
Sequence diagram: index.html loads main.js, which installs the router and Pinia and mounts the
app; the router passes the landing route, Landing loads BoxCanvas, which asks the auth, boxes and
background stores for data over three GraphQL requests
</title>
<!-- Lifelines -->
<g v-for="l in lanes" :key="l.label">
<line class="dg-lifeline" :x1="l.x" y1="66" :x2="l.x" y2="780" />
<rect class="dg-box" :class="l.cls" :x="l.x - l.w / 2" y="18" :width="l.w" height="48" rx="4" />
<text class="dg-title dg-title--sm" :class="l.titleCls" :x="l.x" y="38" text-anchor="middle">{{ l.label }}</text>
<text class="dg-code" :x="l.x" y="56" text-anchor="middle">{{ l.sub }}</text>
</g>
<!-- Activations -->
<rect class="dg-activation" x="265" y="132" width="10" height="140" />
<rect class="dg-activation" x="435" y="172" width="10" height="150" />
<rect class="dg-activation" x="615" y="332" width="10" height="400" />
<rect class="dg-activation" x="795" y="412" width="10" height="330" />
<rect class="dg-activation" x="985" y="442" width="10" height="200" />
<!-- Messages -->
<g v-for="(m, i) in messages" :key="i">
<template v-if="m.self">
<path
class="dg-edge" :class="m.cls"
:d="`M${m.from + 5},${m.y - 8} H${m.from + 34} V${m.y + 6} H${m.from + 9}`"
/>
<text class="dg-edge-label" :class="m.labelCls" :x="m.from + 40" :y="m.y + 2">{{ m.label }}</text>
</template>
<template v-else>
<path
class="dg-edge" :class="m.cls"
:d="`M${m.from + (m.to > m.from ? 5 : -5)},${m.y} H${m.to + (m.to > m.from ? -9 : 9)}`"
/>
<text class="dg-edge-label" :class="m.labelCls" :x="(m.from + m.to) / 2" :y="m.y - 6" text-anchor="middle">{{ m.label }}</text>
</template>
<circle class="dg-badge" cx="26" :cy="m.y" r="10" />
<text class="dg-badge-text" x="26" :y="m.y">{{ i + 1 }}</text>
</g>
<!-- Notes -->
<rect class="dg-band" x="40" y="298" width="1050" height="24" />
<text class="dg-small" x="460" y="314">blank until here: RouterView renders nothing while the initial navigation is pending</text>
<rect class="dg-band dg-band--pink" x="40" y="688" width="1050" height="84" />
<text class="dg-small" x="830" y="768">only if a widget box mounts</text>
</svg>
<template #caption>
<code>main.js</code> installs the router (3) <em>before</em> Pinia (4), and the router's install
starts the first navigation at once. That works only because navigation guards run in a promise
chain, so by the time <code>beforeEach</code> calls <code>useAuthStore()</code> (6) Pinia is active.
On <code>/</code> the guard has nothing to wait for. The canvas then fires three independent
GraphQL POSTs (9–14). It asks for <code>me</code> on its own rather than through the home query,
so the landing page never fans out to Spotify, Steam and Gitea just to decide whether to show an
Edit button. The nine-field <code>HomeData</code> query (pink band, 17–18) is sent only as a side
effect of the first <code>useHomeDataStore()</code> call, which happens when a widget box mounts.
</template>
</DiagramFigure>
</template>
<script setup>
import DiagramFigure from "../../DiagramFigure.vue";
const X = { html: 110, main: 270, router: 440, view: 620, stores: 800, gql: 990 };
const lanes = [
{ x: X.html, w: 130, label: "INDEX.HTML", sub: "<body id=app>", cls: "dg-box--pink", titleCls: "dg-title--pink" },
{ x: X.main, w: 130, label: "MAIN.JS", sub: "createApp" },
{ x: X.router, w: 140, label: "ROUTER", sub: "router/index.js" },
{ x: X.view, w: 170, label: "LANDING → CANVAS", sub: "BoxCanvas.vue" },
{ x: X.stores, w: 160, label: "PINIA STORES", sub: "auth · boxes · bg" },
{ x: X.gql, w: 180, label: "GQL()", sub: "POST /api/graphql" },
];
const messages = [
{ from: X.html, to: X.main, y: 100, label: "loads /src/main.js" },
{ from: X.main, y: 132, self: true, label: "createApp(App)" },
{ from: X.main, to: X.router, y: 172, label: "app.use(router)" },
{ from: X.main, to: X.stores, y: 210, label: "app.use(createPinia())" },
{ from: X.main, to: X.html, y: 250, label: "mount('#app')", cls: "dg-edge--pink", labelCls: "dg-edge-label--pink" },
{ from: X.router, y: 282, self: true, label: "beforeEach: no requiresAdmin → pass" },
{ from: X.router, to: X.view, y: 340, label: "render Landing" },
{ from: X.view, y: 372, self: true, label: "import() BoxCanvas" },
{ from: X.view, to: X.stores, y: 420, label: "auth.ensureLoaded()" },
{ from: X.stores, to: X.gql, y: 450, label: "query Me { me }", cls: "dg-edge--flow" },
{ from: X.view, to: X.stores, y: 490, label: "boxes:index .fetch()" },
{ from: X.stores, to: X.gql, y: 520, label: "boxes(page: \"index\")", cls: "dg-edge--flow" },
{ from: X.view, to: X.stores, y: 560, label: "background.show(\"index\")" },
{ from: X.stores, to: X.gql, y: 590, label: "background(page)", cls: "dg-edge--flow" },
{ from: X.gql, to: X.stores, y: 630, label: "3 answers, any order", cls: "dg-edge--green dg-edge--dashed", labelCls: "" },
{ from: X.stores, to: X.view, y: 660, label: "BoxFrames render", cls: "dg-edge--green dg-edge--dashed" },
{ from: X.view, to: X.stores, y: 710, label: "useHomeDataStore()", cls: "dg-edge--pink dg-edge--dashed", labelCls: "dg-edge-label--pink" },
{ from: X.stores, to: X.gql, y: 742, label: "query HomeData", cls: "dg-edge--pink dg-edge--dashed", labelCls: "dg-edge-label--pink" },
];
</script>

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