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

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

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

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

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

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-16 16:12:21 +01:00
..
2026-04-29 09:06:41 +01:00

My Web - Frontend

Vue 3 SPA for adam-french.co.uk. Built with Vite, Tailwind CSS v4, Pinia, and Vue Router.

Setup

npm install

Development

npm run dev

The Vite dev server proxies API requests:

  • /api -> http://localhost:8080 (Go backend)
  • /gitea -> http://localhost:3000 (Gitea)
  • /radio -> http://localhost:8000 (Icecast2)
  • /py -> http://localhost:8000 (FastAPI; the /py prefix is stripped, as nginx does in production)

Structure

src/
  main.js          entry point — awaits the wasm init, then mounts <App>
  App.vue          empty shell; all chrome lives in the layouts
  router/index.js  route table + the single admin route guard
  graphql.js       the entire GraphQL client (one axios POST)
  layouts/         DefaultLayout (dark, navbar+footer) and CVLayout (light, print)
  stores/          Pinia stores
  components/      reusable UI — text/, input/, util/, borders/, elle/
  views/           page components, one directory per area
  assets/styles.css design tokens + base styles (see Styling)
  js/              small shared helpers
  wasm/            GENERATED by `npm run build:wasm`; gitignored, do not edit
  crates/stp_wasm  the Rust source for the above

Routing

Two layout shells, defined in src/router/index.js:

