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]>
This commit is contained in:
2026-09-16 16:12:21 +01:00
co-authored by Claude Opus 5
parent 64df70e5d2
commit 25ac1cde1c
69 changed files with 2381 additions and 1607 deletions
+39 -3
View File
@@ -154,8 +154,17 @@ services:
dockerfile: Dockerfile
container_name: "${BACKEND_HOST}"
restart: always
# MAP form, not the list form used elsewhere: this waits for db's
# healthcheck to pass, not merely for its container to start. Without it
# the Go process raced Postgres on every boot, failed its first connection,
# died, and relied on `restart: always` to try again — noisy log churn and
# a slower cold start in practice.
# `restart: always` is deliberately KEPT as the backstop: if db's health
# probe were ever to stall past compose's patience, or the DB dropped out
# later, the restart policy still recovers the backend.
depends_on:
- db
db:
condition: service_healthy
networks:
- app-network
env_file:
@@ -191,10 +200,17 @@ services:
# AUTOHEAL_CONTAINER_LABEL=all means "watch every container that defines a
# healthcheck" (i.e. backend and python) rather than only labelled ones.
# It mounts the docker socket, which is effectively root on the host — that
# is the price of the feature; keep the image pinned-ish and trusted.
# is the price of the feature. Because of that the image is pinned BY DIGEST,
# not by a floating tag: `:latest` meant any future push to Docker Hub would
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
# digest below is a multi-arch index (it includes linux/arm64, which is what
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
# time of pinning. To bump it: pull the new tag, `docker image inspect
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
# the digest here — never go back to a bare tag.
# Deliberately NOT on app-network: it talks only to the socket.
autoheal:
image: willfarrell/autoheal:latest
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
container_name: autoheal
restart: always
environment:
@@ -220,6 +236,26 @@ services:
- app-network
volumes:
- dbdata:/var/lib/postgresql/data
# Postgres is the one dependency the backend genuinely cannot start
# without, so `backend` gates on this healthcheck (condition:
# service_healthy) instead of on mere container start.
# TUNED FOR SLOW ARM HARDWARE: on a Raspberry Pi with a cold page cache a
# first-boot Postgres can take well over a minute to finish initdb/recovery
# and accept connections. start_period is the grace window during which a
# failing probe does NOT count against `retries` and does NOT mark the
# container unhealthy, so 90s costs nothing on a warm boot and prevents a
# false "unhealthy" on a cold one. After that, 10 retries at 10s gives
# another ~100s before anything gives up. `pg_isready -U $POSTGRES_USER`
# is the cheapest real readiness probe (it does a protocol-level connect,
# not just a TCP open). Note $$POSTGRES_USER: the doubled $ escapes
# compose's own interpolation so the variable is expanded by the shell
# INSIDE the container, from env_file, at probe time.
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\" -q"]
interval: 10s
timeout: 5s
retries: 10
start_period: 90s
# Admin-only DB browser, reached at /hasura/. Console and dev mode are OFF in
# production (turned on by the dev override). It is additionally gated in