Path Layout Notes
/ DefaultLayout Landing page (statically imported — it's the first paint)
/stp DefaultLayout The personal home page: the widget grid
/admin, /admin/login DefaultLayout /admin is guarded by meta.requiresAdmin
/automata, /hotels, /shrines/* DefaultLayout
/cv, /cv/jobs CVLayout Light print theme; /cv/jobs is admin-only
/stp2 (none) Bare full-bleed mock, deliberately outside both layouts
:pathMatch(.*)* DefaultLayout 404

Everything except the landing page is a dynamic import(), so Vite gives each view its own chunk.

Route names are contracts used by RouterLink/router.push — renaming one breaks every link to it.

The admin guard (router.beforeEach) has one subtlety: the admin flag comes from the me field of the home-data query, which arrives asynchronously. Navigating straight to /admin on a cold load would otherwise read an empty user and bounce a real admin to the login page, so the guard first awaits homeData.loaded via a self-stopping watcher.

Data flow

There is no GraphQL cache or codegen. src/graphql.js is a single function:

const data = await gql(`query { ... }`, variables);

It POSTs to /api/graphql and throws on an error response with no data. Auth rides along in HTTP-only cookies set by the Go backend, so nothing here touches tokens — the request just has to be same-origin (nginx in production, the Vite proxy in dev).

stores/homeData.js is the hub. It issues one query for everything the /stp page needs (posts, favourites, activities, Spotify, rowing, bookmarks, Gitea feed, Steam status, current user) instead of letting a dozen widgets each fire their own request. That fetch is kicked off as a side effect of the first useHomeDataStore() call, so no component has to start it.

The other stores are thin views over it:

Store Role
homeData the one query; owns loaded / error
auth current user; mirrors homeData.me, plus login/logout mutations
posts, favorites, activity, songs, steam mirror one slice of homeData via an immediate watch, and keep a placeholder value until real data arrives
places independent CRUD; sign-in only, so it is fetched lazily
messages the chat WebSocket — not GraphQL at all
models dormant; not imported anywhere

The mirroring watches are immediate on purpose: a store created after homeData has already loaded would never see the existing value otherwise.

Component conventions

  • Layout and one-off tweaks go in Tailwind utilities; reach for a scoped <style> only for what utilities can't express (grid-template-areas, keyframes, media-query-specific layouts).
  • Never hard-code a colour — use a token. The one exception is <canvas> drawing (views/automata/MobileAutomata.vue), which cannot read CSS variables.
  • Home widgets: title goes in <Header>; admin create forms use <CreateToggle v-model="showCreate"> in the header's #action slot and render the form inside <Modal v-model="showCreate">.
  • Admin create forms are loaded with defineAsyncComponent, so a visitor who is not signed in never downloads them.
  • Create forms emit done / cancel and never close themselves — the host decides what to dismiss and refresh.
  • Animation loops (Headline, Intro2, Stamps, AutoScroll, Elle) keep their state in plain lets and write to the DOM directly. Putting per-frame state in a ref would queue a Vue re-render 30–60 times a second. They also cache measurements in a ResizeObserver rather than reading offsetWidth in the rAF callback, which forces a synchronous layout every frame.

Dev vs production

  • Dev (npm run dev): Vite serves the SPA and proxies /api, /gitea, /radio and /py (see the table above and vite.config.js). The /py proxy strips the prefix, matching what nginx does in production.
  • Production (npm run build): dist/ is built into the nginx container and served as static files, with nginx doing the same reverse-proxying.

Note npm run build runs build:wasm first, which needs wasm-pack on the PATH. If you only want the Vue bundle and src/wasm/ is already populated, npx vite build skips that step.

Live vs legacy views

Several files are kept around but not reachable. Each carries a STATUS: note in its header comment; the summary:

File Status
views/home/Home.vue live (/stp) — imports Intro2 and Gym2
views/home/Intro.vue superseded by Intro2.vue; not imported
views/home/Gym.vue superseded by Gym2.vue; not imported
views/home2/Home2.vue reachable at /stp2, but a static mock and unlinked
views/home/BadApple.vue unfinished ASCII video player; not imported
views/CV/CVProgramming.vue live — the only CV template listed in CV.vue
views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue commented out of CV.vue's list; unreachable
views/unused/CoverLetters.vue live despite the directory — it is the "Cover Letter" tab on /cv
views/unused/Notes.vue no route points at it; not imported
components/util/wasm/AutoScroll.vue Rust port of the JS AutoScroll; not imported
components/util/{MusicPlayer,ObjectTable}.vue not imported
components/elle/Elle.vue, components/borders/UtenaFrame.vue decorative; not imported
stores/models.js, js/mobile-automata.mjs not imported

Nothing in this list is dead weight the build ships — unimported files are tree-shaken out. They are kept deliberately; don't delete without asking.

Styling

Everything visual is defined in three places:

File What it holds
src/assets/styles.css Fonts, design tokens, default element styles (dark theme), reusable classes (bdr-1, bdr-2, page-a4, halftone), the slide and fade transitions, print rules
src/layouts/CVLayout.vue The light theme for /cv and /cv/jobs: re-points the colour tokens to ink-on-paper values and holds the shared .cv-btn styles
src/views/CV/cv-shared.css Typography and page layout for the CV templates (.cv-template, .cv-page, --cv-* size variables)
src/views/hotels/hotels-shared.css Panels, forms, tables and tab strip for /hotels, shared by the single-stay and cheapest-night panels; every selector is prefixed with the page's .hotels root class

Tokens

Tokens are declared once in a Tailwind @theme block, so each is available both as a utility class in templates and as a CSS variable in <style> blocks:

Token Utility Variable Role
primary text-primary border-primary var(--color-primary) mint: headings, borders, link text
secondary text-secondary var(--color-secondary) green: body text
tertiary text-tertiary var(--color-tertiary) pink: accents, small print, lists
quaternary border-quaternary var(--color-quaternary) teal: subtle borders
muted text-muted var(--color-muted) grey: secondary labels
surface bg-surface var(--color-surface) widget background
surface-deep bg-surface-deep var(--color-surface-deep) page background
surface-tint bg-surface-tint var(--color-surface-tint) halftone dots, list rows
link-bg bg-link-bg var(--color-link-bg) background behind links and buttons
heading font font-heading var(--font-heading) big_noodle_titling
body font (default) var(--font-body) CreatoDisplay

Note that Tailwind's spacing unit is set to 3px (not the default 4px), so p-1 is 3px, gap-2 is 6px, w-10 is 30px.

Conventions

  • Use Tailwind utilities for layout and one-off tweaks. Reach for a scoped <style> only for what utilities can't express: grid-template-areas, keyframe animations, media-query-specific layouts.
  • 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">.

Production Build

npm run build

In production, the built dist/ is served by Nginx inside a Docker container (see ../Dockerfile).

VS Code + Vue (Official) (and disable Vetur).